# TermsAggregation : sort by score to get relavant document on top - Please help

**URL:** <https://discuss.elastic.co/t/termsaggregation-sort-by-score-to-get-relavant-document-on-top-please-help/218782>\
**Category:** Elasticsearch\
**Created:** [February 11, 2020, 2:06pm UTC](https://discuss.elastic.co/t/termsaggregation-sort-by-score-to-get-relavant-document-on-top-please-help/218782 "2020-02-11T14:06:11Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Chetan\_Ramaiah](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/chetan_ramaiah/32/48571_2.png) [@Chetan\_Ramaiah](https://discuss.elastic.co/u/Chetan_Ramaiah)\
**Post date:** [February 11, 2020, 2:06pm UTC](https://discuss.elastic.co/t/termsaggregation-sort-by-score-to-get-relavant-document-on-top-please-help/218782/1 "2020-02-11T14:06:12Z")

</div>

I have an index which contain documents with same employee name and email address but varies with other information such as meetings attended and amount spent.

```auto
{
   "emp_name" : "Raju",
   "emp_email" : "raju@abc.com",
   "meeting" : "World cup 2019",
   "cost" : "2000" 
}

{
   "emp_name" : "Sanju",
   "emp_email" : "sanju@abc.com",
   "meeting" : "International Academy",
   "cost" : "3000" 
}

{
   "emp_name" : "Sanju",
   "emp_email" : "sanju@abc.com",
   "meeting" : "School of Education",
   "cost" : "4000" 
}

{
   "emp_name" : "Sanju",
   "emp_email" : "sanju@abc.com",
   "meeting" : "Water world",
   "cost" : "1200" 
}

{
   "emp_name" : "Sanju",
   "emp_email" : "sanju@abc.com",
   "meeting" : "Event of Tech",
   "cost" : "5200" 
}

{
   "emp_name" : "Bajaj",
   "emp_email" : "bajaju@abc.com",
   "meeting" : "Event of Tech",
   "cost" : "4500" 
}

```

Now, when I do search based on emp\_name field like "raj" then I should get one of the Raju, Sanju and Bajaj document since I am using fuzzy search functionality (fuzziness(auto)).

I am implementing elasticsearch using Java High level rest client 6.8 API.

```auto
TermsAggregationBuilder termAggregation = AggregationBuilders.terms("employees")
            .field("emp_email.keyword")
            .size(2000);

    TopHitsAggregationBuilder termAggregation1 = AggregationBuilders.topHits("distinct")
            .sort(new ScoreSortBuilder().order(SortOrder.DESC))
            .size(1)
            .fetchSource(includeFields, excludeFields);

```

Based on the above code, it's getting distinct documents but Raju's record is not on the top of the response instead we see Sanju document due to the number of counts.

Below is the JSON created based on the searchrequest.

```auto
{
  "size": 0,
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "raj",
            "fields": [
              "emp_name^1.0",
              "emp_email^1.0"
            ],
            "boost": 1.0
          }
        }
      ],
      "filter": [
        {
          "range": {
            "meeting_date": {
              "from": "2019-12-01",
              "to": null,
              "boost": 1.0
            }
          }
        }
      ],
      "adjust_pure_negative": true,
      "boost": 1.0
    }
  },
  "aggregations": {
    "employees": {
      "terms": {
        "field": "emp_email.keyword",
        "size": 2000,
        "min_doc_count": 1,
        "shard_min_doc_count": 0,
        "show_term_doc_count_error": false,
        "order": [
          {
            "_count": "desc"
          },
          {
            "_key": "asc"
          }
        ]
      },
      "aggregations": {
        "distinct": {
          "top_hits": {
            "from": 0,
            "size": 1,
            "version": false,
            "explain": false,
            "_source": {
              "includes": [
                "all_uid",
                "emp_name",
                "emp_email",
                "meeting",
                "country",
                "cost"
              ],
              "excludes": [

              ]
            },
            "sort": [
              {
                "_score": {
                  "order": "desc"
                }
              }
            ]
          }
        }
      }
    }
  }
}

```

I think if we order by max\_score or \_score then Raju's record will be on top of the response.

Could you please let me know how to get order by \_score or max\_score of the document returned by response?

Sample response is

```auto
{
  "took": 264,
  "timed_out": false,
  "_shards": {
    "total": 3,
    "successful": 3,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 232,
    "max_score": 0.0,
    "hits": [

    ]
  },
  "aggregations": {
    "sterms#employees": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "Sanju",
          "doc_count": 4,
          "top_hits#distinct": {
            "hits": {
              "total": 4,
              "max_score": 35.71312,
              "hits": [
                {
                  "_index": "indexone",
                  "_type": "employeedocs",
                  "_id": "1920424",
                  "_score": 35.71312,
                  "_source": {
                    "emp_name": "Sanju",
                      ...
                   }
            }
          ]
        }
      }
    }, 
    {
          "key": "Raju",
          "doc_count": 1,
          "top_hits#distinct": {
            "hits": {
              "total": 1,
              "max_score": 89.12312,
              "hits": [
                {
                  "_index": "indexone",
                  "_type": "employeedocs",
                  "_id": "1920424",
                  "_score": 89.12312,
                  "_source": {
                    "emp_name": "Raju",
                      ...
                   }
            }
          ]
        }
      }
    }

```

Let me know if you have any question.

**Note:** I see many similar kind of questions but none of them helped me. Please advise.

Thanks, Chetan

---

<div class="post-metadata">

**Author:** ![Chetan\_Ramaiah](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/chetan_ramaiah/32/48571_2.png) [@Chetan\_Ramaiah](https://discuss.elastic.co/u/Chetan_Ramaiah)\
**Post date:** [February 12, 2020, 2:33pm UTC](https://discuss.elastic.co/t/termsaggregation-sort-by-score-to-get-relavant-document-on-top-please-help/218782/2 "2020-02-12T14:33:35Z")

</div>

Hi, I don't see any response. Please let me know if any details required or any confusion with my question.

---

<div class="post-metadata">

**Author:** ![Mark\_Harwood](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mark_harwood/32/10538_2.png) [@Mark\_Harwood](https://discuss.elastic.co/u/Mark_Harwood)\
**Post date:** [February 12, 2020, 2:44pm UTC](https://discuss.elastic.co/t/termsaggregation-sort-by-score-to-get-relavant-document-on-top-please-help/218782/3 "2020-02-12T14:44:26Z")

</div>

If I understand correctly you want to sort the terms agg's name values by top score so you'll need something like this:

```
GET /indexone/_search
{
  "query": {
	"match": {
	  "emp_name": "raju"
	}
  },
  "size": 0,
  "aggs": {
	"topCos": {
	  "terms": {
		"field": "emp_email.keyword",
		"order": {
		  "topscore": "desc"
		}
	  },
	  "aggs": {
		"topscore": {
		  "max": {
			"script": {
			  "source": "_score"
			}
		  }
		},
		"hits": {
		  "top_hits": {
			"size": 2
		  }
		}
	  }
	}
  }
}
```

---

<div class="post-metadata">

**Author:** ![Chetan\_Ramaiah](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/chetan_ramaiah/32/48571_2.png) [@Chetan\_Ramaiah](https://discuss.elastic.co/u/Chetan_Ramaiah)\
**Post date:** [February 12, 2020, 5:04pm UTC](https://discuss.elastic.co/t/termsaggregation-sort-by-score-to-get-relavant-document-on-top-please-help/218782/4 "2020-02-12T17:04:53Z")

</div>

@Mark_Harwood, It worked, thank you very much.

---

<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:** [March 11, 2020, 5:05pm UTC](https://discuss.elastic.co/t/termsaggregation-sort-by-score-to-get-relavant-document-on-top-please-help/218782/5 "2020-03-11T17:05:06Z")

</div>

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