概述
全文检索是程序员开发过程中常见的需求之一,开源的Elasticsearch是目前全文搜索引擎的首选,常用于快速存储、搜索和分析海量数据,Elasticsearch封装了Lucene,提供REST API操作接口,使用方便,本文介绍SpringBoot2.3.0整合Elasticsearch7.6.2,为了方便测试,持久层使用Mybatis-Plus,测试使用Swagger3.0。若需要了解SpringBoot整合Mybtis-Plus相关内容,请阅读另一篇SpringBoot2.3.0整合MyBatis-Plus3.4.0和Swagger3.0
springboot中访问elasticsearch有以下几种方式:
- JestClient:非官方,更新慢
- RestTemplate:模拟HTTP请求,ES很多操作需要自己封装,较麻烦
- HttpClient:同上
- Elasticsearch-Rest-Client:官方RestClient,封装了ES操作,API层次分明,上手简单
引入相关依赖
核心依赖如下:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.2</version>
</dependency>
配置文件
@Configuration
public class ElasticsearchConfig {
public static final RequestOptions COMMON_OPTIONS;
static {
RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
COMMON_OPTIONS = builder.build();
}
@Bean
public RestHighLevelClient restClient() {
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("192.168.108.11", 9200, "http")));
return client;
}
}
业务层代码
public DocWriteResponse.Result indexElasticsearchData(String index, List<SysUser> userList) {
IndexRequest request = new IndexRequest(index);
DocWriteResponse.Result result = null;
try {
for (SysUser user : userList) {
request.id(String.valueOf(user.getId()));
String esStr = JSON.toJSONString(user);
request.source(esStr, XContentType.JSON);
IndexResponse response = restHighLevelClient.index(request, ElasticsearchConfig.COMMON_OPTIONS);
result = response.getResult();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
控制层代码
@PostMapping("/indexElasticsearchData")
@ApiOperation(value = "将用户信息保存进es中")
public AjaxResult indexElasticsearchData() throws IOException {
List<SysUser> userList = userService.list(null);
DocWriteResponse.Result result = userService.indexElasticsearchData("sysuser", userList);
return AjaxResult.ok().data("result", result);
}
完整代码请参考码云地址