RedGiant
RedGiant

Reputation: 4748

Searching for multiple values in exact order in Elasticsearch

I'm looking for a way to do an exact array match in which the items must be in order.

example documents:

{"id": 1, "categories" : ["A", "C","E"]}
{"id": 2, "categories" : ["A", "C"]}
{"id": 3, "categories" : ["C", "A"]}

When I search with "A" AND "C", it will only return the first and third documents

{"id": 1, "categories" : ["A", "C","E"]}
{"id": 2, "categories" : ["A", "C"]}

The third one shouldn't be returned because the order doesn't match.

I have tried the following query but it will still return the third document because it doesn't take order in consideration:

{
    "sort": [
      {
        "modified": {
          "order": "desc"
        }
      }
    ],
    "query": {
      "bool": {
        "filter": {
          "bool": {
            "must": [
              {
                "term": {
                  "categories": "A"
                }
              },
              {
                "term": {
                  "categories": "C"
                }
              }
            ]
          }
        }
      }
    }
  }

I have more than 50 fields that I want to provide this exact order search option, so I prefer not adding extra field serving as a categories keyword and querying with "AC", {"id": 1, "categories" : ["c", "d"], "categorieskey" : "cd"}

is there any other ways of doing it?

Upvotes: 2

Views: 426

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52368

You need to add that categorieskey field because:

  • this should give the best performance when it comes to searching. Just matching an exact value in a field (basically a term filter, nothing complex)
  • I don't think there is an easy way for this. Even if you wouldn't use categorieskey Elasticsearch has no way in knowing the order of those terms. And to perform a search/filter on the _source is painful, uses many resources and the searches will not be fast at all

All in all, go ahead an add that field, this is the best approach in my opinion.

Upvotes: 5

Related Questions