ElasticSearch:嵌套项目计入搜索结果

时间:2018-12-18 10:17:42

标签: elasticsearch elasticsearch-aggregation

我有以下映射:

{
  "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
        }
      }
    ]
  }
}

我可以通过聚合来实现吗?

1 个答案:

答案 0 :(得分:2)

由于您有个好主意,也将totalItems字段存储在根级别,因此您可以对该字段求和,然后得到嵌套项目的数量:

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