轻松:检查单个文档是否包含密钥

时间:2018-11-23 23:17:24

标签: elasticsearch elasticsearch-painless

我正在使用painless用Elastic 5.5过滤文档

问题

使用“无痛”,在strings字段中查找文档。

预期结果

仅返回带有strings字段的文档

实际结果

所有文件都退回了。

观察

只要存在带有strings字段的文档,就会返回所有文档。这可能是某种缓存问题。

TestCase

固定装置

PUT /test_idx

POST /test_idx/t/1
{
      "strings": ["hello", "world"]
}

POST /test_idx/t/2
{
      "numbers": [1, 2, 3]
}

查询

GET /test_idx/_search
{
   "query": {
      "bool": {
         "filter": [
            {
               "script": {
                  "script": {
                     "lang": "painless",
                     "inline": "return doc.containsKey(params.keypath)",
                     "params": {"keypath": "strings"}
                  }
               }
            }
         ]
      }
   }
}

实际反应

{
   "took": 5,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0,
      "hits": [
         {
            "_index": "test_idx",
            "_type": "t",
            "_id": "2",
            "_score": 0,
            "_source": {
               "numbers": [
                  1,
                  2,
                  3
               ]
            }
         },
         {
            "_index": "test_idx",
            "_type": "t",
            "_id": "1",
            "_score": 0,
            "_source": {
               "strings": [
                  "hello",
                  "world"
               ]
            }
         }
      ]
   }
}

期望的响应

{
   "took": 5,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 0,
      "hits": [
         {
            "_index": "test_idx",
            "_type": "t",
            "_id": "1",
            "_score": 0,
            "_source": {
               "strings": [
                  "hello",
                  "world"
               ]
            }
         }
      ]
   }
}

2 个答案:

答案 0 :(得分:0)

为什么您需要这样做很轻松? exists query

可以轻松完成此操作
{
  "query": {
    "exists": {
      "field": "strings"
    }
  }
}

答案 1 :(得分:0)

即使出于性能原因强烈建议不要过度使用它,您也可能想尝试一下

GET /test_idx/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "script": {
            "script": {
              "lang": "painless",
              "inline": "return doc[params.keypath].value != null",
              "params": {
                "keypath": "strings.keyword"
              }
            }
          }
        }
      ]
    }
  }
}