Elasticsearch: sort inner hits using query ordering

Viewed 1374

I have indexed a bunch of documents, each of which contains tags as nested documents, which I get back as "inner_hits". My query and the nested documents are keyword tokenized, and I'm only interested in exact matches between them.

I want elasticsearch to return me the documents that have matches, and to sort the "inner_hits" based on the order the query terms matched the nested documents. Is this possible?

For example, imagine I have the document "ferrari" with the tags red and car. if I search for the query "red sports car", I want ES to return me the document "ferrari" with nested documents "red" and "car" in that order.

This is so that when my user searches for "red sports car", I can say:

Found ferrari matching red car

I don't want to say:

Found ferrari matching car red

Can this be done? At the moment I get back the inner hits sorted by score, and apparently I can change this using sort, but I don't know how to refer to the ordering of the query.

Here are the mappings:

{
  "vehicles": {
    "mappings": {
      "vehicle": {
        "properties": {
          "name": {
            "type": "text"
          },
          "tags": {
            "type": "nested",
            "properties": {
              "name": {
                "type": "text",
                "analyzer": "tags"
              }
            }
          }
        }
      }
    }
  }
}

Here's the shape of the doc:

{
  "_index": "vehicles",
  "_type": "vehicle",
  "_id": "b1013ec8b8",
  "_source": {
    "name": "ferrari",
    "tags": [
      {
        "name": "car"
      },
      {
        "name": "red"
      }
    ]
  }
}

Here's the query:

{  
  "query":{  
    "nested":{  
      "path":"tags",
      "query":{  
        "terms":{  
          "tags.name":[  
            "red",
            "sports",
            "car"
          ]
        }
      },
      "inner_hits":{  
        "size":100
      }
    }
  }
}

I've had to heavily edit these to show what's going on, so apologies if they aren't syntactically correct, they should show the gist.

0 Answers
Related