【问题标题】:Elasticsearch query data with punctuation will leads a wrong query result带有标点符号的 Elasticsearch 查询数据会导致错误的查询结果
【发布时间】:2019-11-10 17:58:05
【问题描述】:

案例介绍

我的案例是在弹性搜索索引中存储一些单词,每个单词都有它的 ID。 我的查询数据是一些消息。当查询数据报文中有标点符号时,Elasticsearch 会返回错误的答案。

示例:

例如,我在索引中存储了关键字“banana,apple,pen”。我使用 bulk_index API 存储它

查询data1:“这是香蕉吗?”

正确的结果应该是命中关键字“banana”,但现在它什么也没命中。

查询数据2:“>>这是一本书”

结果应该没有命中,但现在它命中了索引中的所有关键字。

没有标点符号查询结果将正常工作。

代码:

我的storeToIndex代码:(python,pyelasticsearch作为客户端)

es=ElasticSearch('http://localhost:9200/')
rval = es.bulk_index('%s'%index_name,'json',doc, id_field="id")

我的 queryIndex() 代码

query={"query":{"query_string":{"query":"%s"%query_data}}}
 es=ElasticSearch('http://localhost:9200/')
 search_result=es.search(query=query,index=index_name,doc_type='json')

问题:

我可以使用正则表达式来解决它但是有没有使用弹性搜索设置的解决方案?过滤器或 API 之类的东西?

环境配置:

Ubuntu 12.04 桌面 64 位

Ubuntu 中的 Elasticsearch 服务器,版本 0.90.7,单节点

客户端:pyelasticsearch

编程语言:python

使用的API:bulk_index API、搜索API

【问题讨论】:

  • 欢迎来到 Stack Overflow!看起来您希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的编码人员编写代码,但他们通常只有在发布者已经尝试自己解决问题时才会提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(控制台输出、堆栈跟踪、编译器错误 - 不管是什么适用的)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • 我有一个关于如何使用python解决问题的想法但就我而言,我必须在elasticsearch中解决它。关于我可以使用哪个 API 或过滤器或其他东西的任何想法?我现在使用的API是批量索引API,搜索API。

标签: python-2.7 elasticsearch


【解决方案1】:

您遇到的是query string parsingbanana? 被解释为以 banana 开头并以单个未指定字符结尾的术语。例如,这将匹配 banana1>> .... 正在创建一个开放式范围查询,这就是它匹配索引中所有内容的原因。

我建议您考虑使用不同的查询类型,例如专为此类情况设计的 match query

看看this play 有四个查询(请参阅左下方面板中的搜索选项卡),为方便起见,此处导出为 Curl 命令:

#!/bin/bash

export ELASTICSEARCH_ENDPOINT="http://localhost:9200"

# Create indexes

curl -XPUT "$ELASTICSEARCH_ENDPOINT/play" -d '{
    "settings": {}
}'


# Index documents
curl -XPOST "$ELASTICSEARCH_ENDPOINT/_bulk?refresh=true" -d '
{"index":{"_index":"play","_type":"type"}}
{"somefield":"banana"}
{"index":{"_index":"play","_type":"type"}}
{"somefield":"apple"}
{"index":{"_index":"play","_type":"type"}}
{"somefield":"pen"}
'

# Do searches

curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
{
    "query": {
        "query_string": {
            "query": "is this banana?"
        }
    }
}
'

curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
{
    "query": {
        "match": {
            "somefield": {
                "query": "is this banana?"
            }
        }
    }
}
'

curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
{
    "query": {
        "query_string": {
            "query": ">> it is a book"
        }
    }
}
'

curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d '
{
    "query": {
        "match": {
            "somefield": {
                "query": ">> it is a book"
            }
        }
    }
}
'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2022-10-14
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多