【问题标题】:How to build sibling aggregations using the Elasticsearch Java API?如何使用 Elasticsearch Java API 构建兄弟聚合?
【发布时间】:2016-01-10 04:02:25
【问题描述】:

我想做一个过滤聚合、嵌套聚合,然后是 3 个兄弟聚合。我已经对此进行了测试,它可以使用 REST API 工作。这是我使用的查询:

{
  "aggs": {
    "filter_agg": {
      "filter": {
        ...
      },
      "aggs": {
        "nested_agg": {
          "nested": {
            "path": "myProperty"
          },
          "aggs": {
            "sibling_agg_1": {
              ...
            },
            "sibling_agg_2": {
              ...
            },
            "sibling_agg_3": {
              ...
            }
          }
        }
      }
    }
  }
}

现在,我想在我的代码库中使用 Java API 来实现这个查询。我不确定如何进行兄弟聚合,因为FilterAggregationBuilder 唯一可用的方法是subAggregation()

在 Java API 的上下文中,这些兄弟聚合是子聚合吗?

我开始写的Java代码是这样的:

client.prepareSearch(index)
    .setTypes(types)
    .setSearchType(SearchType.COUNT)
    .addAggregation(myFilterAggregation
      .subAggregation(AggregationBuilders.nested("nested_agg").path("myProperty"))

然后我可以继续构建SearchRequestBuilder 的唯一方法是更多subAggregation - 这是实现此功能的正确方法吗?在这种情况下,REST API 和 Java API 似乎有所不同。

【问题讨论】:

    标签: java elasticsearch


    【解决方案1】:

    您可以通过将子聚合添加到 nested 来做到这一点(请注意,我选择了 terms 聚合,因为从您的查询 DSL 中不清楚您使用哪种特定聚合类型作为兄弟聚合):

    // create the nested aggregation
    NestedBuilder nestedAgg = AggregationBuilders.nested("nested_agg").path("myProperty");
    
    // now add each of your sub-aggregation to it
    nestedAgg.subAggregation(AggregationBuilders.terms("sibling_agg_1").field("field1"));
    nestedAgg.subAggregation(AggregationBuilders.terms("sibling_agg_2").field("field2"));
    nestedAgg.subAggregation(AggregationBuilders.terms("sibling_agg_3").field("field3"));
    
    // finally add the nested aggregation to the filter aggregation
    client.prepareSearch(index)
        .setTypes(types)
        .setSearchType(SearchType.COUNT)
        .addAggregation(myFilterAggregation
          .subAggregation(nestedAgg);
    

    【讨论】:

    • 是的,我昨天意识到的是,它取决于您调用 subAggregation 来确定它是子聚合还是兄弟聚合。
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2022-06-30
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    相关资源
    最近更新 更多