elastic/elasticsearch

painless _score script with value_type double returns null or 0.0

Open

#26,294 opened on Aug 18, 2017

View on GitHub
 (8 comments) (0 reactions) (0 assignees)Java (76,700 stars) (25,882 forks)batch import
:Analytics/Aggregations>bugTeam:Analyticshelp wanted

Description

I have a client that wants to aggregate on the _score of a doc (don't ask). I can accomplish this using a painless inline script. This works until I want to sort those values by term because the value is treated as a string. Simple enough, figured we can just set value_type to double so it is treated a numeric value. Unfortunately this falls over and all docs get 0.0 as their score in 6.0.0-beta1 or return a NPE in 5.x.

Any ideas? Here is a working example where the result should be terms aggregation with values in the following order: 510, 54, 5.

#!/bin/bash

curl -XPUT -H"Content-Type: application/json" 'http://localhost:9200/test' -d '{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0,
  },
  "mappings": {
    "test": {
      "properties": {
        "field": {"type": "keyword"}
      }
    }
  }
}'

curl -XPUT -H"Content-Type: application/json" 'http://localhost:9200/test/test/1' -d '{"field": "a"}'
curl -XPUT -H"Content-Type: application/json" 'http://localhost:9200/test/test/2' -d '{"field": "b"}'
curl -XPUT -H"Content-Type: application/json" 'http://localhost:9200/test/test/3?refresh' -d '{"field": "c"}'


curl -XPOST -H"Content-Type: application/json" 'http://localhost:9200/test/_search?pretty' -d '{
  "size": 0,
  "query": {
    "dis_max": {
      "tie_breaker": 0.0,
      "queries": [
        {"constant_score":{"filter":{"term":{"field":{"value":"c","boost":1.0}}},"boost":510.0}},
        {"constant_score":{"filter":{"term":{"field":{"value":"b","boost":1.0}}},"boost":5.0}},
        {"constant_score":{"filter":{"term":{"field":{"value":"a","boost":1.0}}},"boost":54.0}}
      ],
      "boost":1.0
    }
  },
  "aggregations": {
    "scoreAgg": {
      "terms": {
        "script": {
          "inline":"_score",
          "lang":"painless"
        },
        "order": {
          "_term":"desc"
        }
      }
    }
  }
}'

curl -XPOST -H"Content-Type: application/json" 'http://localhost:9200/test/_search?pretty' -d '{
  "size": 0,
  "track_scores": true,
  "query": {
    "dis_max": {
      "tie_breaker": 0.0,
      "queries": [
        {"constant_score":{"filter":{"term":{"field":{"value":"c","boost":1.0}}},"boost":510.0}},
        {"constant_score":{"filter":{"term":{"field":{"value":"b","boost":1.0}}},"boost":5.0}},
        {"constant_score":{"filter":{"term":{"field":{"value":"a","boost":1.0}}},"boost":54.0}}
      ],
      "boost":1.0
    }
  },
  "aggregations": {
    "scoreAgg": {
      "terms": {
        "script": {
          "inline":"_score",
          "lang":"painless"
        },
        "order": {
          "_term":"desc"
        },
        "value_type": "double"
      }
    }
  }
}'

Contributor guide