在elasticsearch中查找空字符串

6

我想要搜索在某个字段中具有特定值的文档,需要使用_search命令。

{
  "query": {
      "bool": {
        "must": [
         {"field": {"advs.status": "warn"}}
       ]
      }
  }
}

这很好用。但是当我试图查找在该字段中具有空字符串的文档时,我会收到以下错误:

ParseException[Cannot parse '' ...

然后是一个长长的列表,列出了期望得到的字符串,而不是空字符串。

我尝试运行这个查询:

{
  "query": { 
    "bool": {
        "must": [
            {"term": {"advs.status": ""}}
         ]
        }
  }
}

它不会失败,但也找不到任何东西。相反,它只适用于非空字符串。我该怎么做?

对于此类型,我的映射看起来就像这样:

{
    "reports": {
        "dynamic": "false",
        "_ttl": {
            "enabled": true,
            "default": 7776000000
        },
        "properties": {
            "@fields": {
                "dynamic": "true",
                "properties": {
                    "upstream_status": {
                        "type": "string"
                    }
                }
            },
            "advs": {
                "properties": {
                    "status": {
                        "type": "string",
                        "store": "yes"
                    }
                }
            },
            "advs.status": {
                "type": "string",
                "store": "yes"
            }
        }
    }
}

我该如何启用JSON的语法高亮显示? - Evgeny Lazin
6个回答

6

另一种更有效的做法是使用exists过滤器:

"exists" : {
  "field" : "advs.status"
}

两种写法都是正确的,但这种写法更好 :)

2
您可以尝试这个临时解决方案,它可以工作但不是最佳选择 - https://github.com/elastic/elasticsearch/issues/7515
PUT t/t/1
{
"textContent": ""
}

PUT t/t/2
{
 "textContent": "foo"
}

GET t/t/_search
{
 "query": {
  "bool": {
   "must": [
    {
      "exists": {
        "field": "textContent"
      }
    }
  ],
  "must_not": [
    {
      "wildcard": {
        "textContent": "*"
      }
     }
   ]
  }
 }
}

1
如果您想搜索包含空字符串的字段,则可以将映射更改为将not_analyzed设置为此特定字段,或者您可以使用脚本过滤器:
"filter": {
  "script": {
    "script": "_source.advs.status.length() == 0"
  }
}

1

如果字段没有被分析,我通常会使用过滤器。以下是代码片段:

{
  "filtered": {
    "filter": {
      "term": {
        "field": ""
      }
    }
  }
},

1
尝试在您的布尔查询中使用missingmust_not
"must_not":{
  "missing":{
    "field":"advs.status",
    "existence":true,
    "null_value":true
  }
}

1
你能把这两个答案合并成一个吗? - David L

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接