首页 > 解决方案 > 在同一搜索中使用关键字和文本字段进行查询字符串查询

问题描述

从 Elasticsearch 5.x 升级到 6.x。我们广泛使用查询字符串查询,并且通常构造使用不同类型字段的查询。

在 5.x 中,以下查询工作正常且没有错误:

{
  "query": {
    "query_string": {
      "query": "my_keyword_field:\"Exact Phrase Here\" my_text_field:(any words) my_other_text_field:\"Another phrase here\" date_field:[2018-01-01 TO 2018-05-01]",
      "default_operator": "AND",
      "analyzer": "custom_text"
    }
  }
}

在 6.x 中,此查询将返回以下错误:

{
  "type": "illegal_state_exception",
  "reason": "field:[my_keyword_field] was indexed without position data; cannot run PhraseQuery"
}

如果我将短语用括号而不是引号括起来,搜索将返回 0 个结果:

{
  "query": {
    "query_string": {
      "query": "my_keyword_field:(Exact Phrase Here)",
      "default_operator": "AND",
      "analyzer": "custom_text"
    }
  }
}

我猜这是因为分析器阻止传入查询的方式与数据在关键字字段中的存储方式之间存在冲突,但短语方法(my_keyword_field:"Exact Phrase Here")在 5.x 中确实有效。

这在 6.x 中不再支持吗?如果没有,迁移路径和/或好的解决方法是什么?

标签: elasticsearch

解决方案


最好使用可用于不同用例的不同类型的查询来重新表述查询。例如,使用术语查询对关键字字段进行精确搜索。对范围等使用范围查询。

您可以将查询改写如下:

{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "my_text_field:(any words) my_other_text_field:\"Another phrase here\"",
            "default_operator": "AND",
            "analyzer": "custom_text"
          }
        },
        {
          "term": {
            "my_keyword_field": "Exact Phrase Here"
          }
        },
        {
          "range": {
            "date_field": {
              "gte": "2018-01-01",
              "lte": "2018-05-01"
            }
          }
        }
      ]
    }
  }
}

推荐阅读