我正在使用DSL进行Python中的Elasticsearch。我的目标是使用elasticsearch-dsl-py尽可能轻松地循环处理Elasticsearch响应数据。
import datetime
import json
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
e_search = Elasticsearch([{'host': 'my-alias', 'port': 5648}])
s = Search(using=e_search, index='sampleindex-2019.10') \
.filter('range' , **{'@timestamp': {'gte': 1571633450000, 'lt': 1571669450000, 'format' : 'epoch_millis'}})
执行此操作时,我得到以下值:
response = s.execute()
print(response.success())
>>> True
print(response.took)
>> 41
print(response.hits.total)
>> 6582
但是,当我尝试遍历所有结果时,似乎只能打印出10个匹配:
for h in response:
print(hit)
<Hit(sampleindex-2019.10/nQGt7G0BGh3E1MmaFw8e): {'startTime': '2019-10-21T13:57:05.621300916+09:00', 'header...'}>
<Hit(sampleindex-2019.10/egCp7G0BGh3E1Mmaq9bC): {'startTime': '2019-10-21T13:53:15.32923433+09:00', 'headers...'}>
<Hit(sampleindex-2019.10/hACo7G0BGh3E1MmaNsXk): {'headers': {'http_version': 'HTTP/1.1', 'http_user_agent': ...}>
<Hit(sampleindex-2019.10/VgCp7G0BGh3E1Mmae9Tv): {'headers': {'http_version': 'HTTP/1.1', 'http_user_agent': ...}>
<Hit(sampleindex-2019.10/nQGt7G0BGh3E1MmaFw8e): {'startTime': '2019-10-21T13:57:05.621300916+09:00', 'header...'}>
<Hit(sampleindex-2019.10/cwGv7G0BGh3E1Mma1Ddj): {'headers': {'http_version': 'HTTP/1.1', 'http_user_agent': ...}>
<Hit(sampleindex-2019.10/PgGv7G0BGh3E1MmaMzCA): {'startTime': '2019-10-21T13:59:11.83491578+09:00', 'headers...'}>
<Hit(sampleindex-2019.10/4wGw7G0BGh3E1MmaSjzb): {'headers': {'http_version': 'HTTP/1.1', 'http_user_agent': ...}>
<Hit(sampleindex-2019.10/cAGs7G0BGh3E1Mma_Q5Z): {'headers': {'http_version': 'HTTP/1.1', 'http_user_agent': ...}>
<Hit(sampleindex-2019.10/6AGw7G0BGh3E1Mma60OW): {'headers': {'http_version': 'HTTP/1.1', 'http_user_agent': ...}>
如果我想使用此输出数据并进行诸如循环结果并将信息存储在字典中之类的事情,如何使用elasticsearch-dsl-py
尽可能轻松地实现?
答案 0 :(得分:1)
我在GitHub docs(也在Read The Docs)中找到了此摘录:
要指定from / size参数,请使用Python切片API:
s = s[10:20]
如果您要访问查询匹配的所有文档,则可以使用使用扫描/滚动elasticsearch API的扫描方法:
for hit in s.scan():
print(hit.title)
请注意,在这种情况下,结果将不会排序。