如何将pandas数据导出到elasticsearch?

时间:2018-04-09 05:38:46

标签: pandas elasticsearch

可以使用elasticsearch-py将pandas数据帧数据导出到elasticsearch。例如,以下是一些代码:

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

有很多类似的方法,例如to_excelto_csvto_sql

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

4 个答案:

答案 0 :(得分:8)

以下脚本适用于localhost:

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]'验证

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

答案 1 :(得分:2)

我不知道pandas中集成了任何to_elastic方法。您始终可以在pandas github repo上提出问题或创建拉取请求。

但是,有espandas允许将pandas DataFrame导入elasticsearch。来自README的以下示例已使用Elasticsearch 6.2.1进行了测试。

import pandas as pd
import numpy as np
from espandas import Espandas

df = (100 * pd.DataFrame(np.round(np.random.rand(100, 5), 2))).astype(int)
df.columns = ['A', 'B', 'C', 'D', 'E']
df['indexId'] = (df.index + 100).astype(str)

INDEX = 'foo_index'
TYPE = 'bar_type'
esp = Espandas()
esp.es_write(df, INDEX, TYPE)

使用GET foo_index/_mappings检索映射:

{
  "foo_index": {
    "mappings": {
      "bar_type": {
        "properties": {
          "A": {
            "type": "long"
          },
          "B": {
            "type": "long"
          },
          "C": {
            "type": "long"
          },
          "D": {
            "type": "long"
          },
          "E": {
            "type": "long"
          },
          "indexId": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
        }
      }
    }
  }
}

答案 2 :(得分:0)

你可以使用elasticsearch-py或者如果你不使用elasticsearch-py,你可以在这里找到你的问题的答案=> index-a-pandas-dataframe-into-elasticsearch-without-elasticsearch-py

答案 3 :(得分:0)

可以使用

pip install es_pandas
pip install progressbar2

此软件包应在Python3(> = 3.4)上运行,ElasticSearch的版本应为5.x,6.x或7.x。

import time
import pandas as pd
from es_pandas import es_pandas


# Information of es cluseter
es_host = 'localhost:9200'
index = 'demo'

# crete es_pandas instance
ep = es_pandas(es_host)

# Example data frame
df = pd.DataFrame({'Alpha': [chr(i) for i in range(97, 128)], 
                    'Num': [x for x in range(31)], 
                    'Date': pd.date_range(start='2019/01/01', end='2019/01/31')})

# init template if you want
doc_type = 'demo'
ep.init_es_tmpl(df, doc_type)

# Example of write data to es, use the template you create
ep.to_es(df, index, doc_type=doc_type)
# set use_index=True if you want to use DataFrame index as records' _id
ep.to_es(df, index, doc_type=doc_type, use_index=True)

这是文档https://pypi.org/project/es-pandas/
如果'es_pandas'无法解决您的问题,您可以查看其他解决方案:https://towardsdatascience.com/exporting-pandas-data-to-elasticsearch-724aa4dd8f62