SpringBoot整合ElasticSearch
-
引入对应的pom依赖(使用es-rest-high-level-client来调用es)
<!-- es -->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
</exclusion>
<exclusion>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.17.6</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.17.6</version>
</dependency>
注意:这里需要观察里面对应es的版本,如果与你服务器上安装的es版本不一样的话,会报找不到包的异常。
如:
Java ElasticsearchException.toXContent
查看版本对不对应看引入elasticsearch-rest-high-level-client
,如果不对应排除掉,重新引入对应的。
-
设置配置类
/**
* @Description es请求配置类
* es添加了安全访问规则,访问es需要添加一个安全头,就可以通过requestOptions设置
* @Author lh
* @Date 2022/9/21 21:16
*/
-
测试保存数据
结果:
IndexResponse[index=user,type=_doc,id=1,version=3,result=updated,seqNo=2,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
-
测试获取数据
{"took":24,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1,"relation":"eq"},"max_score":0.8630463,"hits":[{"_index":"user","_type":"_doc","_id":"1","_score":0.8630463,"_source":{"age":18,"gender":"男","userName":"李嘉图"}}]}}