I have a large document store in elasticsearch and would like to retrieve the distinct filter values for display on HTML drop-downs.
An example would be something like
[ { "name": "John Doe", "deparments": [ { "name": "Accounts" }, { "name": "Management" } ] }, { "name": "Jane Smith", "deparments": [ { "name": "IT" }, { "name": "Management" } ] } ]
The drop-down should have a list of departments, i.e. IT, Account and Management.
Would some kind person please point me in the right direction for retrieving a distinct list of departments from elasticsearch?
Thanks
This is a job for a
terms
aggregation (documentation).You can have the distinct
departments
values like this :Which, in your example, outputs :
Two additional notes :
size
to 0 will set the maximum buckets number to Integer.MAX_VALUE. Don't use it if there are too manydepartments
distinct values.terms
resulting of analyzingdepartments
values. Be sure to use yourterms
aggregation on a field mapped asnot_analyzed
.For example, with our default mapping (
departments.name
is ananalyzed
string), adding this employee:will cause this kind of result:
With a correct mapping :
The same request ends up outputting :
Hope this helps!