Skip to content

Instantly share code, notes, and snippets.

@jasdeep06
Created August 12, 2019 12:29
Show Gist options
  • Save jasdeep06/5abb1309a94f59a3811267eb182a9606 to your computer and use it in GitHub Desktop.
Save jasdeep06/5abb1309a94f59a3811267eb182a9606 to your computer and use it in GitHub Desktop.
In elasticsearch,in order to apply aggregation on a filtered data,you can proceed in two ways:
1)First Way-
a) Write a filter query
b)Include aggregations in query['aggs'].
This way shows that aggregations in ES are applied on the result of queried data.This case works perfectly when the objects
retrieved after querying are fully in compliance with your query.This assumptions can be incorrect in case of nested objects.
Eg -
Let saleHistory be a nested field of property object.
'saleHistory':[
{'purchasePrice':800000,'contractDate':'20110917'},
{'purchasePrice':1302000,'contractDate':'20181007'}
]
Suppose I want to retrieve all the properties which were sold between Aug'18 - Aug'19.In this case,the object that would be
returned would contain both dict in saleHistory.The aggregation would take that result and apply aggregation on it giving
incorrect results.
2)Second Way-
Use a filter aggregation.
Filter aggregation is the correct way of handling such cases.It refilters the results returned by the query and then applies
aggregation.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment