0

I am working to find the way to do aggregations on a field after filtering on an another filed. But, the Elastic search documentation is not easily understandable.

Lets say My Mapping:

[
  {
     a:'a1'
     b:'b1'
     c:120
     d:12
   },
  {
     a:'a2'
     b:'b1'
     c:170
     d:15
   }
  {
     a:'a3'
     b:'b2'
     c:128
     d:18
   }
  {
     a:'a4'
     b:'b1'
     c:158
     d:5
   }
] 

Required Aggregation:

Return the sum of field "c", by selecting the docs with "b" where b=b1 and d is less than 13

This is not my requirement, but the answer helps me in understanding the documentation.

Jack Daniel
  • 2,527
  • 3
  • 31
  • 52

1 Answers1

1

Try this:

POST index/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "b": "b1"
          }
        },
        {
          "range": {
            "d": {
              "lt": 13
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "total": {
      "sum": {
        "field": "c"
      }
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
  • The aggregations are happening on the whole set of documents, but I wanted the sum of field "c" for the selected documents with term "b" and "d" – Jack Daniel Jul 25 '16 at 11:04
  • That's what the above does. The query only selects the documents with fields `b` and `d` matching their respective queries and the aggregations will run only on those documents. Try it out. – Val Jul 25 '16 at 11:05
  • {"aggs": { "total": { "sum": { "field": "c" } } } ....... also returning the same value as the above query. I am unable to figure out the filtering here. – Jack Daniel Jul 25 '16 at 11:11
  • I don't understand what you mean. Can you explain how you are executing my above query, what results you get and how that differs from what you expect? Please update your question with the requested info so we can sort it out. – Val Jul 25 '16 at 11:13
  • Edited the question. And I ran the query as it is and then to got the same result as the above commented query. I feel my query is a complete aggregate of all docs. – Jack Daniel Jul 25 '16 at 11:22
  • Try to run the query by leaving out the two `bool/must` constraints (i.e. equivalent to `match_all`) and you'll see the difference. – Val Jul 25 '16 at 11:24
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/118217/discussion-between-ashwanth-and-val). – Jack Daniel Jul 25 '16 at 11:28