如何强制 Elasticsearch "terms" 查询为 not_analyzed

How to force Elasticsearch "terms" query to be not_analyzed

我想在文档字段中精确匹配 ID。我已经将字段映射为索引 not_analyzed 但在查询中似乎每个术语都是 tokenizde 或至少是小写的。我如何使查询也 not_analyzed?使用 ES 1.4.4、1.5.1 和 2.0.0

这是一个文档:

 {
    "_index": "index_1446662629384",
    "_type": "docs",
    "_id": "Cat-129700",
    "_score": 1,
    "_source": {
       "similarids": [
          "Cat-129695",
          "Cat-129699",
          "Cat-129696"
       ],
       "id": "Cat-129700"
    }
 }

这是一个查询:

{
    "size": 10,
    "query": {
        "bool": {
            "should": [{
                "terms": {
                    "similarids": ["Cat-129695","Cat-129699","Cat-129696"]
                }
            }]
        }
    }
}

上面的查询不起作用。如果我从文档 ID 中删除大写字母和破折号,它就可以工作。由于很多原因,我不能那样做。有没有办法让 similarids not_analyzed 像文档字段一样?

如果我的理解正确,您只需在映射中的 "similarids" 上设置 "index":"not_analyzed"。如果您已经正确设置了该设置,那么从您发布的内容来看,还有其他事情不明显("terms" query 不会对您的搜索词进行任何分析)。您可能需要检查您的映射以确保它按照您的想法设置。

为了测试它,我设置了一个简单的索引,如下所示:

PUT /test_index
{
   "settings": {
      "number_of_shards": 1
   },
   "mappings": {
      "doc": {
         "properties": {
            "id": {
               "type": "string",
               "index": "not_analyzed"
            },
            "similarids": {
               "type": "string",
               "index": "not_analyzed"
            }
         }
      }
   }
}

然后添加了您的文档:

PUT /test_index/doc/1
{
   "similarids": [
      "Cat-129695",
      "Cat-129699",
      "Cat-129696"
   ],
   "id": "Cat-129700"
}

而且您的查询工作正常。

POST /test_index/_search
{
   "size": 10,
   "query": {
      "bool": {
         "should": [
            {
               "terms": {
                  "similarids": [
                     "Cat-129695",
                     "Cat-129699",
                     "Cat-129696"
                  ]
               }
            }
         ]
      }
   }
}
...
{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 1,
      "successful": 1,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 0.53148466,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "1",
            "_score": 0.53148466,
            "_source": {
               "similarids": [
                  "Cat-129695",
                  "Cat-129699",
                  "Cat-129696"
               ],
               "id": "Cat-129700"
            }
         }
      ]
   }
}

我这里用的是ES 2.0,不过你用哪个版本应该没关系。这是我用来测试的代码:

http://sense.qbox.io/gist/562ccda28dfaed2717b43739696b88ea861ad690