当前位置:   article > 正文

es使用和常用查询(包含多字段聚合查询,实体类方式保存es)_elasticsearch collapse多个字段

elasticsearch collapse多个字段

1.导入es相关jar包

  1. <dependency>
  2. <groupId>org.springframework.data</groupId>
  3. <artifactId>spring-data-elasticsearch</artifactId>
  4. <version>4.2.11</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.elasticsearch.client</groupId>
  8. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  9. <version>7.12.1</version>
  10. </dependency>

2.增加es配置

  1. elasticsearch:
  2. hosts: es-service.xiot-v2.svc.cluster.local:port
  3. storage-strategy: NONE #分库规则 按日分 DAY, 按月分 MONTH, 按年分 YEAR, 不分 NONE
  4. shard: 1 #分片数量

3.读取es相关配置 

  1. @Configuration
  2. public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {
  3. @Value("${elasticsearch.hosts}")
  4. private String HOST;
  5. @Override
  6. public RestHighLevelClient elasticsearchClient() {
  7. final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
  8. .connectedTo(HOST)
  9. .build();
  10. return RestClients.create(clientConfiguration).rest();
  11. }
  12. }

 4.创建es实体类,与es mapping设计一致

  1. @Data
  2. @Document(indexName = "data",createIndex = false)
  3. public class ESData {
  4. @Id
  5. @Field(type = FieldType.Text)
  6. @JSONField(name = "id")
  7. private String id;
  8. /**
  9. * 数据时间点: 相对于 UTC-0 1970-1-1 0 点的毫秒数
  10. */
  11. @Field(name="ts",type = FieldType.Long)
  12. @JSONField(name = "ts")
  13. private Long ts;
  14. //设备说明
  15. @Field(name= "signature.type",type = FieldType.Keyword)
  16. @JSONField(name = "signature.type")
  17. private String signatureType;
  18. }

 5.创建es结构

  1. 1.新建index:data
  2. put http://ip:port/data
  3. 2.新建mapping
  4. put http://ip:port/data/_mapping
  5. {
  6. "properties": {
  7. "ts": {
  8. "type": "long"
  9. },
  10. "name": {
  11. "type": "keyword"
  12. },
  13. "test": {
  14. "type": "nested",
  15. "properties": {
  16. "voltage": {
  17. "type": "nested",
  18. "properties": {
  19. "avg": {
  20. "type": "keyword"
  21. },
  22. "min": {
  23. "type": "keyword"
  24. },
  25. "max": {
  26. "type": "keyword"
  27. }
  28. }
  29. }
  30. }
  31. }

 6.创建类继承 ElasticsearchRepository 实现通过api保存实体类ESData到es

  1. public interface ESRepository extends ElasticsearchRepository<ESData, String> {
  2. }

 7.保存实体类ESData到es

  1. //1.注入
  2. @Autowired
  3. private ESRepository esRepository;
  4. public void insertData(){
  5. //2.初始化实体类,插入数据
  6. ESData data = new ESData();
  7. ....
  8. //3.通过实体类保存es
  9. esRepository.save(data);
  10. }

 8.es查询 多字段匹配查询,分组查询,分组后聚合

  1. @Service
  2. public class EsSearchService {
  3. @Autowired
  4. private RestHighLevelClient client;
  5. /**
  6. 先查询 后分组 再统计
  7. */
  8. public List<HashMap> searchBills(LocalDateTime begin, LocalDateTime end,String boxName){
  9. //设置查询es的index
  10. SearchRequest searchRequest = new SearchRequest("data");
  11. //2.创建 SearchSourceBuilder条件构造。
  12. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  13. //若时间未传查询过去七日数据
  14. Long beginTime = null;
  15. Long endTime = null;
  16. if(begin==null){
  17. beginTime =
  18. LocalDateTime.now().plusDays(-7).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
  19. }else{
  20. beginTime = begin.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
  21. }
  22. if(end==null){
  23. endTime = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli() ;
  24. }else{
  25. endTime = end.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
  26. }
  27. //相当于and查询
  28. BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
  29. boolQuery.filter(QueryBuilders.rangeQuery("ts").from(beginTime).to(endTime));
  30. if(StringUtils.isNotEmpty(boxName)){
  31. boolQuery.must(QueryBuilders.termQuery("boxName",boxName));
  32. }
  33. searchSourceBuilder.query(boolQuery);
  34. //去重
  35. CollapseBuilder collapseBuilder = new CollapseBuilder("ts");
  36. searchSourceBuilder.collapse(collapseBuilder);
  37. //多字段分组
  38. TermsAggregationBuilder aggregation = AggregationBuilders.terms("aggs_group")
  39. .script(new Script("doc['f1'] +'#'+doc['f2']+'#'+doc['f3']+'#'+doc['f4']+'#'+doc['f5']"))
  40. .size(Integer.MAX_VALUE) .order(BucketOrder.aggregation("_key", true));
  41. //sum聚合 aggregation.subAggregation(AggregationBuilders.sum("f6").field("sum1"))
  42. .subAggregation(AggregationBuilders.sum("f7").field("sum2"));
  43. searchSourceBuilder.aggregation(aggregation);
  44. //3.将 SearchSourceBuilder 添加到 SearchRequest中
  45. searchRequest.source(searchSourceBuilder);
  46. //4.执行查询
  47. SearchResponse searchResponse = null;
  48. try {
  49. searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
  50. } catch (IOException e) {
  51. throw new RuntimeException(e);
  52. }
  53. //5.解析查询结果
  54. System.out.println("花费的时长:" + searchResponse.getTook());
  55. List<HashMap> result=new ArrayList<>();
  56. if(RestStatus.OK.equals(searchResponse.status())) {
  57. // 获取聚合结果
  58. Aggregations aggregations = searchResponse.getAggregations();
  59. Terms byAggsAggregation = aggregations.get("aggs_group");
  60. for(Terms.Bucket buck : byAggsAggregation.getBuckets()) {
  61. HashMap map=new HashMap();
  62. String[] arr= buck.getKeyAsString().split("#");
  63. //取子聚合
  64. ParsedSum sum1 = buck.getAggregations().get("sum1");
  65. ParsedSum sum2 = buck.getAggregations().get("sum2");
  66. map.put("f1",arr[0].replace("[","").replace("]",""));
  67. map.put("sum1",sum1.getValue());
  68. map.put("sum2",sum2.getValue());
  69. result.add(map);
  70. }
  71. }
  72. return result;
  73. }
  74. }

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

闽ICP备14008679号