Hoa
Hoa

Reputation: 20438

In Elastic search, how do I match by multiple objects in an array of objects?

I'm following the example here:

https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html

The following query:

GET my_index/_search
{
  "query": {
    "nested": {
      "path": "user",
      "query": {
        "bool": {
          "must": [
            { "match": { "user.first": "Alice" }},
            { "match": { "user.last":  "White" }}
          ]
        }
      }
    }
  }
}

matches one record as expected. Suppose instead I only want to return documents which have both 'John Smith' and 'Alice White' as a user.

I have tried:

GET my_index/_search
{
  "query": {
    "nested": {
      "path": "user",
      "query": {
        "bool": {
          "must": [
            { "match": { "user.first": "Alice" }},
            { "match": { "user.last":  "White" }},
            { "match": { "user.first": "John" }},
            { "match": { "user.last":  "Smith" }}
          ]
        }
      }
    }
  }
}

but this returns zero results. How can I get documents with both 'Alice White' and 'John Smith' (which should just be the same document returned in the original result)?

Upvotes: 0

Views: 1064

Answers (1)

Lupanoide
Lupanoide

Reputation: 3212

You should use a bool query to combine more than one clause. With your syntax you are searching for a doc that has both Alice and John as value in the same field. Try, indeed:

{
  "query": {
    "bool": {
      "should": [
        {
          "nested": {
            "path": "user",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "user.first": "Alice"
                    }
                  },
                  {
                    "match": {
                      "user.last": "White"
                    }
                  }
                ]
              }
            }
          }
        },
        {
          "nested": {
            "path": "user",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "user.first": "John"
                    }
                  },
                  {
                    "match": {
                      "user.last": "Smith"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

Upvotes: 2

Related Questions