如何在PyES中使用ResultSet

时间:2013-03-05 11:05:23

标签: python elasticsearch resultset pyes

我正在使用PyES在Python中使用ElasticSearch。 通常,我使用以下格式构建查询:

# Create connection to server.
conn = ES('127.0.0.1:9200')

# Create a filter to select documents with 'stuff' in the title.
myFilter = TermFilter("title", "stuff")

# Create query.
q = FilteredQuery(MatchAllQuery(), myFilter).search()

# Execute the query.
results = conn.search(query=q, indices=['my-index'])

print type(results)
# > <class 'pyes.es.ResultSet'>

这完美无缺。当查询返回大量文档时,我的问题就开始了。 将结果转换为字典列表是计算上要求很高的,所以我试图在字典中返回查询结果。我偶然发现了这个文档:

http://pyes.readthedocs.org/en/latest/faq.html#id3 http://pyes.readthedocs.org/en/latest/references/pyes.es.html#pyes.es.ResultSet https://github.com/aparo/pyes/blob/master/pyes/es.py(第1304行)

但我无法弄清楚究竟应该做什么。 根据以前的链接,我试过这个:

from pyes import *
from pyes.query import *
from pyes.es import ResultSet
from pyes.connection import connect

# Create connection to server.
c = connect(servers=['127.0.0.1:9200'])

# Create a filter to select documents with 'stuff' in the title.
myFilter = TermFilter("title", "stuff")

# Create query / Search object.
q = FilteredQuery(MatchAllQuery(), myFilter).search()

# (How to) create the model ?
mymodel = lambda x, y: y

# Execute the query.
# class pyes.es.ResultSet(connection, search, indices=None, doc_types=None,
# query_params=None, auto_fix_keys=False, auto_clean_highlight=False, model=None)

resSet = ResultSet(connection=c, search=q, indices=['my-index'], model=mymodel)
# > resSet = ResultSet(connection=c, search=q, indices=['my-index'], model=mymodel)
# > TypeError: __init__() got an unexpected keyword argument 'search'

任何人都可以从ResultSet中获取dict? 任何有效的将ResultSet转换为(list of)字典的好消息也将受到赞赏。

2 个答案:

答案 0 :(得分:1)

我尝试了很多方法直接将ResultSet转换为dict但却什么也没得到。我最近使用的最好方法是将ResultSet项添加到另一个列表或dict中。 ResultSet将每个项目本身作为一个词典覆盖。

以下是我的使用方法:

#create a response dictionary
response = {"status_code": 200, "message": "Successful", "content": []}

#set restul set to content of response
response["content"] = [result for result in resultset]

#return a json object
return json.dumps(response)

答案 1 :(得分:0)

它并不复杂:只是迭代结果集。例如,使用for循环:

for item in results:
   print item