0

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

  • documents that have role 1 assigned with right 2.

But it looks like i get

  • all document that have role 1 assigned disregarding the right
  • and all documents that have right 2 assigned disregarding the role.

Any hints?

Philipp
  • 4,180
  • 7
  • 27
  • 41
  • Can you share your mapping as well? It's likely that `roleRights` is not of `nested` type and it should. – Val Jul 21 '16 at 08:21
  • Your're right. roleRights is not mapped as nested. Is this really necessary? And would i need to use nestedQueries? – Philipp Jul 21 '16 at 08:21
  • Yes, that's necessary. See my answer below. – Val Jul 21 '16 at 08:27

1 Answers1

2

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}
                  }
               }
            }
         ]
      }
   }
}
Val
  • 207,596
  • 13
  • 358
  • 360
  • Bravo! Thank you very much! Just found this [link](https://www.elastic.co/guide/en/elasticsearch/guide/current/complex-core-fields.html#object-arrays) -> explains my problem with "array of objects" – Philipp Jul 21 '16 at 08:29