使用 "must_not exists" 使用 elasticsearch_dsl

Use "must_not exists" using elasticsearch_dsl

对于我的一个项目,我需要确定我的 ES 索引中缺少字段的所有记录。 请参阅下面我的 ES 索引中存储的数据示例:

{
  "schema": "https://sample.org/schemas/user_v0.0.1.json",
  "barcode": "210000001",
  "birth_date": "1961-11-24", 
  "first_name": "John",
  "last_name": "Doe",
  "subscriptions": [
    {
      "end_date": "2021-03-30",
      "start_date": "2020-03-30"
    }
  ]
}, {
  "schema": "https://sample.org/schemas/user_v0.0.1.json",
  "barcode": "210000002",
  "birth_date": "1980-03-17", 
  "first_name": "Bob",
  "last_name": "Smith",
  "subscriptions": []
}, {
  "schema": "https://sample.org/schemas/user_v0.0.1.json",
  "barcode": "210000003",
  "birth_date": "1980-03-17", 
  "first_name": "Patty",
  "last_name": "Smith"
}

我想确定我的哪些用户没有任何订阅。在我的示例中,应该返回 'Bob Smith' 和 'Patty Smith'。我需要使用 Python ElasticSearch DSL 查询来做到这一点。

此时,我可以过滤我的搜索以仅检索用户,但尽管尝试了很多次,但我没有找到仅检索用户 "must_not" + "exists" 订阅的方法。

results = Search()\
          .filter('term', schema='https://sample.org/schemas/user_v0.0.1.json')
          # complete filter with : "Must not exists subscription"
          .source('barcode')
          .scan()

感谢您的帮助

我继续搜索和测试,似乎我找到了解决问题的方法

    query = Search()\
        .filter('term', schema='https://sample.org/schemas/user_v0.0.1.json')\
        .filter('bool', must_not=[Q('exists', field="subscriptions")])\
        .source('barcode')\
        .scan()

希望对大家有所帮助!

我不熟悉 Python DSL,但是用于查找那些没有任何订阅的用户的 REST 查询是:

    {
     "query": {
    "bool": {
      "must_not": [
        {
          "nested": {
            "path": "subscriptions",
            "query": {
              "exists": {
                "field": "subscriptions"
              }
            }
          }
        }
      ]
    }
  }