我正在尝试使用 Elasticsearch 的非常基本查询的结果在 pandas 中构建一个 DataFrame。我得到了我需要的数据,但它是以构建适当数据框的方式对结果进行切片的问题。我真的只关心获取每个结果的时间戳和路径。我尝试了几种不同的 es.search 模式。
代码:
from datetime import datetime
from elasticsearch import Elasticsearch
from pandas import DataFrame, Series
import pandas as pd
import matplotlib.pyplot as plt
es = Elasticsearch(host="192.168.121.252")
res = es.search(index="_all", doc_type='logs', body={"query": {"match_all": {}}}, size=2, fields=('path','@timestamp'))
这给出了 4 个数据块。 [u’hits’, u’_shards’, u’took’, u’timed_out’]。我的结果在命中之内。
res['hits']['hits']
Out[47]:
[{u'_id': u'a1XHMhdHQB2uV7oq6dUldg',
u'_index': u'logstash-2014.08.07',
u'_score': 1.0,
u'_type': u'logs',
u'fields': {u'@timestamp': u'2014-08-07T12:36:00.086Z',
u'path': u'app2.log'}},
{u'_id': u'TcBvro_1QMqF4ORC-XlAPQ',
u'_index': u'logstash-2014.08.07',
u'_score': 1.0,
u'_type': u'logs',
u'fields': {u'@timestamp': u'2014-08-07T12:36:00.200Z',
u'path': u'app1.log'}}]
我唯一关心的是获取时间戳和每次点击的路径。
res['hits']['hits'][0]['fields']
Out[48]:
{u'@timestamp': u'2014-08-07T12:36:00.086Z',
u'path': u'app1.log'}
我终其一生都无法弄清楚谁将结果放入熊猫的数据框中。因此,对于我返回的 2 个结果,我希望有一个类似的数据框。
timestamp path
0 2014-08-07T12:36:00.086Z app1.log
1 2014-08-07T12:36:00.200Z app2.log
原文由 Justin S 发布,翻译遵循 CC BY-SA 4.0 许可协议
有一个叫做
pd.DataFrame.from_dict
的好玩具,你可以在这样的情况下使用它:分四步展示:
1,将列表中的每个项目(即
dictionary
)读入DataFrame
2,我们可以将列表中的所有项目放入一个大的
DataFrame
concat
它们按行排列,因为我们将为每个项目执行步骤#1,我们可以使用map
去做。3、然后我们访问标记为
'fields'
的列4,我们可能希望将
DataFrame
旋转90度(转置)和reset_index
如果我们希望索引为默认值int