Multi-"match-phrase" query in Elastic Search

punkish picture punkish · May 4, 2015 · Viewed 25.3k times · Source

this should be obvious to me but is not. The following two-match only the second phase (in this case, Cape Basin)

"query": {
  "match_phrase": {
    "contents": {
      "query": "St Peter Fm",
      "query": "Cape Basin"
    }
  }
}

"query": {
  "match_phrase": {
    "contents": {
      "query": ["St Peter Fm", "Cape Basin"]
    }
  }
}

while the following croaks with an error

"query": {
  "match_phrase": {
    "contents": {
      "query": "St Peter Fm"
    },
    "contents": {
      "query": "Cape Basin"
    }
  }
}

I want to match all documents that contain either phrases exactly as entered.

Answer

Jakub Kotowski picture Jakub Kotowski · May 4, 2015

Your first query is not really a valid JSON object because you use the same field name twice.

You can use a bool must query to match both phrases:

PUT phrase/doc/1
{
  "text": "St Peter Fm some other text Cape Basin"
}
GET phrase/_search
{
  "query": {
    "bool": {
      "must": [
         {"match_phrase": {"text":  "St Peter Fm"}},
         {"match_phrase": {"text":  "Cape Basin"}}
      ]
    }
 }
}