Multiple cardinality aggregations

I am trying to create sub aggregations that will return the number of items in each category. For example:

{
  "aggs":{
    "stores":{
      "terms":{
        "field": "store_code",
        "order": {
          "_term": "asc"
        }
      },
      "aggs":{
        "item_count":{
          "cardinality":{
            "field": "items"
          }
        }
      },
      "aggs":{
        "item_count":{
          "cardinality":{
            "field": "franchises"
          }
        }
    }
  }
}

So the end product should be the store_code's number of distinct items and franchises. However, I get an error saying duplicate key aggs. How can I make it so the sub aggregations display?

This is invalid JSON since you cannot have the same key twice in a JSON object (hence the error you are getting). To add multiple subaggregation to an aggregation you just need to include them both in the same aggs object. You also need to give your cardinality aggregations different names so that 1) its valid JSON but also more importantly 2) so you can distinguish because the aggregations in the response. Try the following:

{  
   "aggs":{  
      "stores":{  
         "terms":{  
            "field":"store_code",
            "order":{  
               "_term":"asc"
            }
         },
         "aggs":{  
            "item_count":{  
               "cardinality":{  
                  "field":"items"
               }
            },
            "franchise_count":{  
               "cardinality":{  
                  "field":"franchises"
               }
            }
         }
      }
   }
}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.