Elasticsearch 6.2.2 conditional sorting

I'm on Elasticsearch 6.2.2.
Could I do differents sorts based on a field of an index?

#Here I want to sort by age if code=child or by city if code=adult

GET index1/_search
{
  "query": {
    "match_all": {}
    },
    "sort": {
    "_script": {
      "type": "string",
      "order": "asc",
      "script": {
        "lang": "painless",
        "source": "if (ctx._source.code ==~ params.foo) {{doc['age'].value} if (ctx._source.code ==~ params.bar) {doc['city'].value} else {ctx.op = 'noop'}",
            "params": {
           "foo": "child"
           "bar": "adult"
            }
      }
    }
  }
}

Did I missed a detail or is it impossible to do in Elasticsearch?

You can may be do that with:

  • function score query
  • scripted score with painless

Thanks for the answers @dadoonet
I get how I can sort by scoring but not how the scoring could be influenced by one of the field of the said index.
Could something like this work (retaking the above example)?

"function_score": {
          "query": { "match_all": {} },
          "boost": "5", 
          "functions": [
 {
                  "filter": { "match": { "code": "child" } },
                    "sort": [
                    { "age" : "desc" }]
  }
    { 
       another filter with another sort
   }
},

There is an error that said that I should give a query for the sort since I extracted it to put it in the filter.

Moreover do you know why the example in the first message...:

GET index1/_search
{
  "query": {
    "match_all": {}
    },
    "sort": {
    "_script": {
      "type": "string",
      "order": "asc",
      "script": {
        "lang": "painless",
        "source": "if (ctx._source.code ==~ params.foo) {{doc['age'].value} if (ctx._source.code ==~ params.bar) {doc['city'].value} else {ctx.op = 'noop'}",
            "params": {
           "foo": "child",
           "bar": "adult"
            }
      }
    }
  }
} 

...would fail with the error :

  "type": "script_exception",
  "reason": "compile error",
  "script_stack": [
    "... ype_ent ==~ params.foo) {{doc['nom'].value} if (ct ...",
    "                             ^---- HERE"

Thanks, merci.

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