Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch aggregation order by top hit score

I want to order buckets by doc.score of top_hit. My current implementation is below.

  group_by_iid: {
    terms: {
      field: 'iid',
      order: { max_score: 'desc' },
      size: 0
    },
    aggs: {
      max_score: { max: { script: 'doc.score' } },
      top_hit: {
        top_hits: {
          sort: [{ source_priority: { order: 'desc' } }],
          size: 1
        }
      }
    }
  }

This is wrong because buckets are ordered by their top score, not their top source_priority document's score. Is there a way to solve this problem?

like image 528
pandora2000 Avatar asked Oct 06 '14 09:10

pandora2000


People also ask

What is top hits aggregation Elasticsearch?

A top_hits metric aggregator keeps track of the most relevant document being aggregated. This aggregator is intended to be used as a sub aggregator, so that the top matching documents can be aggregated per bucket.

Is Elasticsearch good for aggregation?

Elasticsearch Aggregations provide you with the ability to group and perform calculations and statistics (such as sums and averages) on your data by using a simple search query. An aggregation can be viewed as a working unit that builds analytical information across a set of documents.

What is Bucket aggregation in Elasticsearch?

Bucket aggregations don't calculate metrics over fields like the metrics aggregations do, but instead, they create buckets of documents. Each bucket is associated with a criterion (depending on the aggregation type) which determines whether or not a document in the current context "falls" into it.


1 Answers

I had the same issue, and the way I resolved it was to introduce a sub-aggregation on the docs score. Then in my outer aggregation, I ordered by name of the max_score aggregation.

GET /my-index/my-type/_search

{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "searchTerm": {
              "query": "style",
              "type": "boolean"
            }
          }
        },
        {
          "flt_field": {
            "searchTerm": {
              "like_text": "style"
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "group_by_target_url": {
      "terms": {
        "field": "targetUrl",
        "order": {
          "max_score": "desc"
        }
      },
      "aggs": {
        "max_score": {
          "max": {
            "script": "_score"
          }
        }
      }
    }
  }
}

I followed the directions on this link:

http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html

like image 64
Roy Kachouh Avatar answered Oct 17 '22 04:10

Roy Kachouh