我有以下问题。我有一个具有2个属性(fieldB和fieldC)的嵌套字段(“列表”)。
这是文档的样子:

"fieldA: "1",
"list": [
  {"fieldB": "ABC",
  "fieldC": "DEF"},
  {"fieldB": "ABC",
  "fieldC": "GHI"},
  {"fieldB": "UVW",
  "fieldC": "XYZ"},...]
                        },

我想获得所有文档中“ABC”(fieldB)的所有可能fieldC值的明确列表。到目前为止,我已经在Java(Java REST客户端)中尝试过此操作:
 SearchRequest searchRequest = new SearchRequest("abc*");
 QueryBuilder matchQueryBuilder = QueryBuilders.boolQuery()
             .must(QueryBuilders.nestedQuery("aList",
             QueryBuilders.matchQuery("list.fieldB.keyword", "ABC"), ScoreMode.None));
 SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
 sourceBuilder.query(matchQueryBuilder)
              .aggregation(AggregationBuilders.nested("listAgg","list")
              .subAggregation(AggregationBuilders.terms("fieldBAgg")
              .field("list.fieldB.keyword")));

    searchRequest.source(sourceBuilder);

    SearchResponse searchResponse = null;
    try {
        searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    } catch (IOException e) {
        e.printStackTrace();
    }

    Nested list = searchResponse.getAggregations().get("listAgg");
    Terms fieldBs = list.getAggregations().get("fieldBAgg");

通过该查询,我得到了所有在fieldB中包含“ABC”的文档,并且我得到了所有 fieldC值。但是我只想要fieldC的值,其中fieldB是“ABC”。

因此,在该示例中,我得到了DEF,GHI和XYZ。但是我只想要DEF和GHI。有人知道如何解决这个问题吗?

最佳答案

查询部分中的nested约束将仅选择确实具有满足该约束的嵌套字段的所有文档。您还需要在聚合部分中添加相同的约束,否则,您将聚合所有选定文档的所有嵌套字段。继续这样:

// 1. terms aggregation on the desired nested field
nestedField = AggregationBuilders.terms("fieldBAgg").field("list.fieldC.keyword");

// 2. filter aggregation on the desired nested field value
onlyBQuery = QueryBuilders.termQuery("list.fieldB.keyword", "ABC");
onlyBFilter = AggregationBuilders.filter("onlyFieldB", onlyBQuery).subAggregation(nestedField);

// 3. parent nested aggregation
nested = AggregationBuilders.nested("listAgg", "list").subAggregation(onlyBFilter);

// 4. main query/aggregation
sourceBuilder.query(matchQueryBuilder).aggregation(nested);

关于java - Elasticsearch-术语聚合嵌套字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61728763/

10-10 17:49