https://elasticsearch-py.readthedocs.io/en/master/
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 )
转载请注明:爱开源 » 使用Python往Elasticsearch插入数据