【问题标题】:Use "must_not exists" using elasticsearch_dsl使用 elasticsearch_dsl 使用“must_not exists”
【发布时间】:2023-03-19 21:57:02
【问题描述】:

对于我的一个项目,我需要确定我的 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()

感谢您的帮助

【问题讨论】:

    标签: python elasticsearch elasticsearch-dsl


    【解决方案1】:

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

        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()
    

    我希望它可以帮助别人!

    【讨论】:

    • 一个更简洁的写must_not exists的方法是使用.exclude()方法,像这样:.exclude("exists", field="subscriptions")
    • 什么问题?啊.... from elasticsearch_dsl import Q
    【解决方案2】:

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

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

    【讨论】:

    • 太棒了。但请注意,这仅适用于嵌套字段类型。
    猜你喜欢
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2021-09-05
    • 2023-03-05
    • 2011-10-28
    • 2010-12-08
    相关资源
    最近更新 更多