Sort multiple doc types, but different field names


(Ben George) #1

I have two documents that both have date fields that I want to sort by, but they have different names.

I can use unmatched type in the sort eg:

{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "doctType1DateField": {
        "unmapped_type": "date"
      }
    },
    {
      "doctType2DateField": {
        "unmapped_type": "date"
      }
    }
  ]
}

However this will put all the docType1 records (in order) followed by docType2 records (in order).

I know I could add mappings so I end up with a field in both documents with same name, but I want to know if I can achieve a true sort in this case using just a query.


(Ivan Brusic) #2

You can use script-based sorting:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html#_script_based_sorting

It will have a small cost performance, so avoid it if you are scoring large
volumes of documents. You can always sort normally and then apply the sort
script on the top n documents using the rescorer:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-rescore.html

Ivan


(system) #3