springboot整合ES的基本操作

如题所述

第1个回答  2022-06-22
springboot整合ES的基本操作

1,如何整合引入依赖坐标

2,简单的进行测试

首先要明确springboot对于elasticsearch的high-level并没有进行整合,这就表明我们需要手动导入坐标依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>

接下来我们对elasticsearch进行测试

首先我们要测试是否可以开启客户端

@BeforeEach
void setUp() {

客户端测试成功后我们再进行第一步简单操作建立一个索引
@Test
void contextLoads() throws IOException {

//这一段是对mappings进行设置字段和分子器
String json="{\n" +
" "mappings":{\n" +
" "properties":{\n" +
" "id":{\n" +
" "type":"keyword"\n" +
" },\n" +
" "name":{\n" +
" "type":"text",\n" +
" "analyzer":"ik_max_word",\n" +
" "copy_to":"all"\n" +
" },\n" +
" "type":{\n" +
" "type":"keyword"\n" +
" },\n" +
" "description":{\n" +
" "type":"text",\n" +
" "analyzer":"ik_max_word",\n" +
" "copy_to":"all"\n" +
" },\n" +
" "all":{\n" +
" "type":"text",\n" +
" "analyzer":"ik_max_word"\n" +
" }\n" +
"\n" +
"\n" +
" }\n" +
" }\n" +
"\n" +
"\n" +
"}";
//request.source()是对请求中参数的设置
request.source(json,XContentType.JSON);
//调用indices方法进行索引的创建
/*
* 这里的request代表我们需要发送一个请求
* RequestOptions.DEFAULT代表这里我们需要一个请求参数,我们这里直接默认就好了
* */
client.indices().create(request,RequestOptions.DEFAULT);
}
索引建立完毕后我们再添加文档

对于文档的添加我们有两种方式第一种就是单个添加

//这里我直接用了我mysql中的数据
//添加文档 利用json的转换 直接用mysql里面的数据
@Test
void createDoc() throws IOException {
book book = bookDao.selectById(1);
System.out.println(book);
IndexRequest request =new IndexRequest("books").id(book.getId().toString());
//将得到的数据转换成json格式
String json= JSON.toJSONString(book);
request.source(json,XContentType.JSON);
//调用index进行文档的添加
client.index(request,RequestOptions.DEFAULT);
}
第二种就是批量添加文档操作

//批量添加文档
@Test
void createDocMany() throws IOException {

在接下来就是查询了

先来个根据id查询

//查询
//按照id查询
@Test
void get() throws IOException {

再然后是我们日后常用到的条件查询了

//条件查询
@Test
void ifsearch() throws IOException {

// System.out.println(sourceAsString);
System.out.println(book);