3

I'm trying to query documents where the nested array contains all of the elements passed in the query.

The index stores groups and each group has a list of members. I want to query all the groups that contains the given members.

Mapping:

"properties" : {
   "members" : {
      "type" : "nested",
      "properties" : {
         "name" : {
            "type" : "keyword"
         }
       }
    },
    "name" : {
        "type" : "text"
     }
   }
  }
}

Example content:

[
  {
    "name" : "group 1",
    "members" : [
      {
        "name" : "alice"
      },
      {
        "name" : "bob"
      }
    ]
  },
  {
    "name" : "group 2",
    "members" : [
      {
        "name" : "alice"
      },
      {
        "name" : "foo"
      },
      {
        "name" : "bob"
      }
    ]
  },
  {
    "name" : "group 3",
    "members" : [
      {
        "name" : "foo"
      },
      {
        "name" : "bar"
      }
    ]
  }
]

How can I find all groups that have both "alice" and "foo" as members?

I have tried the following query but it returns nothing:

GET /group/_search
{
  "query": {
    "nested": {
      "path": "members",
      "query": {
        "bool": {
          "must": [
            {"match": {"members.name": "alice"}},
            {"match": {"members.name": "foo"}}
          ]
        }
      }
    }
  }
}

I have also tried with term instead of match but it gives no results.

1 Answer 1

3

You can use the nested within a must clause. Like this:

GET /group/_search
{
 "query": {
   "bool": {
     "must": [
       {
         "nested": {
           "path": "members",
           "query": {
             "term": {
               "members.name": {
                 "value": "alice"
               }
             }
           }
         }
       },
       {
         "nested": {
           "path": "members",
           "query": {
             "term": {
               "members.name": {
                 "value": "foo"
               }
             }
           }
         }
       }
     ]
   }
 }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.