环境
elasticsearch:6.7
嵌套查询中字段不存在
如下:
POST players/players/_search
{
"query": {
"bool": {
"filter": [
{
"nested": {
"path": "features",
"query": {
"bool": {
"must_not": [
{
"exists": {
"field": "features" // 或者"field": "features.comment"
}
}
]
}
}
}
}
]
}
}
}
我们知道查询某个字段不存在,官方的文档:
curl -X GET "localhost:9200/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"bool": {
"must_not": {
"exists": {
"field": "user"
}
}
}
}
}
'
所以我们也就会自然而然的在嵌套查询里把其加上类似的写法。
但是老外的评论里,给出的写法是:
If instead of putting the must_not inside your nested query, you put the nested query inside of a must_not, it should work:
中文是说:不是将must_not
放到嵌套查询中里,而是将嵌套查询放到must_not
中。
POST players/players/_search
{
"query": {
"bool": {
"must_not": [
{
"nested": {
"path": "features",
"query": {
"exists": {
"field": "features"
}
}
}
}
]
}
}
}
我的理解
把must_not
放到嵌套查询中,会有个逻辑问题。嵌套查询是通过path
来指定路径的。我们可以抽象的理解为:你已经进入了房间,却要在房间里判断这个房间是否存在。要判断房间是否存在应该在房间的外面才行。