前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Python往Elasticsear

使用Python往Elasticsear

作者头像
py3study
发布2020-01-08 10:50:58
4460
发布2020-01-08 10:50:58
举报
文章被收录于专栏:python3python3

使用Python往Elasticsearch插入数据


在这里,我使用Elasticsearch官方推荐elasticsearch第三方包来讲述插入数据的两种方法。

1. index 这是很简单的一个插入数据的方法,每条数据调用一个index方法,代码如下

from datetime import datetime
from elasticsearch import Elasticsearch

es = Elasticsearch( "localhost:9200" ) 
data = {
    "@timestamp" : datetime.now().strftime( "%Y-%m-%dT%H:%M:%S.000+0800" ),
    "http_code" : "404",
    "count" : "10"
}

es.index( index="http_code", doc_type="error_code", body=data )

2. bulk 一次性插入多条数据的方法

from datetime import datetime
from elasticsearch import Elasticsearch
import elasticsearch.helpers
import random

es = Elasticsearch( "localhost:9200" ) 
package = []
for i in range( 10 ):
    row = {
        "@timestamp":datetime.now().strftime( "%Y-%m-%dT%H:%M:%S.000+0800" ),
        "http_code" : "404",
        "count" : random.randint(  1, 100 )
    }
    package.append( row )

actions = [
    {
        '_op_type': 'index',
        '_index': "http_code",  //index
        '_type': "error_code",  //type
        '_source': d
    }
    for d in package
]    

elasticsearch.helpers.bulk( es, action )
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 使用Python往Elasticsearch插入数据
相关产品与服务
Elasticsearch Service
腾讯云 Elasticsearch Service(ES)是云端全托管海量数据检索分析服务,拥有高性能自研内核,集成X-Pack。ES 支持通过自治索引、存算分离、集群巡检等特性轻松管理集群,也支持免运维、自动弹性、按需使用的 Serverless 模式。使用 ES 您可以高效构建信息检索、日志分析、运维监控等服务,它独特的向量检索还可助您构建基于语义、图像的AI深度应用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档