如何在elasticsearch中查询特殊字符

3

我有一条类似于以下内容的数据存储在Elasticsearch中:

   {"_index": "my_index",
    "_type": "my_type",
    "_id": "test_id",
    "_version": 1,
    "_score": 1,
    "_source": {
        "d2": "*",
        "d1": "test_data"
    }}

所以我可以通过这个子句来搜索这些数据:

{"query": {"filtered":{"filter":{"term":{"d1":"test"}}}}}

然而,由于字段 “d2” 存在一个特殊字符“*”,我困惑如何通过d2搜索这个数据。以下两种方法都是错误的。

{"query": {"filtered":{"filter":{"term":{"d2":"*"}}}}}

或者

{"query": {"filtered":{"filter":{"term":{"d2":"\*"}}}}}
1个回答

3

你的问题是你的索引中没有包含任何内容!

如果你没有设置特定的映射,那么使用的动态映射已经设置了一个类型为string的字段,默认情况下使用standard分析器进行< strong>分析。

如果你使用标准分析器来分析*的结果,你会发现没有任何标记作为结果:

GET _analyze?analyzer=standard&text=*

ElasticSearch 响应:

{
   "tokens": []
}

将您的映射更改为将d2字段索引为not_analyzed,则文档将与您的查询匹配。

示例:

POST /special/
{
  "mappings":{
    "character":{
      "properties":{
        "d2":{
          "type":"string",
          "index":"not_analyzed"
        }
      }
    }
  }
}

POST /special/character/
{
  "d2":"*"
}

POST /special/_search
{
  "query": {
    "term": {
      "d2": "*"
    }
  }
}

最终你将得到以下结果:

"hits": {
      "total": 1,
      "max_score": 0.30685282,
      "hits": [
         {
            "_index": "special",
            "_type": "character",
            "_id": "AU_gcWOBn6s1TzYZvmTv",
            "_score": 0.30685282,
            "_source": {
               "d2": "*"
            }
         }
      ]
   }

分析是ElasticSearch的一个非常重要的概念:花时间了解它,你就可以节省大量时间来理解正在发生的事情。

更一般地回答如何在这些特殊字符上进行查询,您必须控制您的分析不删除它们或查询一个不被分析的专用字段。


谢谢您的回答。它真的帮了我很多。 - Yarkee

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