ElasticSearch Nested字段查询问题

环境:ES为7.10.2

数据-成员表,大概结构如下:

主键Id标题成员数据(nested结构:uid,uname)
11d1uid="f1",uname="灰太狼"、uid="f2",uname="蜗牛"
22d2uid="f1",uname="灰太狼"
PUT /f_data
{
  "mappings": {
    "properties": {
      "id":{"type": "keyword"},
      "title":{"type": "wildcard"},
      "members":{
        "type": "nested",
        "properties": {
          "uid":{"type":"keyword"},
          "uname":{"type":"wildcard"}
        } 
      }
    }
  }
}

测试数据如下:

PUT f_data/_doc/11
{"id":"11","title":"d1","members":[{"uid":"f1","uname":"灰太狼"},{"uid":"f2","uname":"蜗牛"}]}
PUT f_data/_doc/22
{"id":"22","title":"d2","members":[{"uid":"f1","uname":"灰太狼"}]}

针对members字段做 “无指定用户(uid)的数据”查询查询

查询条件:查询 members中无 f1 用户的数据
实现方式:基于nested查询+must_not查询
期望结果:无返回数据
实际结果:返回了d1数据

问题:如何通过查询实现此类需求

查询语句如下:

POST f_data/_search?filter_path=hits.hits._source
{
  "query": {
    "nested": {
      "path": "members",
      "query": {
        "bool": {
          "must_not": [
            {"term": {"members.uid": {"value": "f1"}}}
          ]
        }
      }
    }
  }
}

执行结果:

{
  "hits" : {
    "hits" : [
      {
        "_source" : {
          "id" : "11",
          "title" : "d1",
          "members" : [
            {
              "uid" : "f1",
              "uname" : "灰太狼"
            },
            {
              "uid" : "f2",
              "uname" : "蜗牛"
            }
          ]
        }
      }
    ]
  }
}

问题已解决:在你nested查询外部使用bool-must_not做约束

# 查询不存在==未填写;已存在取反,在nested之下取
POST f_data/_search?filter_path=hits.hits._source
{
  "query": {
    "bool": {
      "must_not": [
        {"nested": {
          "path": "members",
          "query": {
            "term": {"members.uid": {"value": "f1"}}
          }
        }}
      ]
    }
  }
}