2016-07-21 14 views
0

我有一个包含多个角色文件/右定义为嵌套对象的数组:elasticsearch - 通过精确匹配一个嵌套的对象找到文件

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

我想具体roleRights过滤出的文档,但我查询似乎混合组合。这是我filterQuery为“伪”

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

以上应该只返回已分配右2

作用1

  • 文件,但它看起来像我得到

    • 所有具有角色1分配的文档无视权利
    • 以及所有权利为2的所有文档均不承担任何责任。

    任何提示?

+0

你可以分享你的映射呢? 'roleRights'很可能不是嵌套类型,它应该是。 – Val

+0

你是对的。 roleRights未映射为嵌套。这真的有必要吗?我是否需要使用nestedQueries? – Philipp

+0

是的,这是必要的。请参阅下面的答案。 – Val

回答

1

您需要映射roleRightsnested(见good explanation here),如下图所示:

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

确保先删除索引,重新创建和重新填充它。

然后,你就可以让你的查询是这样的:

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

Bravo!非常感谢你!刚刚发现这个[link](https://www.elastic.co/guide/en/elasticsearch/guide/current/complex-core-fields.html#object-arrays) - >用“数组对象”解释我的问题 – Philipp

+0

很高兴帮助! – Val