Elasticsearch: Replicating Google's Double Quote Exact Match Query

In google when you put double quotes around a phrase it does an exact match.

I see in elasticsearch how I can do an exact match on a given field. But I don't see how I can do an exact match over all the fields.

How can I do an exact match over all the fields in my index?

I've search for this many times and all the examples show how to do it for a given field. Please note I want to do this for every single field in my index.

There's a special metadata field called _all which contains all values of all fields concatenated as one big string. You could query that field using a match_phrase query:

GET my_index/_search
{
  "query": {
    "match_phrase": {
      "_all": "my query"
    }
  }
}

However, _all may be disabled in your mappings, and it's going away in the upcoming 6 release of Elasticsearch, so a better alternative may be to execute a query_string query in which you do not provide an explicit field, and in which you put your query between quotes (note the escaping):

GET my_index/_search
{
  "query": {
    "query_string": {
      "query": "\"my query\""
    }
  }
}

Depending on whether _all is enabled or not, this query will query the _all field, or it will execute an "all" query against all fields.

Thanks Abdon!

What will be the behavior if I do:

GET my_index/_search
{
  "query": {
    "query_string": {
      "query": "test this \"my query\""
    }
  }
}

That query will default to an OR between test, this and the phrase "my query". So any document matching either of these three will be considered a match.

Great, thanks! Looks good. I should be able to easily swap this into my existing code. I just want to double check one thing for my understanding.

And are these the same behavior?

GET my_index/_search
{
  "query": {
     "bool": {
         "must": {
                 "query_string": {  "query": "regular search" }
          },
          ....
  }
}

and

GET my_index/_search
{
  "query": {
       "bool" {
           "must": {
                    "match": { "_all": "regular search" }
           },
           ...
  }
}

Yes, these should match the same documents.

Excellent, thanks!

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