整合Elasticsearch,工程的创建
步骤如下:
搭建好,工程目录如下:
当pom文件下载完毕后,我们可以看elasticsearch的源代码
接着,我们需要在pom文件引入jest的jar文件
<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>5.3.3</version>
</dependency>
查看jestClient的参数是否复活,快捷键(ctrl+shift+n)搜索jestAutoConfiguration的源代码即可,如图所示:
所以,我们需要在application.properties文件下配置以下参数:
spring.elasticsearch.rest.uris=http://192.168.219.5:9200
接着,我们需要在JestAutoConfiguration源码下的启动,这是交互启动
日志正常打印信息0k:
接下来,我们需要在test目录下的SpringbootElasticApplicationTests类做单元测试
前提需要创建bean的pojo实体类:Article类
Article.java
package com.study.elastic.bean;
import io.searchbox.annotations.JestId;
public class Article {
@JestId
private Integer id;
private String author;
private String title;
private String content;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
接着,我们需要在test目录下的SpringbootElasticApplicationTests类做单元测试的代码编写:
package com.study.elastic;
import com.study.elastic.bean.Article;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.SearchResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
class SpringbootElasticApplicationTests {
@Autowired
JestClient jestClient;
@Test
void contextLoads() {
//1、给Es中索引(保存)一个文档
Article article = new Article();
article.setId(1);
article.setTitle("好消息");
article.setAuthor("zhangsan");
article.setContent("Hello World");
//构建一个索引功能
Index index = new Index.Builder(article).index("atguigu").type("news").build();
//执行
try {
//执行
jestClient.execute(index);
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行单元测试:contextLoads
控制台日志打印的信息,出错信息:
找了一下,发现配置文件写错了
spring.elasticsearch.jest.uris=http://192.168.219.5:9200
重新运行,控制台日志信息打印:
访问服务:
http://192.168.219.5:9200/atguigu/news/1
接着,我们也可以尝试写一个测试搜索的单元测试
//测试搜索
@Test
public void search(){
//查询表达式
String json ="{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"content\" : \"hello\"\n" +
" }\n" +
" }\n" +
"}";
//更多操作:https://github.com/searchbox-io/Jest/tree/master/jest
//构建搜索功能
Search search = new Search.Builder(json).addIndex("atguigu").addType("news").build();
//执行
try {
SearchResult result = jestClient.execute(search);
System.out.println(result.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
启动运行单元测试search
控制台日志打印出来的信息