2013-03-05 31 views
1

我使用PyES在Python中使用ElasticSearch。 通常情況下,我建我的查詢的格式如下:如何在PyES中使用ResultSet

# 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轉換爲(列表)字典的好消息也將被讚賞。

+0

你不應該試圖把它轉換成一個字典或類似的。 這將做兩次相同的事情。我所做的是覆蓋ES對象,它不使用DottedDict訪問。但另一種可能性是使用「原始查詢」。 – 2014-01-21 23:52:43

回答

0

它並不那麼複雜:只是迭代結果集。例如,使用for循環:

for item in results: 
    print item 
+0

這正是我想要避免的。處理大型結果集時,這個問題變得非常緩慢。 – JCJS 2013-08-23 11:34:44

1

我嘗試了太多方法直接將ResultSet轉換爲字典,但什麼都沒有。我最近使用的最佳方式是將ResultSet項目附加到另一個列表或字典中。 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)