Elasticearch如何进行过滤器聚合

sg2wtvxw  于 2022-10-06  发布在  ElasticSearch
关注(0)|答案(1)|浏览(185)

我需要进行平均聚合,但我想过滤一些值。在下面的示例中,我希望筛选长度=100,因此我希望对所有文档的长度(文档#1和文档#2)和宽度进行平均化。所以我希望看到长度平均值为9,宽度平均值为5。我应该怎么做?

文档示例:

["id": 1, "length": 10, "width":8]
["id": 2, "length": 8, "width":2]
["id": 3, "length": 100, "width":5]

在其他情况下,长度可能不存在,这种情况如何?

["id": 1, "length": 10, "width":8]
["id": 2, "length": 8, "width":2]
["id": 3, "width":5]
termAggregation.subAggregation(AggregationBuilders.avg("length").field("length"))
.subAggregation(AggregationBuilders.avg("width").field("width"));
o8x7eapl

o8x7eapl1#

您的聚合查询将如下所示,用于从聚合中排除100。您需要使用filter聚合并在该avg内用子聚合。

{
  "size": 0,
  "aggs": {
    "cal": {
      "filter": {
        "bool": {
          "must_not": [
            {
              "match": {
                "length": "100"
              }
            }
          ]
        }
      },
      "aggs": {
        "avg_length": {
          "avg": {
            "field": "length"
          }
        }
      }
    },
    "avg_width":{
      "avg": {
        "field": "width"
      }
    }
  }
}

Java代码

AvgAggregationBuilder widthAgg = new AvgAggregationBuilder("avg_width").field("width");
        AvgAggregationBuilder lengthAgg = new AvgAggregationBuilder("avg_length").field("length");

        FilterAggregationBuilder filter = new FilterAggregationBuilder("cal",
                QueryBuilders.boolQuery().mustNot(QueryBuilders.matchQuery("length", "100")));
        filter.subAggregation(lengthAgg);

        SearchSourceBuilder ssb = new SearchSourceBuilder();
        ssb.aggregation(filter);
        ssb.aggregation(widthAgg);

        System.out.println(ssb.toString());

响应

"aggregations": {
    "avg_width": {
      "value": 5
    },
    "cal": {
      "meta": {},
      "doc_count": 3,
      "avg_length": {
        "value": 9
      }
    }
  }

相关问题