pandas dataframe 写入到es中

1.pandas中的dataframe

1.工作原因,需要从hive读取数据到pandas中进行操作,然后处理完全以后需要再读取到es中。

读取hive数据:因为脚本在生产上,所以,导入的包如果有缺失,可以自己补一下。

import pandas as pd
from pyhive import hive
import json
import time
from elasticsearch import Elasticsearch

2.读取Hive数据库

conn=hive.connect(host='',port='',username='',database='')
sql='select * from table1'
start_time=time.time()
tb=pd.read_sql(sql=sql,con=conn)
end_time=time.time()
# 显示的是加载数据的时间
print(t)

2.调用es的包,并写入到ES中

在es中并不需要提前去新增索引,可以按照自己的喜好命名。
我参照的是他的代码@'Humz:我觉得还可以,只是有些需要优化下。



def connect_es(frame, index_, type_):

    try:
        es = Elasticsearch(host, http_auth=(user, password), port='9200')
        # 把df转化成json
        df_as_json = frame.to_json(orient='records', lines=True)
        bulk_data = []
        # ID最好是需求但是一定要唯一,可以是两个str拼接起来的
        for json_document in df_as_json.split('\n'):
            json_document1=json_document.loads(json_document)
            id1=json_document1['id']+json_document1['versionn']
            bulk_data.append({"index": {
                '_index': index_,
                '_type': type_,
                '_id':id1
            }})
            bulk_data.append(json.loads(json_document))
            
            # 一次bulk request包含1000条数据
            if len(bulk_data) > 1000:
                es.bulk(bulk_data)
                bulk_data = []
                
        es.bulk(bulk_data)
        print('database connet successfully')

    except Exception as e:
    
        print(e)
connect_es(tb,index_name,'docs')

3.写到最后

由于我对es并不是很熟,我一开始想着先读取一个es到df中看下es的构成是那些的,算是一些启发吧。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值