当前位置:   article > 正文

springBoot集成Elasticsearch_elasticsearch http.host

elasticsearch http.host

记录一下springBoot集成Elasticsearch的基本使用。

目录

第一步:pom文件添加依赖

第二步:配置文件添加es配置

第三步:配置类中配置

第四步:编写常用的增删查改方法


RestHighLevelClient是官方指定的连接API, 在springBoot项目中使用RestHighLevelClient来连接es并实现增删改查。

第一步:pom文件添加依赖

  1. <!-- 其他依赖这里省略 -->
  2. <properties>
  3. <elasticsearch.version>7.4.2</elasticsearch.version>
  4. </properties>
  5. <dependencies>
  6. <!-- ElasticSearch 相关依赖 start-->
  7. <dependency>
  8. <groupId>org.elasticsearch.client</groupId>
  9. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  10. <version>${elasticsearch.version}</version>
  11. </dependency>
  12. <dependencies>

第二步:配置文件添加es配置

  1. ### ES连接信息配置 ###
  2. # 单机版ip
  3. elasticsearch.port=127.0.0.1
  4. # 单机版端口号
  5. elasticsearch.host=9200
  6. # 是否开启集群模式
  7. opencluster=false
  8. #集群模式各节点IP和端口号
  9. elasticsearch.hostAndPorts=127.0.0.1:9201;127.0.0.1:9202;127.0.0.1:9203

第三步:配置类中配置

配置类中对RestHighLevelClient对象进行初始化并注入到容器

  1. package com.zhh.demo.commons.elasticsearch.config;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.client.RestClient;
  4. import org.elasticsearch.client.RestHighLevelClient;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. /**
  11. * ES基础配置
  12. * @author zhaoheng
  13. * @date 2021/05/24
  14. */
  15. @Configuration
  16. public class ElasticSearchConfig {
  17. protected static final Logger logger = LoggerFactory.getLogger(ElasticSearchConfig.class);
  18. /** 单机版端口号 */
  19. @Value("${elasticsearch.host}")
  20. public String host;
  21. /** 单机版ip */
  22. @Value("${elasticsearch.port}")
  23. public int port;
  24. /** 是否开启集群模式 */
  25. @Value("${opencluster}")
  26. public boolean openCluster;
  27. /** 集群各节点的IP和端口号 */
  28. @Value("${elasticsearch.hostAndPorts}")
  29. private String hostAndPorts;
  30. /**
  31. * ES客户端配置并注入到容器
  32. */
  33. @Bean
  34. public RestHighLevelClient restHighLevelClient() {
  35. RestHighLevelClient client = null;
  36. if (openCluster) {
  37. logger.info("开始初始化集群模式RestHighLevelClient连接...");
  38. final HttpHost[] httpHosts = getHttpHosts();
  39. if (httpHosts != null && httpHosts.length > 0) {
  40. logger.info("获取到的配置文件为空");
  41. return client;
  42. }
  43. try {
  44. client = new RestHighLevelClient(RestClient.builder(httpHosts));
  45. } catch (Exception ex) {
  46. logger.error("初始化ES连接失败,失败信息:{}", ex.getMessage());
  47. }
  48. } else {
  49. final HttpHost singleNode = new HttpHost(host, port, "http");
  50. logger.info("开始初始化非集群模式RestHighLevelClient连接...");
  51. client = new RestHighLevelClient(
  52. RestClient.builder(singleNode));
  53. }
  54. return client;
  55. }
  56. /**
  57. * 获取配置文件中的es服务器地址信息
  58. * @return
  59. */
  60. private HttpHost[] getHttpHosts() {
  61. HttpHost[] httpHosts = null;
  62. if (hostAndPorts != null && !"".equals(hostAndPorts)) {
  63. final String[] hostAndPort = hostAndPorts.split(";");
  64. if (httpHosts != null && hostAndPort.length > 0) {
  65. httpHosts = new HttpHost[hostAndPort.length];
  66. for (int i = 0; i < hostAndPort.length; i++) {
  67. String hostAndPortItem = hostAndPort[i];
  68. final String[] singleHostAndPort = hostAndPortItem.split(":");
  69. final String hostIP = singleHostAndPort[0];
  70. final String port = singleHostAndPort[1];
  71. logger.info("获取到的主机是:host:{},port:{}", hostIP, port);
  72. final HttpHost nodes = new HttpHost(hostIP, Integer.parseInt(port), "http");
  73. httpHosts[i] = nodes;
  74. }
  75. }
  76. }
  77. return httpHosts;
  78. }
  79. }

第四步:编写常用的增删查改方法

后续直接调用即可

  1. package com.zhh.demo.commons.elasticsearch;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.zhh.demo.commons.utils.JSONDataUtil;
  5. import com.zhh.demo.commons.utils.ToolUtil;
  6. import com.zhh.demo.domain.ProductESDTO;
  7. import org.elasticsearch.action.bulk.BulkRequest;
  8. import org.elasticsearch.action.bulk.BulkResponse;
  9. import org.elasticsearch.action.delete.DeleteRequest;
  10. import org.elasticsearch.action.delete.DeleteResponse;
  11. import org.elasticsearch.action.index.IndexRequest;
  12. import org.elasticsearch.action.index.IndexResponse;
  13. import org.elasticsearch.action.search.SearchRequest;
  14. import org.elasticsearch.action.search.SearchResponse;
  15. import org.elasticsearch.client.RequestOptions;
  16. import org.elasticsearch.client.RestHighLevelClient;
  17. import org.elasticsearch.client.indices.CreateIndexRequest;
  18. import org.elasticsearch.client.indices.CreateIndexResponse;
  19. import org.elasticsearch.client.indices.GetIndexRequest;
  20. import org.elasticsearch.common.settings.Settings;
  21. import org.elasticsearch.common.xcontent.XContentBuilder;
  22. import org.elasticsearch.common.xcontent.XContentFactory;
  23. import org.elasticsearch.common.xcontent.XContentType;
  24. import org.elasticsearch.index.query.QueryBuilders;
  25. import org.elasticsearch.index.reindex.BulkByScrollResponse;
  26. import org.elasticsearch.index.reindex.DeleteByQueryRequest;
  27. import org.elasticsearch.rest.RestStatus;
  28. import org.elasticsearch.search.SearchHit;
  29. import org.elasticsearch.search.SearchHits;
  30. import org.elasticsearch.search.builder.SearchSourceBuilder;
  31. import org.slf4j.Logger;
  32. import org.slf4j.LoggerFactory;
  33. import org.springframework.beans.factory.annotation.Autowired;
  34. import org.springframework.stereotype.Component;
  35. import java.io.IOException;
  36. import java.util.ArrayList;
  37. import java.util.HashMap;
  38. import java.util.List;
  39. import java.util.Map;
  40. /**
  41. * 商品ES搜索相关
  42. * @author zhaoheng
  43. * @date 2021/05/24
  44. */
  45. @Component
  46. public class ProductServiceEs {
  47. private static final Logger logger = LoggerFactory.getLogger(ProductServiceEs.class);
  48. /** 索引名称 */
  49. public static final String MY_INDEX ="my_index";
  50. @Autowired
  51. private RestHighLevelClient restHighLevelClient;
  52. /**
  53. * 创建索引并添加mapping字段映射
  54. * @throws Exception
  55. */
  56. public boolean createIndex()throws Exception{
  57. logger.info("创建ES索引开始");
  58. CreateIndexRequest request = new CreateIndexRequest(MY_INDEX);
  59. request.mapping(this.mappingBuilder());
  60. // 设置分片和分片副本
  61. request.settings(Settings.builder()
  62. .put("index.number_of_shards",5)
  63. .put("index.number_of_replicas",1));
  64. CreateIndexResponse response = restHighLevelClient.indices().create(request,RequestOptions.DEFAULT);
  65. logger.info("创建ES索引结束,结果:{}",response.isAcknowledged());
  66. return response.isAcknowledged();
  67. }
  68. /**
  69. * es的字段mapping设置
  70. * 设置es索引字段属性,是否分词,使用的什么分词器
  71. * @return
  72. * @throws Exception
  73. */
  74. private XContentBuilder mappingBuilder() throws Exception{
  75. XContentBuilder xContentBuilder = XContentFactory.jsonBuilder().prettyPrint()
  76. .startObject()
  77. .startObject("properties")
  78. // 商品id
  79. .startObject("productId")
  80. // 字段类型text类型,不需要建立分词索引
  81. .field("type", "keyword")
  82. .endObject()
  83. // 商品名称
  84. .startObject("productName")
  85. // 字段类型text类型,商品名称需要根据关键字搜索,使用需要设置成text类型,需要建立索引分词
  86. .field("type", "text")
  87. /**
  88. * index定义字段的分析类型以及检索方式,控制字段值是否被索引.他可以设置成 true 或者 false。
  89. * 没有被索引的字段将无法搜索,默认都是true
  90. * */
  91. .field("index", "true")
  92. // 使用ik分词器
  93. .field("analyzer","ik_max_word")
  94. .endObject()
  95. // 搜索提示、自动补全,参考es的Completion Suggester api
  96. .startObject("titleList")
  97. .field("type", "completion")
  98. .endObject()
  99. .endObject()
  100. .endObject();
  101. return xContentBuilder;
  102. }
  103. /**
  104. * 判断索引是否存在
  105. * @return
  106. * @throws Exception
  107. */
  108. public Boolean isExistsIndex() throws Exception{
  109. GetIndexRequest request = new GetIndexRequest(MY_INDEX);
  110. return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
  111. }
  112. /**
  113. * id相同,数据存在就覆盖,不存在就添加
  114. * @throws IOException
  115. */
  116. public boolean save(ProductESDTO product) throws Exception {
  117. logger.info("ES添加数据,data:{}", JSONDataUtil.toJSONStr(product));
  118. IndexRequest request = new IndexRequest(MY_INDEX);
  119. request.id(product.getProductId());
  120. request.source(JSONDataUtil.toJSONStr(product), XContentType.JSON);
  121. // 添加数据索引
  122. IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
  123. logger.info(indexResponse.toString());
  124. return RestStatus.CREATED.equals(indexResponse.status());
  125. }
  126. /**
  127. * 批量添加数据
  128. * @param list
  129. * @throws Exception
  130. */
  131. public boolean bulkSave(List<ProductESDTO> list) throws Exception {
  132. logger.info("ES-批量添加数据start");
  133. IndexRequest request = null;
  134. BulkRequest bulkRequest = new BulkRequest();
  135. for (ProductESDTO product : list) {
  136. request = new IndexRequest(MY_INDEX);
  137. request.id(String.valueOf(product.getProductId()));
  138. request.source(JSONDataUtil.toJSONStr(product), XContentType.JSON);
  139. bulkRequest.add(request);
  140. }
  141. BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
  142. logger.info("ES-批量添加数据end");
  143. return !bulkResponse.hasFailures();
  144. }
  145. /**
  146. * 批量删除数据
  147. * @param productIds
  148. * @throws Exception
  149. */
  150. public boolean bulkDelete(List<String> productIds) throws Exception {
  151. logger.info("批量删除数据start");
  152. DeleteRequest request = null;
  153. BulkRequest bulkRequest = new BulkRequest();
  154. for (String product : productIds) {
  155. request = new DeleteRequest(MY_INDEX);
  156. request.id(product);
  157. bulkRequest.add(request);
  158. }
  159. BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
  160. logger.info("批量删除数据end");
  161. return !bulkResponse.hasFailures();
  162. }
  163. /**
  164. * 根据id删除数据
  165. * @param productId 商品id
  166. * @throws Exception
  167. */
  168. public boolean deleteById(String productId) throws Exception{
  169. DeleteRequest deleteRequest = new DeleteRequest(MY_INDEX);
  170. deleteRequest.id(productId);
  171. DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
  172. return RestStatus.OK.equals(deleteResponse.status());
  173. }
  174. /**
  175. * 删除全部数据
  176. * @throws Exception
  177. */
  178. public boolean deleteAllData() throws Exception{
  179. logger.info("删除索引{}的全部数据",MY_INDEX);
  180. DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(MY_INDEX);
  181. // 删除所有匹配上的数据,查询全部,即删除全部
  182. deleteByQueryRequest.setQuery(QueryBuilders.matchAllQuery());
  183. BulkByScrollResponse deleteResponse = restHighLevelClient.deleteByQuery(deleteByQueryRequest,RequestOptions.DEFAULT);
  184. logger.info("删除索引{}的全部数据,删除条数:{}",MY_INDEX,deleteResponse.getTotal());
  185. return RestStatus.OK.equals(deleteResponse.getStatus());
  186. }
  187. /**
  188. * 搜索并且获取结果
  189. *
  190. * @param searchSourceBuilder
  191. * @param indexName
  192. * @return
  193. */
  194. private SearchResponse searchAndGetResult(SearchSourceBuilder searchSourceBuilder, String indexName) throws IOException {
  195. SearchRequest searchRequest = new SearchRequest();
  196. searchRequest.indices(indexName);
  197. searchRequest.source(searchSourceBuilder);
  198. SearchResponse response = null;
  199. logger.info("ES查询的DSL语句为:{}", searchSourceBuilder.toString());
  200. try {
  201. response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  202. } catch (Exception ex) {
  203. logger.error("ES查询时出错,出错信息为:{}", ex.getMessage());
  204. throw ex;
  205. }
  206. if (ToolUtil.isNotEmpty(response)) {
  207. logger.debug("ES查询返回的数据为:{}", response.toString());
  208. }
  209. return response;
  210. }
  211. /**
  212. * 获取处理过的查询数据
  213. *
  214. * @param response
  215. * @return
  216. */
  217. private static Map<String, Object> getJsonArray(SearchResponse response) {
  218. final JSONArray jsonArray = new JSONArray();
  219. final Map<String, Object> resultMap = new HashMap<>();
  220. if (ToolUtil.isEmpty(response)) {
  221. return resultMap;
  222. }
  223. final SearchHits hits = response.getHits();
  224. Long count = 0L;
  225. List<String> ids = new ArrayList<>();
  226. if (ToolUtil.isNotEmpty(hits)) {
  227. count = hits.getTotalHits().value;
  228. final SearchHit[] hitsArray = hits.getHits();
  229. if (ToolUtil.isNotEmpty(hitsArray)) {
  230. for (SearchHit hit : hitsArray) {
  231. final Map<String, Object> sourceAsMap = hit.getSourceAsMap();
  232. final String id = hit.getId();
  233. final JSONObject jsonObject = new JSONObject();
  234. for (Map.Entry<String, Object> entry : sourceAsMap.entrySet()) {
  235. jsonObject.put(entry.getKey(), entry.getValue());
  236. }
  237. jsonArray.add(jsonObject);
  238. ids.add(id);
  239. }
  240. }
  241. }
  242. // 满足条件的数据总条数
  243. resultMap.put("total", count);
  244. // 查询得到的数据
  245. resultMap.put("rows", jsonArray);
  246. // 查询到的数据的id集合
  247. resultMap.put("ids", ids);
  248. return resultMap;
  249. }
  250. }

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/68759
推荐阅读
相关标签
  

闽ICP备14008679号