Query with different sort on different index

Having two index which got different field, could I put a query that sort by index name, and then sort on a field on one and sort on another on the second?

#In the two next query I aim to sort by "code_index1" if the document belong to index1 and by "this_field_of_index2" if the document belong to index2.

GET _search
{
  "sort": [
    {
      "_index": {
        "order": "asc"
      }
    },
    {
      "code_index1": {
        "order": "asc"
      }
    },
    {
      "this_field_of_index2": {
        "order": "asc"
      }
    },
  ]
}

Could a script help me?

GET index1,index2/_search
{
  "query": {
    "match_all": {}
    },
    "sort": {
    "_script": {
      "type": "string",
      "order": "asc",
      "script": {
        "lang": "painless",
        "source": "if (ctx._source ==~ params.foo) {return \"code_index1\"} "if (ctx._source ==~ params.bar) {return \"this_field_of_index2\"} else {ctx.op = 'noop'}",
            "params": {
           "foo": "index1"
           "bar": "index2"
            }
      }
    }
  }
}

Could I even do different sort based on a field of an index?

#Here I want to sort by age if code=child and 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) {return \"age\"} "if (ctx._source.code ==~ params.bar) {return \"city\"} else {ctx.op = 'noop'}",
            "params": {
           "foo": "child"
           "bar": "adult"
            }
      }
    }
  }
}

Obviously, none of the above queries work, I just wanted to show were I was at the moment. :thinking:
Maybe I just miss a little something in them.

I'v answer to the first question. :wink:
Still looking for the second one.

GET index1,index2/_search
{
  "query": {
    "match_all": {} 
    },
    "sort": {
    "_script": {
      "type": "string",
      "order": "asc",
      "script": {
        "lang": "painless",
        "source": "if (doc.containsKey('code_index1')) { doc['code_index1'].value } else { doc['this_field_of_index2'].value}"
      }
    }
  }
}

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