SpringBoot通过Jest整合EasticSearch案例
一、搭建环境
1)、引入相关Jar
<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>5.3.3</version>
</dependency>
2)、配置 EasticSearch访问uri
spring.elasticsearch.jest.uris=http://192.168.43.118:9200/
二、测试是否整合成功
1)、编写一个用于测试的bean,设置id为JestId
public class Article {
@JestId
private Integer id;
private String author;
private String title;
private String content;
public Integer getId() {
return id;
}
...
2)、编写保存索引的单元测试
@Autowired
JestClient jestClient;
/**
* 1、给ES中索引(保存)一个文档
*/
@Test
public void addESTest(){
//封装要保存的内容
Article article = new Article();
article.setId(1);
article.setTitle("Java入门到放弃");
article.setAuthor("张三");
article.setContent("Java是蓝领搬砖工!");
//构建一个索引
Index index = new Index.Builder(article).index("zhq").type("news").build();
try {
//执行保存索引
jestClient.execute(index);
} catch (IOException e) {
e.printStackTrace();
}
}
浏览器访问看是否保存成功:
2)、编写全文搜索单元测试
@Autowired
JestClient jestClient;
/**
* 2、全文搜索测试
*/
@Test
public void searchESTest(){
//查询条件表达式
String json="{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"content\" : \"蓝领\"\n" +
" }\n" +
" }\n" +
"}";
//构建查询条件
Search search = new Search.Builder(json).addIndex("zhq").addType("news").build();
try {
//执行查询
SearchResult result = jestClient.execute(search);
System.out.println("result:"+result.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}
}
查询结果: