# Filtering Aggs by most terms

**URL:** <https://discuss.elastic.co/t/filtering-aggs-by-most-terms/19079>\
**Category:** Elasticsearch\
**Created:** [August 4, 2014, 4:58pm UTC](https://discuss.elastic.co/t/filtering-aggs-by-most-terms/19079 "2014-08-04T16:58:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![thinkmusic](https://avatars.discourse-cdn.com/v4/letter/t/d07c76/32.png) [@thinkmusic](https://discuss.elastic.co/u/thinkmusic)\
**Post date:** [August 4, 2014, 4:58pm UTC](https://discuss.elastic.co/t/filtering-aggs-by-most-terms/19079/1 "2014-08-04T16:58:28Z")

</div>

From a list of terms, I'm trying to find all the records that have those  
terms in a specific field and aggregate on that field. As an example, I  
have a list of records that contain a city name. I'd like the user to free  
form type words (some of which would be the city name). Then I'd like to  
see the top cities that have the most terms that match in them. This sort  
of works but it seems to return all the records that have the most single  
terms (lake) rather than the most terms that match. I do eventually get  
"Mayfield Lake" but it can be far at the bottom since there is only a few  
mayfields. Any suggestions on the best way to filter or only return records  
that contain the most terms. Should this be part of the query? Can I sort  
results in an Agg by relevance from the query?

"aggs": {  
"cities": {  
"filter": {  
"bool": {  
"should": [

[{"term":{"city":"mayfield"}},{"term":{"city":"lake"}},{"term":{"city":"capitol"}},{"term":{"city":"the"}}]  
]  
}  
},  
"aggs": {  
"cities": {  
"terms": {  
"field": "cityState.raw"  
}  
}  
}  
},

example result:

aggregations: {

- 
  - 

cities: {  
- doc\_count: 750  
- -  
cities: {  
- -  
buckets: [  
- -  
{  
- key: "Moses Lake, WA"  
- doc\_count: 250  
}  
- -  
{  
- key: "Bonney Lake, WA"  
- doc\_count: 200  
}  
- -  
....

--  
You received this message because you are subscribed to the Google Groups "elasticsearch" group.  
To unsubscribe from this group and stop receiving emails from it, send an email to [elasticsearch+unsubscribe@googlegroups.com](mailto:elasticsearch+unsubscribe@googlegroups.com).  
To view this discussion on the web visit [https://groups.google.com/d/msgid/elasticsearch/9ee290e0-9014-41a9-ae7d-fb8596616ca5%40googlegroups.com](https://groups.google.com/d/msgid/elasticsearch/9ee290e0-9014-41a9-ae7d-fb8596616ca5%40googlegroups.com).  
For more options, visit [https://groups.google.com/d/optout](https://groups.google.com/d/optout).

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 6, 2017, 1:10am UTC](https://discuss.elastic.co/t/filtering-aggs-by-most-terms/19079/2 "2017-07-06T01:10:55Z")

</div>

Closed on July 6, 2017, 1:10am UTC


