0

This is my structure:

document 1 has

{
  "people": [
    {
      "name": "Darrell",
      "age": "10",
    },
    {
      "name": "Karen",
      "age": "20",
    },
    {
      "name": "Gary",
      "age": "30",
    }
  ]
}

Document 2 has

{
  "people": [
    {
      "name": "Karen",
      "age": "25",
    },
    {
      "name": "Gary",
      "age": "30",
    }
  ]
}

Now, how can I perform count aggregation on individual array elements that matched the query?

  1. If I query for name:Karen, I need the count as 2.
  2. If I query for name:Karen && age:20, I need the count as 1.
  3. If I query for name:Gary && age:30, I need the count as 2.

1 Answer 1

2

You need to map your people object as nested objects, otherwise it won't work as you expect.

curl -XPUT localhost:9200/your_index -d '{
  "mappings": {
    "your_type": {
      "properties": {
        "people": {
          "type": "nested",
          "properties": {
              "name": {"type": "string"},
              "age": {"type": "integer"}
          }
        }
      }
    }
  }
}'

Once your index and mapping type have been created and after you've re-indexed your data, you'll be able to run your query like this:

curl -XPOST localhost:9200/your_index/_search -d '{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "people",
            "query": {
              "term": {
                "people.name": "karen"
              }
            }
          }
        },
        {
          "nested": {
            "path": "people",
            "query": {
              "term": {
                "people.age": "20"
              }
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "people": {
      "nested": {
        "path": "people"
      },
      "aggs": {
        "names": {
          "terms": {
             "field": "people.name"
          }
        }
      }
    }
  }
}'
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks val. It shows me an error- "bool query does not support [filter]"
Oh, I'm using ES 2. and you probably aren't. I've updated my answer with a pre-2.0 valid query.
for some reason the terms aggregation did not work. I switched to value_count and it worked. thanks a lot.
I had added the name key already but still "terms" was not giving the correct counts...still trying to debug that. (But value_count was readily correct).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.