ElasticSearch:嵌套项在搜索结果中计数

ElasticSearch: nested items count in search results

我有以下映射:

{
  "test_index" : {
    "mappings" : {
      "test_type" : {
        "properties" : {
          "field1" : {
            "type" : "string"
          },
          "field2" : {
            "type" : "string"
          },
          "items" : {
            "type" : "nested",
            "properties" : {
              "nested_field1" : {
                "type" : "string"
              },
              "nested_field2" : {
                "type" : "string"
              }            
            }
          }
        }
      }
    }
  }
}

对于搜索结果,我想获得结果结构中的总嵌套项:

{
  "hits": {
    "total": 2,
    "max_score": 1.0,
    "hits": [
      {
        "_index": "test_index",
        "_type": "test_type",
        "_id": "AWfAc79wljtimCd5JZlJ",
        "_score": 1.0,
        "_source": {
          "field1": "Some string 1",
          "field2": "Some string 2",
          "items": [
            {
              "nested_field1": "Some val1",
              "nested_field2": "Some val2"
            }
          ],
          "totalItems": 1
        }
      },
      {
        "_index": "test_index",
        "_type": "test_type",
        "_id": "AZxfc79dtrt878xx",
        "_score": 1.0,
        "_source": {
          "field1": "Some string 3",
          "field2": "Some string 4",
          "items": [
            {
              "nested_field1": "Some val3",
              "nested_field2": "Some val4"
            },
            {
              "nested_field1": "Some val5",
              "nested_field2": "Some val6"
            }
          ],
          "totalItems": 2
        }
      }
    ]
  }
}

我可以通过聚合实现吗?

由于您已经有了将 totalItems 字段也存储在根级别的好主意,您只需对该字段求和即可得到嵌套项的数量:

{
  "query": {
    "match_all": {}
  },
  "aggs": {
    "total_items": {
      "sum": {
        "field": "totalItems"
      }
    }
  }
}