SpringBoot 整合 Elasticsearch
Posted Fisher3652
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot 整合 Elasticsearch相关的知识,希望对你有一定的参考价值。
目录
- 1. 引入依赖
- 2. 添加配置文件
- 3. 创建ES配置类
- 4. swagger配置类
- 5. 消息返回体
- 6. 创建保存文档的实体
- 7. 索引操作service
- 8. 创建索引controller
- 9. 测试索引操作
- 10. 文档操作service
- 11. 创建文档controller
- 12. 测试文档操作
- 13. search操作service
- 14. search操作controller
- 15. 测试search接口操作
- 16. 聚集操作service
- 17. 聚集查询controller
- 18. 测试聚集查询
- 代码下载地址
1. 引入依赖
- 这里使用springboot 2.5.4 版本,es使用 7.14.0 版本
- 可以参考es 官方文档 ,在Java REST Client 下找到对应的版本
- 这里使用7.14.0的 Java High Level REST Client
- 右下角有详细的使用说明
- 需要同时使用elasticsearch和elasticsearch-rest-high-level-client
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- es-->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.14.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.14.0</version>
</dependency>
<!-- fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.57</version>
</dependency>
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. 添加配置文件
#es
elasticsearch.host=192.168.42.111
elasticsearch.port=9200
#jackson
spring.jackson.default-property-inclusion=non_null
3. 创建ES配置类
package com.example.demo.config;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ESConfig
@Value("$elasticsearch.host")
private String host;
@Value("$elasticsearch.port")
private int port;
@Bean
public RestHighLevelClient highLevelClient()
HttpHost httpHost = new HttpHost(host, port, "http");
// 如果是集群模式,可以添加HttpHost数组
RestClientBuilder restClientBuilder = RestClient.builder(httpHost);
return new RestHighLevelClient(restClientBuilder);
4. swagger配置类
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig
@Bean
public Docket createRestApi()
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo")).build();
private ApiInfo apiInfo()
return new ApiInfoBuilder().version("1.0").build();
5. 消息返回体
- 用来包装返回数据
package com.example.demo.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AjaxResult<T>
private Integer code;
private String message;
private T data;
public static <T> AjaxResult<T> ok(T data)
return new AjaxResult<>(0, "success", data);
public static <T> AjaxResult<T> error(T data)
return new AjaxResult<>(1, "error", data);
6. 创建保存文档的实体
package com.example.demo.vo;
import lombok.Data;
@Data
public class User
private String firstName;
private String secondName;
private String content;
private Integer age;
7. 索引操作service
- 这里对索引进行创建,判断索引是否存在和删除索引
package com.example.demo.service;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
@Service
public class OperateIndex
@Resource
private RestHighLevelClient restHighLevelClient;
public boolean createIndex(String indexName)
boolean acknowledged = false;
try
/**
* 可以根据需要设置字段属性,如果不设置,es会根据添加文档时的字段类型自动推断
* put /indexName/_mapping
*
* "properties":
* "firstName":
* "type": "keyword"
* ,
* "secondName":
* "type": "keyword"
* ,
* "age":
* "type": "integer"
* ,
* "content":
* "type": "text"
*
*
*
*/
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
.startObject()
.field("properties").startObject()
.field("firstName").startObject().field("type", "keyword").endObject()
.field("secondName").startObject().field("type", "keyword").endObject()
.field("age").startObject().field("type", "integer").endObject()
.field("content").startObject().field("type", "text").endObject()
.endObject()
.endObject();
CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
createIndexRequest.mapping(xContentBuilder);
CreateIndexResponse createIndexResponse =
restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
acknowledged = createIndexResponse.isAcknowledged();
catch (IOException e)
e.printStackTrace();
return acknowledged;
public boolean isIndexExists(String indexName)
GetIndexRequest getIndexRequest = new GetIndexRequest(indexName);
getIndexRequest.humanReadable(true);
boolean exists = false;
try
exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
catch (IOException e)
e.printStackTrace();
return exists;
public boolean deleteIndex(String indexName)
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName);
// 忽略索引不存在的情况;如果不设置,索引不存在时,会报错
deleteIndexRequest.indicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN);
boolean acknowledged = false;
try
AcknowledgedResponse delete =
restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
acknowledged = delete.isAcknowledged();
catch (IOException e)
e.printStackTrace();
return acknowledged;
8. 创建索引controller
package com.example.demo.controller;
import com.example.demo.service.OperateIndex;
import com.example.demo.vo.AjaxResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("/index")
public class IndexController
@Resource
private OperateIndex operateIndex;
/*
* 创建索引
*/
@PostMapping("/create")
public AjaxResult<Boolean> createIndex(@RequestParam String indexName)
return AjaxResult.ok(operateIndex.createIndex(indexName));
/**
* 索引是否存在
*/
@PostMapping("/exit")
public AjaxResult<Boolean> indexExit(@RequestParam String indexName)
return AjaxResult.ok(operateIndex.isIndexExists(indexName));
/**
* 删除索引
*/
@PostMapping("/delete")
public AjaxResult<Boolean> deleteIndex(@RequestParam String indexName)
return AjaxResult.ok(operateIndex.deleteIndex(indexName));
9. 测试索引操作
9.1 创建索引
- 查看是否创建成功
9.2 判断索引是否存在
9.3 删除索引
- 再次查看索引是否存在
10. 文档操作service
package com.example.demo以上是关于SpringBoot 整合 Elasticsearch的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot系列八:SpringBoot整合消息服务(SpringBoot 整合 ActiveMQSpringBoot 整合 RabbitMQSpringBoot 整合 Kafka)
[SpringBoot系列]SpringBoot如何整合SSMP