pyhton 操作Elasticsearch

来源:互联网 发布:wifi mac地址查询 编辑:程序博客网 时间:2024/06/08 11:46

1、python连接elasticsearch

#coding=utf-8from elasticsearch import Elasticsearch as ESes=ES('192.168.1.38',port=9200)

2、创建索引

初始化索引 (mapping 相当于mysql的建表语句)

# coding=utf-8from  elasticsearch import Elasticsearchimport sys# 解决编码问题reload(sys)sys.setdefaultencoding("utf8")es = Elasticsearch('192.168.1.38', port=9200)# 初始化索引mapping设置(ES6.0中每个_index只能有一个_type)my_index_map = {    "mappings": {        "as_org": {            "properties": {                "asnumber": {"type": "integer"},                "asname": {"type": "text", },                "orgname": {"type": "text"},                "type": {"type": "text"},                "country": {"type": "text"}            }        }    }}# 如果索引不存在,则创建索引,索引名称不能有大写,应为全部小写if es.indices.exists(index="awtools") is not True:    es.indices.create(index="awtools", body=my_index_map)

3、批量插入数据

批量写入数据用的是es中的bulk。目前bulk批量插入数据一次最多只能有500条。

 #res_ip_as为数据库中的fetchall()的值 actions=[] i = 1 for each in res_ip_as:     action = {         "_index": "awtools",         "_type": "as_org",         "_id": i,         "_source": {             "minip": each[1],             "maxip": each[2],             "asnumber_as": each[3],         }     }     i += 1     actions.append(action)     if len(actions) == 500:         helpers.bulk(es, actions)         del actions[0:len(actions)] if len(actions) > 0:     helpers.bulk(es, actions)

4、单条插入数据

es.index(index='awtools',doc_type='as_org',body=action)