gerky
gerky

Reputation: 6417

ElasticSearch - multi_match with AND/OR

I want to use multi_match across multiple fields in my index.

For example, I have this users index.

Users
id
real_name
contact_name
user_name

These fields are all using the standard analyzer. So I want to search these 3 fields (real_name, contact_name, user_name) and look for users who have both "John" and "Peter" in at least one of those fields.

I know I can use multi_match if I don't need the AND part. Example: only search for John:

{
  "multi_match" : {
    "query":    "john", 
    "fields": [ "real_name", "contact_name", "user_name" ] 
  }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html#query-dsl-multi-match-query

But how do I do it if I want additional and conditions. Is it possible to do this with multi_match?

Upvotes: 5

Views: 10186

Answers (2)

NicolasY
NicolasY

Reputation: 323

Use "operator" : "AND":

{
  "query": {
    "bool": {
      "should": [
        {
          "multi_match": {
            "query": "john",
            "fields": [
              "real_name",
              "contact_name",
              "user_name"
            ],
            "type": "cross_fields",
            "operator": "AND"
          }
        }
      ]
    }
  }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html#operator-min

Upvotes: 2

vinod_vh
vinod_vh

Reputation: 1061

Try this. John must be present in the real_name or contact_name or user_name.

{
"bool": {
    "should": [
        {
          "multi_match" : {
            "query":      "john",
            "type":       "cross_fields",
            "fields":     [ "real_name", "contact_name", "user_name" ],
            "minimum_should_match": "50%" 
          }
        }
    ]
  }
}

Upvotes: 0

Related Questions