【问题标题】:Unexpected result of Elastic term query弹性术语查询的意外结果
【发布时间】:2016-10-05 15:01:02
【问题描述】:

我在 http://localhost:9200 上运行 Elastic 2.4 仅用于测试。

设置

作为新的开始,我在索引中创建了 1 个且仅 1 个项目。

$ curl -s -XPUT "http://localhost:9200/movies/movie/1" -d'
{
    "title": "The Godfather",
    "director": "Francis Ford Coppola",
    "year": 1972,
    "genres": ["Crime", "Drama"]
}'

返回

{"_index":"movies","_type":"movie","_id":"1","_version":3,"_shards":{"total":2,"successful":1,"failed":0},"created":false}

然后我运行这个命令来确认索引工作:

$ curl -s -XPOST "http://localhost:9200/movies/_search" -d'
{
    "query": {
        "query_string": {
            "query": "Godfather"
        }
    }
}'

返回

{"took":8,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":1,"max_score":0.095891505,"hits":[{"_index":"movies","_type":"movie","_id":"1","_score":0.095891505,"_source":
{
    "title": "The Godfather",
    "director": "Francis Ford Coppola",
    "year": 1972,
    "genres": ["Crime", "Drama"]
}}]}}

问题

我尝试像这样运行术语查询:

$ curl -s -XPOST "http://localhost:9200/movies/_search" -d'
{
    "query": {
        "term": {"title": "The Godfather"}
    }
}'

我应该得到 1 个结果,但我得到了这个:

{"took":1,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}

我做错了什么?

【问题讨论】:

  • title 字段已分析,因此请尝试使用 match 查询而不是 term ;-)
  • 谢谢。我想找到title 与"The Godfather" 完全匹配的项目,所以match 似乎不符合我的需要。无论如何我可以使用给定的数据进行术语查询吗?

标签: elasticsearch


【解决方案1】:

match_phrase 像 jay 建议的那样,或者您需要创建一个 not_analyzed 子字段(例如 title.raw),如下所示:

$ curl -s -XPUT "http://localhost:9200/movies/_mapping/movie" -d'
{
    "properties": {
        "title": {
            "type": "string",
            "fields": {
               "raw": {
                   "type": "string",
                   "index": "not_analyzed"
               }
            }
        }
    }
}'

然后您可以重新索引您的文档以填充title.raw:

$ curl -s -XPUT "http://localhost:9200/movies/movie/1" -d'
{
    "title": "The Godfather",
    "director": "Francis Ford Coppola",
    "year": 1972,
    "genres": ["Crime", "Drama"]
}'

最后,您的术语查询将适用于 title.raw 子字段:

$ curl -s -XPOST "http://localhost:9200/movies/_search" -d'
{
    "query": {
        "term": {"title.raw": "The Godfather"}
    }
}'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多