1
{
    ...
    "shirt_sizes":["XL","L","M","S"]
    ...
}

How to create aggregation of shirt_size field in elasticsearch ?

1 Answer 1

1

Assuming I'm understanding your question correctly, you need to use a terms aggregation. You probably also want the "shirt_sizes" field to be not_analyzed.

As a simple example, I set up an index with an un-analyzed field, and added a couple of docs:

PUT /test_index
{
   "mappings": {
      "doc": {
         "properties": {
            "shirt_sizes": {
               "type": "string",
               "index": "not_analyzed"
            }
         }
      }
   }
}

POST /test_index/doc/_bulk
{"index":{"_id":1}}
{"shirt_sizes":["XL","L","M","S"]}
{"index":{"_id":2}}
{"shirt_sizes":["L","M","S","XS"]}

Then I can get back all the sizes with a simple aggregation:

POST /test_index/_search?search_type=count
{
    "aggs": {
        "shirt_sizes_terms": {
            "terms": {
                "field": "shirt_sizes"
            }
        }
    }
}
...
{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0,
      "hits": []
   },
   "aggregations": {
      "shirt_sizes_terms": {
         "buckets": [
            {
               "key": "L",
               "doc_count": 2
            },
            {
               "key": "M",
               "doc_count": 2
            },
            {
               "key": "S",
               "doc_count": 2
            },
            {
               "key": "XL",
               "doc_count": 1
            },
            {
               "key": "XS",
               "doc_count": 1
            }
         ]
      }
   }
}

Here is the code I used:

http://sense.qbox.io/gist/9d759c95c8794be7786b0248f58bfdec6da7510f

Sign up to request clarification or add additional context in comments.

2 Comments

Why "not analyzed" for shirt sizes? So that it preserves capital letters?
Yup. If that doesn't matter to you then you can leave it out.

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.