0

I'm migrating my Elasticsearch queries from the 1.7 version to 5.0 (the latest at this moment) and I'm having some trouble with aggregations.

I want to do aggregation on a given field and show the top 5 documents ordered by score. From what I've read this used to be done like this:

"aggs" : {
    "max_price" : { "max" : { "script" : "_score" } }
}

Using Sense, the answer I get is "Unexpected token VALUE_STRING [script] in [top_score]."

Anyone went through this?

Note: For an older version an answer was posted here: ElasticSearch: aggregation on _score field?

Community
  • 1
  • 1

2 Answers2

0

The default scripting language for Elasticsearch is now Painless instead of groovy. According to How to use scripts, you could try:

"aggs" : {
    "max_price": {
        "max": {
            "script": {
                "lang": "groovy", 
                "inline": "_score"
            } 
        } 
    }
}

Updated in Elasticsearch 5.x, there will be deprecated logs like:

[WARN ][o.e.d.s.g.GroovyScriptEngineService] [groovy] scripts are deprecated, use [painless] scripts instead

The more correct way is:

"aggs" : {
    "max_price": {
        "max": {
            "script": {
                "lang": "painless", 
                "inline": "_score"
            } 
        } 
    }
}
mosyang
  • 1
  • 2
0

If you just need the top 5 documents by score, overall, for your search terms, you can just set the size of your query to 5 and that should do the trick (eg below)

{ "size": 5, "query": { "bool": { "must": [ { "match": { "my_field": "whatever" } }, { "match": { "my_other_field": "whatever else" } } ], "should": [], "must_not": [], "filter": [] } }, "aggs": { "something": { "terms": { "field": "my_term" }, "aggs": { "field_stats": { "stats": { "field": "price" } } } } } }

On the other hand, if you want the top 5 scoring documents for each bucket, have you considered using a top hits aggregation? https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-top-hits-aggregation.html

Evan Volgas
  • 2,900
  • 3
  • 19
  • 30