Philipp
Philipp

Reputation: 4270

elasticsearch - find document by exactly matching a nested object

I have documents that contain multiple role/right definitions as an array of nested objects:

{
  ...
  'roleRights': [
    {'roleId':1, 'right':1},
    {'roleId':2, 'right':1},
    {'roleId':3, 'right':2},
  ]
}

I am trying to filter out document with specific roleRights, but my query seems to mix up combinations. Here is my filterQuery as "pseudoCode"

boolFilter > must > termQuery >roleRights.roleId: 1
boolFilter > must > termQuery >roleRights.type: 2

The above should only return

But it looks like i get

Any hints?

Upvotes: 0

Views: 532

Answers (1)

Val
Val

Reputation: 217254

You need to map roleRights as nested (see a good explanation here), like below:

PUT your_index
{
  "mappings": {
    "your_type": {
      "properties": {
        "roleRights": {
          "type": "nested",
          "properties": {
             "roleId": { "type": "integer" },
             "right": { "type": "integer" }
          }
        }
      }
    }
  }
}

Make sure to delete your index first, recreate it and re-populate it.

Then you'll be able to make your query like this:

POST your_index/_search
{
   "query": {
      "bool": {
         "must": [
            {
               "nested": {
                  "path": "roleRights",
                  "query": {
                     "term": { "roleRights.roleId": 1}
                  }
               }
            },
            {
               "nested": {
                  "path": "roleRights",
                  "query": {
                     "term": { "roleRights.type": 2}
                  }
               }
            }
         ]
      }
   }
}

Upvotes: 2

Related Questions