我想从cloudant数据库中检索一组密钥。我尝试了几种方法。但是,与其他方法相比,custom_result执行闪电般快速。有人可以解释原因吗?
from cloudant import cloudant
import json
import time
from cloudant.result import Result,ResultByKey
with open('credentials.json') as f:
cred = json.load(f)
with cloudant(str(cred['credentials']['username']),str(cred['credentials']['password']),url=str(cred['credentials']['url'])) as client:
my_database = client['my_database']
#Using POST
payload = {"keys": ["012","345"]}
end_point = '{0}/{1}'.format(client.server_url, 'my_database/_all_docs')
params = {'include_docs': 'true'}
start = time.time()
response = client.r_session.post(end_point, data=json.dumps(payload), params=params)
end = time.time()
print end-start
#using custom_result
start = time.time()
result = my_database.custom_result(include_docs=True,keys=["012","345"])
end = time.time()
print end-start
#using all_doc
start = time.time()
result = my_database.all_docs(include_docs=True,keys=["012","345"])
end = time.time()
print end-start
#using iteration
keys=["012","345"]
start = time.time()
result=[]
result_collection = Result(my_database.all_docs, include_docs=True)
for i in range(len(keys)):
result.append(result_collection[ResultByKey(i)])
end = time.time()
print end-start
我的输出如下:
0.426064968109
4.10079956055e-05
0.409541845322
0.819295167923
有人能告诉我为什么custom_result的执行速度如此之快?
答案 0 :(得分:1)
函数database.custom_result()仅创建cloudant.result.Result实例,Cloudant不返回任何结果。您可以尝试以这种方式进行测试,end-start将是您从Cloudant获得响应的整个过程。
start = time.time()
with database.custom_result(include_docs=True) as result:
data = result[:]
end = time.time()
print end-start