通过嵌套计算 ElasticSearch 中的搜索结果 属性

Counting search results in ElasticSearch by a nested property

这是一个带有嵌套 属性 的模式。

{
    "dynamic": "strict",
    "properties" : {
        "Id" : {
          "type": "integer"
        },
        "Name_en" : {
            "type": "text",
            "fields" : {
                "keyword" : {
                    "type" : "keyword",
                    "normalizer": "cloudbuy_normalizer_alphanumeric"
                },
                "text" : {
                    "type" : "text",
                    "analyzer": "english"
                }
            }
        },
        "Menus" : {
            "type" : "nested",
            "properties" : {
                "Id" : {
                    "type" : "integer"
                },
                "Name" : {
                    "type" : "keyword",
                    "normalizer": "normalizer_alphanumeric"
                },
                "AncestorsIds" : {
                    "type" : "integer"
                }
            }
        }
    }
}

这是一份文件。

{
        "Id": 12781279
        "Name": "Thing of purpose made to fit",
        "Menus": [
            {
                "Id": -571057,
                "Name": "Top level menu",
                "AncestorsIds": [
                    -571057
                ]
            }
            ,
            {
                "Id": 1022313,
                "Name": "Other",
                "AncestorsIds": [
                    -571057
                    ,
                    1022313
                ]
            }
        ]
}

对于任何给定的查询,我需要一个包含两列的列表:Menu.Id 和结果集中在 Menus 数组中具有 Menu.Id 的文档数。

怎么样? (是否有任何关于 aggs 的文档不是不可理解的?)

@Richard,这个查询符合您的需要吗?

POST yourindex/_search
{
  "_source": "false", 
  "aggs":{
    "menus": {
      "nested": {
        "path": "Menus"
      },
      "aggs":{
        "menu_aggregation": {
        "terms": {
          "field": "Menus.Id",
          "size": 10
          }
        }
      }
    }
  }

输出:

"aggregations": {
    "menus": {
      "doc_count": 2,
      "menu_aggregation": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
          {
            "key": -571057,
            "doc_count": 1
          },
          {
            "key": 1022313,
            "doc_count": 1
          }
        ]
      }
    }

这里我们指定了一个嵌套路径,然后在菜单Ids上聚合。 您可以查看此文档页面:https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html