当前位置:   article > 正文

SpringBoot整合ES_springboot 集成es

springboot 集成es

1.引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    <version>2.6.3</version>
</dependency>

2.config配置文件

  1. @Configuration
  2. public class RestClientConfig extends AbstractElasticsearchConfiguration {
  3. @Override
  4. @Bean
  5. public RestHighLevelClient elasticsearchClient() {
  6. final ClientConfiguration clientConfiguration =ClientConfiguration.builder()
  7. .connectedTo("xx.xxx.xxx.xx:9200") //地址
  8. .build();
  9. return RestClients.create(clientConfiguration).rest();
  10. }
  11. }

         会返回两个客户端对象,分别是ElasticsearchOperations和RestHighLevelClient(更推荐使用)。前者是通过面向对象的形式来操作的,后者是通过客户端的方式操作的。

3.索引相关操作

  1. /*
  2. 索引相关操作
  3. */
  4. public class Test1 {
  5. RestHighLevelClient restHighLevelClient;
  6. @Before
  7. public void init(){
  8. final ClientConfiguration clientConfiguration =ClientConfiguration.builder()
  9. .connectedTo("xx.xxxx.xxx.xx:xxxx")
  10. .build();
  11. this.restHighLevelClient = RestClients.create(clientConfiguration).rest();
  12. }
  13. @Test//创建索引
  14. public void createIndex() throws IOException {
  15. CreateIndexRequest createIndexRequest = new CreateIndexRequest("products");
  16. //指定映射 参数1:指定映射json结构 参数2:指定数据类型
  17. createIndexRequest.mapping("{\n" +
  18. " \"properties\": {\n" +
  19. " \"id\":{\n" +
  20. " \"type\":\"integer\"\n" +
  21. " },\n" +
  22. " \"title\":{\n" +
  23. " \"type\":\"keyword\"\n" +
  24. " },\n" +
  25. " \"price\":{\n" +
  26. " \"type\":\"double\"\n" +
  27. " },\n" +
  28. " \"created_at\":{\n" +
  29. " \"type\":\"date\"\n" +
  30. " },\n" +
  31. " \"description\":{\n" +
  32. " \"type\":\"text\",\n" +
  33. " \"analyzer\": \"ik_max_word\"\n" +
  34. " }\n" +
  35. " }\n" +
  36. " }", XContentType.JSON);
  37. //参数1:创建索引请求对象 参数2:请求配置对象
  38. CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
  39. System.out.println("创建状态:"+createIndexResponse.isAcknowledged()); //打印返回信息
  40. restHighLevelClient.close(); //关闭资源
  41. }
  42. @Test//删除索引
  43. public void deleteIndex() throws IOException {
  44. AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(new DeleteIndexRequest("products"), RequestOptions.DEFAULT);
  45. System.out.println("删除状态:"+acknowledgedResponse.isAcknowledged()); //打印返回信息
  46. restHighLevelClient.close(); //关闭资源
  47. }
  48. }

4.文档相关操作

  1. /*
  2. 文档相关操作(document)
  3. */
  4. public class Test2 {
  5. RestHighLevelClient restHighLevelClient;
  6. @Before
  7. public void init(){
  8. final ClientConfiguration clientConfiguration =ClientConfiguration.builder()
  9. .connectedTo("xx.xxx.xxx.xx:9200")
  10. .build();
  11. this.restHighLevelClient = RestClients.create(clientConfiguration).rest();
  12. }
  13. @Test //创建文档
  14. public void createDoc() throws IOException {
  15. IndexRequest indexRequest = new IndexRequest("products");
  16. indexRequest.id("2") //手动指定文档的id,如果不指定则会用uuid
  17. .source("{\n" +
  18. " \"title\":\"瑞星咖啡\",\n" +
  19. " \"price\": 9.8,\n" +
  20. " \"created_at\":\"2023-11-18\",\n" +
  21. " \"description\":\"瑞星咖啡我最爱了,好喝\"\n" +
  22. "}", XContentType.JSON);
  23. //参数1:索引请求对象,参数2:请求配置对象
  24. IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
  25. System.out.println(indexResponse.status());
  26. restHighLevelClient.close();
  27. }
  28. @Test //修改文档
  29. public void updateDoc() throws IOException {
  30. UpdateRequest updateRequest = new UpdateRequest("products","1");
  31. updateRequest.doc("{\n" +
  32. " \"title\":\"库迪咖啡非\"\n" +
  33. " }",XContentType.JSON);
  34. //参数1:索引请求对象,参数2:请求配置对象
  35. UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
  36. System.out.println(updateResponse.status());
  37. restHighLevelClient.close();
  38. }
  39. @Test //删除文档
  40. public void deleteDoc() throws IOException {
  41. DeleteRequest deleteRequest = new DeleteRequest("products","2");
  42. //参数1:索引请求对象,参数2:请求配置对象
  43. DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
  44. System.out.println(deleteResponse.status());
  45. restHighLevelClient.close();
  46. }
  47. @Test //基于id查询文档
  48. public void searchDocById() throws IOException {
  49. GetRequest getRequest = new GetRequest("products", "1");
  50. GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
  51. System.out.println(getResponse.getId());
  52. System.out.println(getResponse.getSourceAsString());
  53. }
  54. }

5.高级查询

  1. public class Test3 {
  2. RestHighLevelClient restHighLevelClient;
  3. @Before
  4. public void init(){
  5. final ClientConfiguration clientConfiguration =ClientConfiguration.builder()
  6. .connectedTo("xx.xxx.xxx.xx:9200")
  7. .build();
  8. this.restHighLevelClient = RestClients.create(clientConfiguration).rest();
  9. }
  10. @Test //查询一个索引中的所有文档
  11. public void searchAll() throws IOException {
  12. SearchRequest searchRequest = new SearchRequest("products");
  13. searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()));//查询所有
  14. //参数1:搜索请求对象 参数2:请求配置对象
  15. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  16. System.out.println("查询出来的总条数:"+searchResponse.getHits().getTotalHits().value);
  17. System.out.println("查询出来的最大得分"+searchResponse.getHits().getMaxScore());
  18. //拿到数据结果
  19. SearchHit[] hits = searchResponse.getHits().getHits();
  20. for(SearchHit hit:hits){
  21. String id = hit.getId();
  22. System.out.println("id: "+id+" source: "+hit.getSourceAsString());
  23. }
  24. }
  25. @Test //基于关键词查询
  26. public void search() throws IOException {
  27. SearchRequest searchRequest = new SearchRequest("products");
  28. searchRequest.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("description","好喝")));//查询所有
  29. //参数1:搜索请求对象 参数2:请求配置对象
  30. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  31. System.out.println("查询出来的总条数:"+searchResponse.getHits().getTotalHits().value);
  32. System.out.println("查询出来的最大得分"+searchResponse.getHits().getMaxScore());
  33. //拿到数据结果
  34. SearchHit[] hits = searchResponse.getHits().getHits();
  35. for(SearchHit hit:hits){
  36. String id = hit.getId();
  37. System.out.println("id: "+id+" source: "+hit.getSourceAsString());
  38. }
  39. }
  40. /*
  41. * 分页查询
  42. * 排序
  43. * 字段
  44. */
  45. @Test //分页查询 与排序
  46. public void search2() throws IOException {
  47. SearchRequest searchRequest = new SearchRequest("products");
  48. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  49. searchSourceBuilder.query(QueryBuilders.matchAllQuery())
  50. .from(1) //起始位置 start=(page-1)*size
  51. .size(1) //每页显示条数
  52. .sort("price", SortOrder.ASC) //字段排序
  53. .fetchSource(new String[]{},new String[]{"created_at"}); //参数1:包含字段数组 参数2:排除字段数组
  54. searchRequest.source(searchSourceBuilder);//查询所有
  55. //参数1:搜索请求对象 参数2:请求配置对象
  56. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  57. System.out.println("查询出来的总条数:"+searchResponse.getHits().getTotalHits().value);
  58. System.out.println("查询出来的最大得分"+searchResponse.getHits().getMaxScore());
  59. //拿到数据结果
  60. SearchHit[] hits = searchResponse.getHits().getHits();
  61. for(SearchHit hit:hits){
  62. String id = hit.getId();
  63. System.out.println("id: "+id+" source: "+hit.getSourceAsString());
  64. }
  65. }
  66. @Test //高亮
  67. public void search3() throws IOException {
  68. SearchRequest searchRequest = new SearchRequest("products");
  69. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  70. HighlightBuilder highlightBuilder = new HighlightBuilder();
  71. highlightBuilder.requireFieldMatch(false).field("description").field("title").preTags("<span style='color:red;'>").postTags("</span>");
  72. searchSourceBuilder.query(QueryBuilders.termQuery("description","好喝"))
  73. .highlighter(highlightBuilder);
  74. searchRequest.source(searchSourceBuilder);//查询所有
  75. //参数1:搜索请求对象 参数2:请求配置对象
  76. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  77. System.out.println("查询出来的总条数:"+searchResponse.getHits().getTotalHits().value);
  78. System.out.println("查询出来的最大得分"+searchResponse.getHits().getMaxScore());
  79. //拿到数据结果
  80. SearchHit[] hits = searchResponse.getHits().getHits();
  81. for(SearchHit hit:hits){
  82. System.out.println("id: "+hit.getId()+" source: "+hit.getSourceAsString());
  83. //获取高亮字段
  84. Map<String, HighlightField> highlightFields = hit.getHighlightFields();
  85. if(highlightFields.containsKey("description")){
  86. System.out.println("description高亮结果: "+highlightFields.get("description").fragments()[0]);
  87. }
  88. if(highlightFields.containsKey("title")){
  89. System.out.println("title高亮结果: "+highlightFields.get("title").fragments()[0]);
  90. }
  91. }
  92. }
  93. @Test //过滤查询
  94. public void search4() throws IOException {
  95. SearchRequest searchRequest = new SearchRequest("products");
  96. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  97. searchSourceBuilder.query(QueryBuilders.matchAllQuery())
  98. .postFilter(QueryBuilders.idsQuery().addIds("1")); //指定过滤条件
  99. searchRequest.source(searchSourceBuilder);//查询所有
  100. //参数1:搜索请求对象 参数2:请求配置对象
  101. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  102. System.out.println("查询出来的总条数:"+searchResponse.getHits().getTotalHits().value);
  103. System.out.println("查询出来的最大得分"+searchResponse.getHits().getMaxScore());
  104. //拿到数据结果
  105. SearchHit[] hits = searchResponse.getHits().getHits();
  106. for(SearchHit hit:hits){
  107. String id = hit.getId();
  108. System.out.println("id: "+id+" source: "+hit.getSourceAsString());
  109. }
  110. }
  111. }

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

闽ICP备14008679号