python-2.7 - 带有标点符号的Elasticsearch查询数据会导致错误的查询结果

标签 python-2.7 elasticsearch

案例介绍

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

示例:

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

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

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

查询data2:“>>这是一本书”

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

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

代码:

我的 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')

问题:

我可以使用正则表达式来解决它但是有没有使用 elasticsearch 设置的解决方案?像过滤器或 API 等?

环境配置:

Ubuntu 12.04 桌面 64 位

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

客户:pyelasticsearch

编程语言:python

使用的API:bulk_index API、search API

最佳答案

您遇到的是 query string parsing . banana? 被解释为以 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"
            }
        }
    }
}
'

关于python-2.7 - 带有标点符号的Elasticsearch查询数据会导致错误的查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20544614/

相关文章:

python - 在函数内部使用全局变量

python - SSLv3 警告与 urllib2 的握手失败

python - 对 csv 读取分割一切感到困惑

Elasticsearch 7.x 断路器 - 数据过大 - 故障排除

elasticsearch - Elasticsearch通配符查询

python - 转换为 DMatrix 后 XGBoost 在训练和测试特征上的差异

python - 在 python 中创建 cd 式结构的奇怪问题

java - Apache Flink连接elasticsearch的问题

symfony - 将带有Filebeat的symfony日志文件传输到本地docker-环境中的graylog

elasticsearch - Logstash:将两个日志合并为一个输出文档