Elasticsearch无法准确查询Document中的数组Field

时间:2016-09-03 04:01:36

标签: elasticsearch nested nest

我在elasticsearch类型中有以下数据,名为' bank'

[
    {
        "_id": "1",
        "name": "ICIC",
        "balance": "$2,574.27",
        "friends": [
            {
                "roleid": 0,
                "name": "Alana Shepard",
                "isactive": true
            },
            {
                "roleid": 1,
                "name": "Katheryn Hatfield",
                "isactive": false
            }
        ]
    },
    {
        "_id": "2",
        "name": "SBK",
        "balance": "$2,346.44",
        "friends": [
            {
                "roleid": 0,
                "name": "Hinton Kaufman",
                "isactive": true
            },
            {
                "roleid": 1,
                "name": "Miles Alford",
                "isactive": true
            }
        ]
    }
]

现在我尝试获取 friends.roleid = 1和friends.isactive = true 的文档。请求的DSL查询如下,

{
    "query": {
        "bool": {
            "must": [
                {
                    "term": {
                        "friends.roleid": {
                            "value": 1
                        }
                    }
                },
                {
                    "term": {
                        "friends.isactive": {
                            "value": true
                        }
                    }
                }
            ]
        }
    }
}

预期的结果是 _id = 2 的对象。但实际结果是_id = 1和_id = 2。如果有人帮助找到DSL查询中的问题,将不胜感激。谢谢

1 个答案:

答案 0 :(得分:1)

修复问题的方法是将Field“friends”作为嵌套对象。并且DSL查询重建如下,

{
    "query": {
        "nested": {
            "path": "friends",
            "query": {
                "bool": {
                    "must": [
                        {
                            "term": {
                                "friends.roleid": {
                                    "value": 1
                                }
                            }
                        },
                        {
                            "term": {
                                "friends.isactive": {
                                    "value": "true"
                                }
                            }
                        }
                    ]
                }
            }
        }
    }
}

DSL查询中的路径指定嵌套对象。 elasticsearch文档参考installer on majorgeeks将有很大帮助。