首页 > 解决方案 > 弹性搜索 - 过滤匹配值和数据类型的数据

问题描述

我正在使用 AWS 的 ES 5.7。弹性搜索集群中存储了对象列表。每个对象都有一个字段状态,其值为整数,但是由于索引器的一个编程错误,某些对象状态值存储为文本而不是整数。我需要使用状态为文本的布尔查询过滤对象。

我使用下面的查询来过滤数据。

样本数据

{  
   "took":22,
   "timed_out":false,
   "_shards":{  
      "total":16,
      "successful":16,
      "failed":0
   },
   "hits":{  
      "total":3208,
      "max_score":1,
      "hits":[  
         {  
            "_index":"entity-data",
            "_type":"account",
            "_id":"b7b46c",
            "_score":1,
            "_source":{  
               "status":"3"
            }
         },
         {  
            "_index":"entity-data",
            "_type":"account",
            "_id":"b7b46",
            "_score":1,
            "_source":{  
               "status":3
            }
         }
      ]
   }
}

用于根据状态进行过滤的布尔查询

{  
   "query":{  
      "bool":{  
         "filter":[  
            {  
               "term":{  
                  "status": "3"
               }
            }
         ]
      }
   }
}

Here "status": "3" and "status": 3 is providing same result. 

我需要过滤“状态”:“3”的数据。

任何建议都会有所帮助。提前致谢。

标签: elasticsearchtypesaws-elasticsearch

解决方案


您的脚本不起作用,因为该字段的映射将是类型long,并且在使用您编写的脚本进行搜索时,它只查看类型为 long 的倒排索引。

您可以使用无痛脚本来访问文档值并查找所有字符串值。该脚本检查字段的数据类型status并仅对字符串类型返回 true。因此,它将返回所有包含字符串值的文档。

PUT t1/doc/1
{
   "status": 3
}

PUT t1/doc/2
{
   "status": "3"
}



GET t1/_search
{
    "query": {
        "bool" : {
            "filter" : {
                "script" : {
                    "script" : {
                        "inline": "if(params._source.status instanceof String) return true;",
                        "lang": "painless"
                     }
                }
            }
        }
    }
}

输出:

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0,
    "hits": [
      {
        "_index": "t1",
        "_type": "doc",
        "_id": "2",
        "_score": 0,
        "_source": {
          "status": "3"
        }
      }
    ]
  }
}

附加信息:

如果您想将所有这些字符串值更改为 long,您可以reindex进入一个新索引并使用脚本来操作这些值。

//Create new index
PUT t2

//reindex from t1 to t2 and change string to integer
POST _reindex
{
  "source": {
    "index": "t1"
  },
  "dest": {
    "index": "t2"
  },
  "script": {
    "lang": "painless",
    "inline": "if(ctx._source.status instanceof String){ctx._source.status = Integer.parseInt(ctx._source.status)}"
  }
}

推荐阅读