当前位置:   article > 正文

RestClient 访问elasticsearch_highlevelrestclient访问es

highlevelrestclient访问es

1。引入依赖

1)引入es的RestHighLevelClient依赖:

  1. <dependency>
  2. <groupId>org.elasticsearch.client</groupId>
  3. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  4. </dependency>

2)因为SpringBoot默认的ES版本是7.6.2,所以我们需要覆盖默认的ES版本:

  1. <properties>
  2. <java.version>1.8</java.version>
  3. <elasticsearch.version>7.12.1</elasticsearch.version>
  4. </properties>

3)初始化RestHighLevelClient:

初始化的代码如下:

  1. RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
  2. HttpHost.create("http://192.168.150.101:9200")
  3. ));

2.创建索引库和删除索引库

存储的是新增索引库的语句

  1. package cn.itcast.hotel;
  2. public class HotelConstants {
  3. public static final String MAPPING_TEMPLATE = "{\n" +
  4. " \"mappings\": {\n" +
  5. " \"properties\": {\n" +
  6. " \"id\": {\n" +
  7. " \"type\": \"keyword\"\n" +
  8. " },\n" +
  9. " \"name\":{\n" +
  10. " \"type\": \"text\",\n" +
  11. " \"analyzer\": \"ik_max_word\",\n" +
  12. " \"copy_to\": \"all\"\n" +
  13. " },\n" +
  14. " \"address\":{\n" +
  15. " \"type\": \"keyword\",\n" +
  16. " \"index\": false\n" +
  17. " },\n" +
  18. " \"price\":{\n" +
  19. " \"type\": \"integer\"\n" +
  20. " },\n" +
  21. " \"score\":{\n" +
  22. " \"type\": \"integer\"\n" +
  23. " },\n" +
  24. " \"brand\":{\n" +
  25. " \"type\": \"keyword\",\n" +
  26. " \"copy_to\": \"all\"\n" +
  27. " },\n" +
  28. " \"city\":{\n" +
  29. " \"type\": \"keyword\",\n" +
  30. " \"copy_to\": \"all\"\n" +
  31. " },\n" +
  32. " \"starName\":{\n" +
  33. " \"type\": \"keyword\"\n" +
  34. " },\n" +
  35. " \"business\":{\n" +
  36. " \"type\": \"keyword\"\n" +
  37. " },\n" +
  38. " \"location\":{\n" +
  39. " \"type\": \"geo_point\"\n" +
  40. " },\n" +
  41. " \"pic\":{\n" +
  42. " \"type\": \"keyword\",\n" +
  43. " \"index\": false\n" +
  44. " },\n" +
  45. " \"all\":{\n" +
  46. " \"type\": \"text\",\n" +
  47. " \"analyzer\": \"ik_max_word\"\n" +
  48. " }\n" +
  49. " }\n" +
  50. " }\n" +
  51. "}";
  52. }

新增和删除索引库操作 

  1. import org.apache.http.HttpHost;
  2. import org.apache.http.client.methods.HttpPost;
  3. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  4. import org.elasticsearch.client.RequestOptions;
  5. import org.elasticsearch.client.RestClient;
  6. import org.elasticsearch.client.RestHighLevelClient;
  7. import org.elasticsearch.client.indices.CreateIndexRequest;
  8. import org.elasticsearch.common.xcontent.XContentType;
  9. import org.junit.jupiter.api.AfterEach;
  10. import org.junit.jupiter.api.BeforeEach;
  11. import org.junit.jupiter.api.Test;
  12. import org.springframework.boot.test.context.SpringBootTest;
  13. import java.io.IOException;
  14. @SpringBootTest
  15. class HotelSuoYinTest {
  16. private RestHighLevelClient client;
  17. @BeforeEach
  18. void setup() {
  19. this.client =
  20. new RestHighLevelClient(
  21. RestClient.builder(
  22. HttpHost.create("http://101.43.94.150:9200")
  23. ));
  24. }
  25. @AfterEach
  26. void shutdown() throws IOException {
  27. this.client.close();
  28. }
  29. // indices() 有这个,就是索引库的操作
  30. @Test
  31. void test() throws IOException {
  32. // 创建request对象
  33. CreateIndexRequest request = new CreateIndexRequest("hotel");
  34. // 准备请求的参数 dsl语句
  35. request.source(HotelConstants.MAPPING_TEMPLATE, XContentType.JSON);
  36. // 发送请求
  37. client.indices().create(request, RequestOptions.DEFAULT);
  38. }
  39. @Test
  40. void deltest() throws IOException {
  41. // 创建request对象
  42. DeleteIndexRequest request = new DeleteIndexRequest("hotel");
  43. // 发送请求
  44. client.indices().delete(request, RequestOptions.DEFAULT);
  45. }
  46. }

判断索引库是不是存在 

  1. @Test
  2. void testExistsHotelIndex() throws IOException {
  3. // 1.创建Request对象
  4. GetIndexRequest request = new GetIndexRequest("hotel");
  5. // 2.发送请求
  6. boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
  7. // 3.输出
  8. System.err.println(exists ? "索引库已经存在!" : "索引库不存在!");
  9. }

索引库操作的基本步骤:

  • 初始化RestHighLevelClient

  • 创建XxxIndexRequest。XXX是Create、Get、Delete

  • 准备DSL( Create时需要,其它是无参)

  • 发送请求。调用RestHighLevelClient#indices().xxx()方法,xxx是create、exists、delete

3.删除文档 修改文档 新增文档 批量添加文档

因为mysql查询出来的hotel信息经纬度信息是分开的,但是eleasticsearch的地理坐标要求是一个String类型,中间用逗号分开,所以要转为hotelDoc

  1. //文档,相当于mysql中的行
  2. //#查询一条文档(记录)的 dsl语句
  3. // GET /heima/_doc/1
  4. @SpringBootTest
  5. public class DocumentTest {
  6. private RestHighLevelClient client;
  7. @Autowired
  8. HotelService hotelService;
  9. // 插入新数据
  10. @Test
  11. public void testadd() throws IOException {
  12. Hotel hotel = hotelService.getById(61083L);
  13. HotelDoc hotelDoc = new HotelDoc(hotel);
  14. // 创建request,并指明要处理的索引是hotel,记录号是 hotelDoc.getId()
  15. IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
  16. request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
  17. client.index(request, RequestOptions.DEFAULT);
  18. }
  19. // 查询某条数据
  20. @Test
  21. public void testquery() throws IOException {
  22. GetRequest request = new GetRequest("hotel", "61083");
  23. GetResponse response = client.get(request, RequestOptions.DEFAULT);
  24. String json = response.getSourceAsString();
  25. HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
  26. System.out.println(hotelDoc);
  27. }
  28. //更新某条数据
  29. @Test
  30. public void testupdate() throws IOException {
  31. Hotel hotel = hotelService.getById(61083L);
  32. HotelDoc hotelDoc = new HotelDoc(hotel);
  33. UpdateRequest request = new UpdateRequest("hotel", "61083");
  34. request.doc("price", "952");
  35. request.doc("address", "北京饭店");
  36. client.update(request, RequestOptions.DEFAULT);
  37. }
  38. // 删除某条数据
  39. @Test
  40. void testDeleteDocument() throws IOException {
  41. // 1.准备Request
  42. DeleteRequest request = new DeleteRequest("hotel", "61083");
  43. // 2.发送请求
  44. client.delete(request, RequestOptions.DEFAULT);
  45. }
  46. @Test
  47. void testpiliangadd() throws IOException {
  48. List<Hotel> hotels = hotelService.list();
  49. BulkRequest request = new BulkRequest();
  50. for (Hotel hotel : hotels) {
  51. HotelDoc hotelDoc = new HotelDoc(hotel);
  52. request.add(new IndexRequest("hotel")
  53. .id(hotelDoc.getId() + "")
  54. .source(JSON.toJSONString(hotelDoc)
  55. , XContentType.JSON));
  56. }
  57. client.bulk(request, RequestOptions.DEFAULT);
  58. }
  59. @BeforeEach
  60. void setup() {
  61. this.client =
  62. new RestHighLevelClient(
  63. RestClient.builder(
  64. HttpHost.create("http://101.43.94.150:9200")
  65. ));
  66. }
  67. @AfterEach
  68. void shutdown() throws IOException {
  69. this.client.close();
  70. }
  71. }

4.查询文档

  1. package cn.itcast.hotel;
  2. import cn.itcast.hotel.pojo.HotelDoc;
  3. import com.alibaba.fastjson.JSON;
  4. import org.apache.http.HttpHost;
  5. import org.elasticsearch.action.search.SearchRequest;
  6. import org.elasticsearch.action.search.SearchResponse;
  7. import org.elasticsearch.client.RequestOptions;
  8. import org.elasticsearch.client.RestClient;
  9. import org.elasticsearch.client.RestHighLevelClient;
  10. import org.elasticsearch.index.query.BoolQueryBuilder;
  11. import org.elasticsearch.index.query.QueryBuilder;
  12. import org.elasticsearch.index.query.QueryBuilders;
  13. import org.elasticsearch.search.SearchHit;
  14. import org.elasticsearch.search.SearchHits;
  15. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  16. import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
  17. import org.elasticsearch.search.sort.SortOrder;
  18. import org.junit.jupiter.api.AfterEach;
  19. import org.junit.jupiter.api.BeforeEach;
  20. import org.junit.jupiter.api.Test;
  21. import org.springframework.boot.test.context.SpringBootTest;
  22. import java.io.IOException;
  23. import java.util.Map;
  24. @SpringBootTest
  25. public class QueryTest {
  26. private RestHighLevelClient client;
  27. //查询全部文档
  28. @Test
  29. void testmatchall() throws IOException {
  30. // 1. 准备request
  31. SearchRequest request = new SearchRequest("hotel");
  32. // 2. 准备dsl
  33. request.source().query(QueryBuilders.matchAllQuery());
  34. // 3.发送请求
  35. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  36. handleResponse(response);
  37. }
  38. //全文检索查询
  39. @Test
  40. void testquerycheck() throws IOException {
  41. // 1. 准备request
  42. SearchRequest request = new SearchRequest("hotel");
  43. // 2. 准备dsl
  44. request.source().query(QueryBuilders.matchQuery("all", "如家"));
  45. // 3.发送请求
  46. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  47. handleResponse(response);
  48. }
  49. //boolean复合查询
  50. @Test
  51. void testBool() throws IOException {
  52. // 1.准备Request
  53. SearchRequest request = new SearchRequest("hotel");
  54. // 2.准备DSL
  55. // 2.1.准备BooleanQuery
  56. BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
  57. // 2.2.添加term
  58. boolQuery.must(QueryBuilders.termQuery("city", "上海"));
  59. // 2.3.添加range
  60. boolQuery.filter(QueryBuilders.rangeQuery("price").lte(250));
  61. // 关联查询条件
  62. request.source().query(boolQuery);
  63. // 3.发送请求
  64. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  65. // 4.解析响应
  66. handleResponse(response);
  67. }
  68. //查询后排序和按页查询 el的分页查询是查询所有结果之后再分页。
  69. @Test
  70. void testpageandsort() throws IOException {
  71. // 页码,每页大小
  72. int pagenum = 1, pagesize = 5;
  73. // 1.准备Request
  74. SearchRequest request = new SearchRequest("hotel");
  75. request.source().query(QueryBuilders.matchAllQuery());
  76. request.source().sort("price", SortOrder.ASC);
  77. // 前端传过来的是页码和每页大小 ,算一下从第多少条后开始分页
  78. request.source().from((pagenum - 1) * pagesize);
  79. // 页大小
  80. request.source().size(pagesize);
  81. // 3.发送请求
  82. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  83. // 4.解析响应
  84. handleResponse(response);
  85. }
  86. //查询后高亮显示
  87. @Test
  88. void testhightlight() throws IOException {
  89. // 1.准备Request
  90. SearchRequest request = new SearchRequest("hotel");
  91. request.source().query(QueryBuilders.matchQuery("brand", "如家"));
  92. // requireFieldMatch(false) 搜索条件brand和高亮的属性name设为不一致
  93. request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));
  94. // 3.发送请求
  95. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  96. handleHeightLightResponse(response);
  97. }
  98. // 高亮查询
  99. private void handleHeightLightResponse(SearchResponse response) {
  100. // 4.解析响应
  101. SearchHits searchHits = response.getHits();
  102. // 4.1.获取总条数
  103. long total = searchHits.getTotalHits().value;
  104. System.out.println("共搜索到" + total + "条数据");
  105. // 4.2.文档数组
  106. SearchHit[] hits = searchHits.getHits();
  107. // 4.3.遍历
  108. for (SearchHit hit : hits) {
  109. // 获取文档source
  110. String json = hit.getSourceAsString();
  111. // 反序列化
  112. HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
  113. // 获取高亮
  114. Map<String, HighlightField> highlightFields = hit.getHighlightFields();
  115. HighlightField highlightField = highlightFields.get("name");
  116. String name = highlightField.getFragments()[0].toString();
  117. hotelDoc.setName(name);
  118. System.out.println(hotelDoc);
  119. }
  120. }
  121. // 解析响应函数
  122. private void handleResponse(SearchResponse response) {
  123. // 4.解析响应
  124. SearchHits searchHits = response.getHits();
  125. // 4.1.获取总条数
  126. long total = searchHits.getTotalHits().value;
  127. System.out.println("共搜索到" + total + "条数据");
  128. // 4.2.文档数组
  129. SearchHit[] hits = searchHits.getHits();
  130. // 4.3.遍历
  131. for (SearchHit hit : hits) {
  132. // 获取文档source
  133. String json = hit.getSourceAsString();
  134. // 反序列化
  135. HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
  136. // System.out.println("hotelDoc = " + hotelDoc);
  137. }
  138. }
  139. @BeforeEach
  140. void setup() {
  141. this.client =
  142. new RestHighLevelClient(
  143. RestClient.builder(
  144. HttpHost.create("http://101.43.94.150:9200")
  145. ));
  146. }
  147. @AfterEach
  148. void shutdown() throws IOException {
  149. this.client.close();
  150. }
  151. }

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

闽ICP备14008679号