• SpringBoot整合ElasticSearch


    导入依赖

    1. org.elasticsearch.client
    2. elasticsearch-rest-high-level-client
    3. 7.4.2

    spring-boot-dependencies中所依赖的ES版本位6.8.5,要改掉

    1. 1.8
    2. 7.4.2

    官方建议把requestOptions创建成单实例

    1. package com.hdb.pingmoweb.search.config;
    2. import org.apache.http.HttpHost;
    3. import org.elasticsearch.client.RequestOptions;
    4. import org.elasticsearch.client.RestClient;
    5. import org.elasticsearch.client.RestClientBuilder;
    6. import org.elasticsearch.client.RestHighLevelClient;
    7. import org.springframework.context.annotation.Bean;
    8. import org.springframework.context.annotation.Configuration;
    9. @Configuration
    10. public class PingmoESConfig {
    11. public static final RequestOptions COMMON_OPTIONS;
    12. static {
    13. RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
    14. COMMON_OPTIONS = builder.build();
    15. }
    16. @Bean
    17. public RestHighLevelClient esRestClient() {
    18. RestClientBuilder builder = null;
    19. // 可以指定多个es
    20. builder = RestClient.builder(new HttpHost("192.168.19.128", 9200, "http"));
    21. RestHighLevelClient client = new RestHighLevelClient(builder);
    22. return client;
    23. }
    24. }

    官方文档:Index API | Java REST Client [7.17] | Elastic

    保存数据 

    Index API | Java REST Client [7.17] | Elastic

    1. @Test
    2. public void indexData() throws IOException {
    3. // 设置索引
    4. IndexRequest indexRequest = new IndexRequest ("users");
    5. indexRequest.id("1");
    6. User user = new User();
    7. user.setUserName("张三");
    8. user.setAge(20);
    9. user.setGender("男");
    10. String jsonString = JSON.toJSONString(user);
    11. //设置要保存的内容,指定数据和类型
    12. indexRequest.source(jsonString, XContentType.JSON);
    13. //执行创建索引和保存数据
    14. IndexResponse index = client.index(indexRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
    15. System.out.println(index);
    16. }

    获取数据

    1. @Test
    2. public void find() throws IOException {
    3. // 1 创建检索请求
    4. SearchRequest searchRequest = new SearchRequest();
    5. searchRequest.indices("bank");
    6. SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    7. // 构造检索条件
    8. // sourceBuilder.query();
    9. // sourceBuilder.from();
    10. // sourceBuilder.size();
    11. // sourceBuilder.aggregation();
    12. sourceBuilder.query(QueryBuilders.matchQuery("address","mill"));
    13. //AggregationBuilders工具类构建AggregationBuilder
    14. // 构建第一个聚合条件:按照年龄的值分布
    15. TermsAggregationBuilder agg1 = AggregationBuilders.terms("agg1").field("age").size(10);// 聚合名称
    16. // 参数为AggregationBuilder
    17. sourceBuilder.aggregation(agg1);
    18. // 构建第二个聚合条件:平均薪资
    19. AvgAggregationBuilder agg2 = AggregationBuilders.avg("agg2").field("balance");
    20. sourceBuilder.aggregation(agg2);
    21. System.out.println("检索条件"+sourceBuilder.toString());
    22. searchRequest.source(sourceBuilder);
    23. // 2 执行检索
    24. SearchResponse response = client.search(searchRequest, PingmoESConfig.COMMON_OPTIONS);
    25. // 3 分析响应结果
    26. System.out.println(response.toString());
    27. }

    返回数据

    1. {
    2. "took": 28,
    3. "timed_out": false,
    4. "_shards": {
    5. "total": 1,
    6. "successful": 1,
    7. "skipped": 0,
    8. "failed": 0
    9. },
    10. "hits": {
    11. "total": {
    12. "value": 4,
    13. "relation": "eq"
    14. },
    15. "max_score": 5.4032025,
    16. "hits": [{
    17. "_index": "bank",
    18. "_type": "account",
    19. "_id": "970",
    20. "_score": 5.4032025,
    21. "_source": {
    22. "account_number": 970,
    23. "balance": 19648,
    24. "firstname": "Forbes",
    25. "lastname": "Wallace",
    26. "age": 28,
    27. "gender": "M",
    28. "address": "990 Mill Road",
    29. "employer": "Pheast",
    30. "email": "forbeswallace@pheast.com",
    31. "city": "Lopezo",
    32. "state": "AK"
    33. }
    34. }, {
    35. "_index": "bank",
    36. "_type": "account",
    37. "_id": "136",
    38. "_score": 5.4032025,
    39. "_source": {
    40. "account_number": 136,
    41. "balance": 45801,
    42. "firstname": "Winnie",
    43. "lastname": "Holland",
    44. "age": 38,
    45. "gender": "M",
    46. "address": "198 Mill Lane",
    47. "employer": "Neteria",
    48. "email": "winnieholland@neteria.com",
    49. "city": "Urie",
    50. "state": "IL"
    51. }
    52. }, {
    53. "_index": "bank",
    54. "_type": "account",
    55. "_id": "345",
    56. "_score": 5.4032025,
    57. "_source": {
    58. "account_number": 345,
    59. "balance": 9812,
    60. "firstname": "Parker",
    61. "lastname": "Hines",
    62. "age": 38,
    63. "gender": "M",
    64. "address": "715 Mill Avenue",
    65. "employer": "Baluba",
    66. "email": "parkerhines@baluba.com",
    67. "city": "Blackgum",
    68. "state": "KY"
    69. }
    70. }, {
    71. "_index": "bank",
    72. "_type": "account",
    73. "_id": "472",
    74. "_score": 5.4032025,
    75. "_source": {
    76. "account_number": 472,
    77. "balance": 25571,
    78. "firstname": "Lee",
    79. "lastname": "Long",
    80. "age": 32,
    81. "gender": "F",
    82. "address": "288 Mill Street",
    83. "employer": "Comverges",
    84. "email": "leelong@comverges.com",
    85. "city": "Movico",
    86. "state": "MT"
    87. }
    88. }]
    89. },
    90. "aggregations": {
    91. "avg#agg2": {
    92. "value": 25208.0
    93. },
    94. "lterms#agg1": {
    95. "doc_count_error_upper_bound": 0,
    96. "sum_other_doc_count": 0,
    97. "buckets": [{
    98. "key": 38,
    99. "doc_count": 2
    100. }, {
    101. "key": 28,
    102. "doc_count": 1
    103. }, {
    104. "key": 32,
    105. "doc_count": 1
    106. }]
    107. }
    108. }
    109. }

    解析数据

    1. private void parseSearchResponse(SearchResponse response){
    2. SearchHits hits = response.getHits();
    3. SearchHit[] searchHits = hits.getHits();
    4. for(SearchHit hit : searchHits){
    5. String sourceAsString = hit.getSourceAsString();
    6. Account account = JSON.parseObject(sourceAsString, Account.class);
    7. System.out.println(account);
    8. }
    9. Aggregations aggregations = response.getAggregations();
    10. Terms agg1 = aggregations.get("agg1");
    11. for(Terms.Bucket bucket:agg1.getBuckets()){
    12. String keyAsString = bucket.getKeyAsString();
    13. System.out.println("年龄:"+keyAsString);
    14. }
    15. Avg agg2 = aggregations.get("agg2");
    16. System.out.println("平均薪资:"+agg2.getValue());
    17. }

  • 相关阅读:
    Linux more 命令使用介绍
    2022首届中国敏捷大会(线上会议)将于12月召开
    Qt: windows下关闭系统窗体
    前端工作总结114-JS-JS创建数组的三种方法
    Worthington公司精氨酸酶:L-鸟氨酸的制备应用
    java字符串专项训练(手机号屏蔽)
    完成原型设计的五个步骤
    关于Java Chassis 3的契约优先(API First)开发
    Python图像处理丨带你认识图像量化处理及局部马赛克特效
    Rust编程-泛型、Trait和生命周期
  • 原文地址:https://blog.csdn.net/qq_29385297/article/details/127434851