如何在 ElasticSearch 中使 query_string 搜索精确短语 [英] How to make query_string search exact phrase in ElasticSearch

查看:37
本文介绍了如何在 ElasticSearch 中使 query_string 搜索精确短语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Elasticsearch 中放了 2 个文档:

I put 2 documents in Elasticsearch :

curl -XPUT "http://localhost:9200/vehicles/vehicle/1" -d'
{
    "model": "Classe A"
}'

curl -XPUT "http://localhost:9200/vehicles/vehicle/2" -d'
{
    "model": "Classe B"
}'

为什么这个查询返回 2 个文档:

Why is this query returns the 2 documents :

curl -XPOST "http://localhost:9200/vehicles/_search" -d'
{
  "query": {
    "query_string": {
      "query": "model:"Classe A""
    }
  }
}'

而这个,只有第二个文件:

And this one, only the second document :

curl -XPOST "http://localhost:9200/vehicles/_search" -d'
{
  "query": {
    "query_string": {
      "query": "model:"Classe B""
    }
  }
}'

我希望弹性搜索匹配我传递给查询参数的确切短语,带空格,我该怎么做?

I want elastic search to match on the exact phrase I pass to the query parameter, WITH the whitespace, how can I do that ?

推荐答案

你需要看的是analyzer 您正在使用.如果您没有指定 Elasticsearch 将使用 标准分析器.它适用于大多数纯文本输入的情况,但不适用于您提到的用例.

What you need to look at is the analyzer you're using. If you don't specify one Elasticsearch will use the Standard Analyzer. It is great for the majority of cases with plain text input, but doesn't work for the use case you mention.

标准分析器会做的是拆分字符串中的单词,然后将它们转换为小写.

What the standard analyzer will do is split the words in your string and then converts them to lowercase.

如果要匹配整个字符串Classe A"并将其与Classe B"区分开来,可以使用关键字分析器.这会将整个字段保留为一个字符串.

If you want to match the whole string "Classe A" and distinguish this from "Classe B", you can use the Keyword Analyzer. This will keep the entire field as one string.

然后您可以使用匹配查询,它将返回您期望的结果.

Then you can use the match query which will return the results you expect.

创建映射:

PUT vehicles
{
  "mappings": {
    "vehicle": {
      "properties": {
        "model": {
          "type": "string",
          "analyzer": "keyword"
        }
      }
    }
  }
}

执行查询:

POST vehicles/_search
{
  "query": {
    "match": {
      "model": "Classe A"
    }
  }
}

如果您想使用 query_string 查询,那么您可以将运算符设置为 AND

If you wanted to use the query_string query, then you could set the operator to AND

POST vehicles/vehicle/_search
{
  "query": {
    "query_string": {
      "query": "Classe B",
      "default_operator": "AND"
    }
  }
}

这篇关于如何在 ElasticSearch 中使 query_string 搜索精确短语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆