使用 Python 请求查询 ElasticSearch 无法正常工作 [英] Querying ElasticSearch with Python Requests not working fine
问题描述
我正在尝试使用 Elastic Search 引擎在 mongodb 数据库上进行全文搜索,但我遇到了一个问题:无论我提供什么搜索词(或者如果我使用 query1 或 query2),引擎总是返回相同的结果.我认为问题在于我提出请求的方式,但我不知道如何解决.
I'm trying to do full-text search on a mongodb db with the Elastic Search engine but I ran into a problem: no matters what search term I provide(or if I use query1 or query2), the engine always returns the same results. I think the problem is in the way I make the requests, but I don't know how to solve it.
代码如下:
def search(search_term):
query1 = {
"fuzzy" : {
"art_text" : {
"value" : search_term,
"boost" : 1.0,
"min_similarity" : 0.5,
"prefix_length" : 0
}
},
"filter": {
"range" : {
"published": {
"from" : "20130409T000000",
"to": "20130410T235959"
}
}
}
}
query2 = {
"match_phrase": { "art_text": search_term }
}
es_query = json.dumps(query1)
uri = 'http://localhost:9200/newsidx/_search'
r = requests.get(uri, params=es_query)
results = json.loads( r.text )
data = [res['_source']['api_id'] for res in results['hits']['hits'] ]
print "results: %d" % len(data)
pprint(data)
推荐答案
params
参数不适用于正在发送的数据.如果您尝试将数据发送到服务器,您应该特别使用 data 参数.如果您尝试发送查询参数,则不应对它们进行 JSON 编码,而应将其作为 dict 提供给 params.
The params
parameter is not for data being sent. If you're trying to send data to the server you should specifically be using the data parameter. If you're trying to send query parameters, then you shouldn't be JSON-encoding them and just give it to params as a dict.
我怀疑您的第一个请求应该是以下内容:
I suspect your first request should be the following:
r = requests.get(uri, data=es_query)
在有人反对我之前,是的,HTTP/1.1 规范允许使用 GET 请求发送数据,是的请求确实支持它.
And before someone downvotes me, yes the HTTP/1.1 spec allows data to be sent with GET requests and yes requests does support it.
这篇关于使用 Python 请求查询 ElasticSearch 无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!