How to search for "foo ba*" in elastic search?

Viewed 25

There are match_phrase queries in Elasticsearch and there are also wildcard queries. Is there a way to combine the two to search something like "foo ba*"?

1 Answers

The answer to this question lies in using "Span Queries". As mentioned in the official documentation:

Span queries are low-level positional queries which provide expert control over the order and proximity of the specified terms.

The final query would look something like this:

{
    "query": {
        "span_near" : {
            "clauses" : [
                { "span_term" : { "field" : "foo" } },
                { "span_multi" : { "match": { "wildcard": { "field" : "ba*" } } } }
            ],
            "slop" : 0,
            "in_order" : true
        }
    }
}

NOTE:

  1. slop is used to mention how far can the different "span terms" be. Here since we want them to be adjacent to each other, we specified the slop to be 0.
  2. in_order is for whether the order of terms is important. In our case, it is - hence true.
Related