0

I have products stored in ES and I'm trying to aggregate them by their size. I would like to design following behaviour. For each term even outside of query to receive term counts based on query.

So querying for sizes ["S", "M"] I would like to receive:

S: 1
M: 1
L: 0

Is this somehow possible?

Here is my setup where I get following result:

S: 1
M: 1

But L is completely missing.

PUT demo
{
    "mappings": {
        "product": {
            "properties": {
                "size": { 
                  "type": "keyword"
                }
            }
        }
    }
}

PUT demo/product/1
{
    "size": "S"  
}

PUT demo/product/2
{
    "size": "M"  
}

PUT demo/product/3
{
    "size": "L"  
}

GET demo/_search
{
   "size": 0,
   "query": {
      "bool": {
         "must": [
            {
               "terms": {
                  "size": [
                     "S",
                     "M"
                  ]
               }
            }
         ]
      }
   },
   "aggs": {
      "size": {
         "terms": {
            "field": "size"
         }
      }
   }
}

1 Answers1

0

You can use filter.

{
    "size": 0,
    "query": {
        "bool": {
            "must": [
                { "terms": { "field": "size" } }
            ],
            "filter": { 
                "terms": { "size": [ "S", "M"] } 
            }
        }
    },
    "aggs": {
        "size": {
            "terms": { "field": "size" }
        }
    }
}
skal88
  • 464
  • 2
  • 10
  • This doesn't seem to work in elasticsearch 5. https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-filtered-query.html – Josef Rousek Nov 30 '16 at 15:12
  • @JosefRousek I have edited my answer. Try again now in ES5 – skal88 Nov 30 '16 at 15:32
  • Thank you for the effort, but this doesn't work either. I've done pretty long research before posting, so Its just a matter of me having problem describing the question. – Josef Rousek Dec 01 '16 at 07:57