@rickyChen
2016-11-08T09:53:14.000000Z
字数 866
阅读 7460
Python Elasticsearch
在这里,我使用Elasticsearch官方推荐
elasticsearch第三方包来讲述插入数据的两种方法。
1. index
这是很简单的一个插入数据的方法,每条数据调用一个index方法,代码如下
from datetime import datetimefrom elasticsearch import Elasticsearches = 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 datetimefrom elasticsearch import Elasticsearchimport elasticsearch.helpersimport randomes = 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 )
