首页 > 解决方案 > 你如何过滤非空值弹性搜索?

问题描述

我正在尝试过滤掉不为 null 的值:

以 sql 为例

SELECT ALL FROM Mytable WHERE field_1 NOT NULL and field_2 ="alpha"

我应该如何在 elasticsearch-dsl(python) 中编写此查询?

我试过这样的事情:

s = Mytable.search().query(
Q('match', field_2 ='alpha')
).filter(~Q('missing', field='field_1'))

但它返回 field_1 为空值的元素

另外,我试过这个,但它没有用

field_name_1 = 'field_2'
value_1 = "alpha"
field_name_2 = 'field_1'
value_2 = " "
filter = { 
    "query": {
        "bool": {
        "must": [
            {
            "match": {
                field_name_1 : value_1
            }
            },
            {
            "bool": {
                "should": [
                    {
                    "bool": {
                        "must_not": [
                            {
                                field_name_2: {
                                    "textContent": "*"
                                }
                            }
                        ]
                    } }
                ]
            }
            }
        ]
        }
    }
    }
  

标签: pythonelasticsearchelasticsearch-dsl

解决方案


我不熟悉 elasticsearch-dsl(python),但是以下搜索查询将为您提供与您想要的相同的搜索结果:

SELECT ALL FROM Mytable WHERE field_1 NOT NULL and field_2 ="alpha"

在下面的搜索查询的帮助下,搜索结果将是name="alpha"ANDcost字段not be null。您可以参考存在查询以了解更多信息。

指数数据:

 {  "name": "alpha","item": null }
 {  "name": "beta","item": null  }
 {  "name": "alpha","item": 1    }
 {  "name": "alpha","item": []   }

搜索查询:

您可以将 bool 查询与 exists 查询结合起来,如下所示:

    {
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "name": "alpha"
          }
        },
        {
          "exists": {
            "field": "item"
          }
        }
      ]
    }
  }
}

搜索结果:

"hits": [
  {
    "_index": "my-index",
    "_type": "_doc",
    "_id": "4",
    "_score": 1.6931472,
    "_source": {
      "name": "alpha",
      "item": 1
    }
  }
]

推荐阅读