# Query to get and Sort based on Most occurrence of a field value

**URL:** <https://discuss.elastic.co/t/query-to-get-and-sort-based-on-most-occurrence-of-a-field-value/233004>\
**Category:** Elasticsearch\
**Created:** [May 17, 2020, 4:44pm UTC](https://discuss.elastic.co/t/query-to-get-and-sort-based-on-most-occurrence-of-a-field-value/233004 "2020-05-17T16:44:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![KVN\_REDDY](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/kvn_reddy/32/45191_2.png) [@KVN\_REDDY](https://discuss.elastic.co/u/KVN_REDDY)\
**Post date:** [May 17, 2020, 4:44pm UTC](https://discuss.elastic.co/t/query-to-get-and-sort-based-on-most-occurrence-of-a-field-value/233004/1 "2020-05-17T16:44:16Z")

</div>

Hi,

I am working on Recommendation engine where trying to retrieve the purchase data, I need to sort the data based on most occurrence means in order index productId is one of the field.  
For ex :  
o111, prod111,  
o222, prod222,  
o333, prod111,  
o444, prod333,  
o555, prod222,  
o666, prod111

I want to get the data as below  
o111, prod111,  
o333, prod111,  
o666, prod111,  
o222, prod222,  
o555, prod222,  
o444, prod333,

I am using Java high level rest client, Please suggest me the elastic search query and java example if possible.

ThanksInAdvance.

---

<div class="post-metadata">

**Author:** ![polyfractal](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/polyfractal/32/48162_2.png) [@polyfractal](https://discuss.elastic.co/u/polyfractal)\
**Post date:** [May 18, 2020, 5:28pm UTC](https://discuss.elastic.co/t/query-to-get-and-sort-based-on-most-occurrence-of-a-field-value/233004/2 "2020-05-18T17:28:23Z")

</div>

You should be able to just use the query sorting capability to sord by `productId` ASC: [https://www.elastic.co/guide/en/elasticsearch/reference/7.x/search-request-body.html#request-body-search-sort](https://www.elastic.co/guide/en/elasticsearch/reference/7.x/search-request-body.html#request-body-search-sort)

In java, you can use a `FieldSortBuilder`: [https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-search.html#\_specifying\_sorting](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-search.html#_specifying_sorting)

---

<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:** [June 15, 2020, 5:28pm UTC](https://discuss.elastic.co/t/query-to-get-and-sort-based-on-most-occurrence-of-a-field-value/233004/3 "2020-06-15T17:28:29Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
