Richard Barraclough
Richard Barraclough

Reputation: 2984

Counting search results in ElasticSearch by a nested property

Here is a schema with 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"
                }
            }
        }
    }
}

And here is a document.

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

For any given query I need a list with two columns: the Menu.Id and the number of documents in the result set that have that Menu.Id in their Menus array.

How? (Is there any documentation for aggs that isn't impenetrable?)

Upvotes: 0

Views: 27

Answers (1)

baitmbarek
baitmbarek

Reputation: 2518

@Richard, does this query suits your need ?

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

Output :

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

Here we specify a nested path and then aggregate on the menu Ids. You can take a look at this documentation page : https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-nested-aggregation.html

Upvotes: 2

Related Questions