pandas - 如何将pandas数据导出到elasticsearch?

标签 pandas elasticsearch

可以使用 elasticsearch-py 将 pandas dataframe 数据导出到 elasticsearch。例如,这里有一些代码:

https://www.analyticsvidhya.com/blog/2017/05/beginners-guide-to-data-exploration-using-elastic-search-and-kibana/

to_excelto_csvto_sql等类似方法还有很多。

是否有to_elastic方法?如果没有,我应该在哪里申请?

最佳答案

以下脚本适用于本地主机:

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

INDEX="dataframe"
TYPE= "record"

def rec_to_actions(df):
    import json
    for record in df.to_dict(orient="records"):
        yield ('{ "index" : { "_index" : "%s", "_type" : "%s" }}'% (INDEX, TYPE))
        yield (json.dumps(record, default=int))

from elasticsearch import Elasticsearch
e = Elasticsearch() # no args, connect to localhost:9200
if not e.indices.exists(INDEX):
    raise RuntimeError('index does not exists, use `curl -X PUT "localhost:9200/%s"` and try again'%INDEX)

r = e.bulk(rec_to_actions(df)) # return a dict

print(not r["errors"])

使用 curl -g 'http://localhost:9200/dataframe/_search?q=A:[29%20TO%2039]' 验证

可以添加许多小东西以满足不同的需求,但主要的还是有。

关于pandas - 如何将pandas数据导出到elasticsearch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49726229/

相关文章:

python - 使用 group by 函数进行字符串模式聚合

python - 从逐笔报价数据到烛台

python - 如何在单元测试中使用 assert_frame_equal

elasticsearch - Elasticsearch :一旦获得所需结果,如何终止多重搜索查询

mongodb - 查询数据以在AWS中实现最小延迟的最佳方法

python - 根据特定日期条件在Python中选择日期列

Python将数据保存到PostgreSQL : array value error

elasticsearch - 用于提取URI一部分的grok模式

json - Elasticsearch没有JSON查询的结果

node.js - 如何通过AWS lambda nodejs函数索引存储在S3中的XML文件?