Nipun
Nipun

Reputation: 4319

Query to aggregate over nested field with filter in elastic search

I need to aggregate with filter in elastic search for example. I have assets which are saved in elastic search as a document as

{
"id":1,
"name":"1",
"url":"1png20160612115249190.png",
"description": "this is a good asset",
"alt_sizes": ["hi","yes"],
"tags":[{ "id":"1", "name":"Movies"},
    { "id":"2", "name":"Sports"}],
"packs":[{ "id":"1", "name":"pack1", "partnerId":"1"},
    { "id":"2", "name":"pack2 test", "partnerId":"2"}],
"category":[{ "id":"1", "name":"cat1"},
    { "id":"2", "name":"cat2"}],
"appPartner":[{ "id":"1", "name":"par1"},
        { "id":"2", "name":"par2"}],
"created_time":"2016-07-26 00:00:00",
"updated_time":"2016-07-26 10:45:43"
}

Here the packs is indexed as nested type in ES. Packs will have an array of id, name and partnerId. Now what I want is to aggregate on packs with a particular partnerId like I want all the packs with partnerId = 10.

I have tried this query

{
    "size":0,
   "query": {
     "nested": {
                  "path":"appPartner",
                  "query": {
                    "bool": {
                      "must": [
                        {"match": {"appPartner.id": "1"}}
                      ]
                    }
                  }
                }
   },
   "aggs": {
      "packs" : {
          "nested" : {
              "path" : "packs"
          }, 
           "aggs" : {
              "id" : {
                  "terms" : {
                      "field" : "packs.id"
                  }
              ,
              "aggs":{
                  "name":{
                    "terms" : {
                          "field" : "packs.name"
                      }
                  }
             }
             }
          }       

      }
   }
}

This query gives me aggregate over all nested pack ids. I need to aggregate over all nested packids, with partnerID =

Upvotes: 1

Views: 231

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52368

  "aggs": {
    "packs": {
      "nested": {
        "path": "packs"
      },
      "aggs": {
        "partner": {
          "filter": {
            "term": {
              "packs.partnerId": "10"
            }
          },
          "aggs": {
            "id": {
              "terms": {
                "field": "packs.id"
              },
              "aggs": {
                "name": {
                  "terms": {
                    "field": "packs.name"
                  }
                }
              }
            }
          }
        }
      }
    }
  }

Upvotes: 1

Related Questions