简体   繁体   中英

Find the count of nested.nested Elastic Search documents

Is it possible using the Elastic Search _count API and having the following abbreviated ES template to find the count of sponsorships for all the campaigns by brandId ?

sponsorshipSets and sponsorships are optional so it can be null .

{
  "index_patterns": "campaigns*",
  "order": 4,
  "version": 4,
  "aliases": {
    "campaigns": {

    }
  },
  "settings": {
    "number_of_shards": 5
  },
  "mappings": {
    "dynamic": "false",
    "properties": {
      "brandId": {
        "type": "keyword"
      },
      "sponsorshipSets": {
        "type": "nested",
        "properties": {
          "id": {
            "type": "keyword"
          },
          "sponsorships": {
            "type": "nested",
            "properties": {
              "id": {
                "type": "keyword"
              }
            }
          }
        }
      }
    }

filter aggregation can be used to fetch docs with certain brand Id. Two Nested aggregations to point to sponsorship and value_count aggregation to get the count.

Query

{
  "aggs": {
    "selected_brand": {
      "filter": {
        "term": {
          "brandId": "1"
        }
      }
    },
    "sponsorshipSets": {
      "nested": {
        "path": "sponsorshipSets"
      },
      "aggs": {
        "sponsorships": {
          "nested": {
            "path": "sponsorshipSets.sponsorships"
          },
          "aggs": {
            "count": {
              "value_count": {
                "field": "sponsorshipSets.sponsorships.id"
              }
            }
          }
        }
      }
    }
  }
}

I found a solution without using Aggregations, it seems more accurate from the above and I can use the _count API.

{
    "query": {
        "bool": {
            "must": [
                {
                    "nested": {
                        "path": "sponsorshipSets.sponsorships",
                        "query": {
                            "bool": {
                                "filter": {
                                    "exists": {
                                        "field": "sponsorshipSets.sponsorships"
                                    }
                                }
                            }
                        }
                    }
                },
                {
                    "term": {
                        "brandId": "b1d28821-3730-4266-8f55-eb69596004fb"
                    }
                }
            ]
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM