python语言操作elasticsearch增删改查的相关功能,在日常开发中常用到。
#!/usr/bin/env python # coding=utf-8 """ @author: shenzh @file: es_operate.py @desc: python操作es数据库相关操作(增、删、改、查) """ from elasticsearch import Elasticsearch import es_config as conf ''' 插入 create:必须指定待查询的idnex、type、id和查询体body;缺一不可,否则报错 index:相比于create,index的用法就相对灵活很多;id并非是一个必选项,如果指定,则该文档的id就是指定值, 若不指定,则系统会自动生成一个全局唯一的id赋给该文档。 ''' def create_and_add(es, indexName, doc_type, body, id=None): es.index(index=indexName, doc_type=doc_type, body=body, id=id) ''' 删除 delete:删除指定index、type、id的文档 ''' def delete(es, indexName, doc_type, id): es.delete(index=indexName, doc_type=doc_type, id=id) ''' 查找 get:获取指定index、type、id所对应的文档 ''' def query(es, indexName, doc_type, id): es.get(index=indexName, doc_type=doc_type, id=id) ''' ''' ''' 更新 update:跟新指定index、type、id所对应的文档 ''' def update(es, indexName, doc_type, id, body): es.update(index=indexName, doc_type=doc_type, id=id, body=body) ''' 批量插入、删除、更新 bulk:这个方法可以同时执行多个操作,单只请求一次,从而在批量操作的时候,可以很大程度上减少程序系统开销。 此外,bulk不仅可以一次性批量执行插入、或者删除操作,还可以在一次请求中,既可以插入、又可以删除和更新操作。 ''' def es_bulk(es, indexName, doc_type, body): es.bulk(index=indexName, doc_type=doc_type, body=body) ''' 条件查询 search:查询满足条件的所有文档,没有id属性,且index,type和body均可为None。 ''' def query_search(es, indexName, doc_type, query_type=None, key=None, value=None): if query_type == 'term': query = {'query': {'term': {key: value}}} # else: query = {'query': {'match_all': {}}} # allDoc = es.search(index=indexName, doc_type=doc_type, body=query) return allDoc['hits']['hits'] if __name__ == '__main__': body = {"name": 'lucy', 'sex': 'male', 'age': 10,'edcation':'doctor'} print(conf.es_port) print(type(conf.es_port)) es = Elasticsearch(conf.es_ip, port=conf.es_port) create_and_add(es,indexName='ott', doc_type='ott_type', body=body, id=None) # delete(es, indexName='ott', doc_type='ott_type', id='BNQnWHsBhcsul8GhPug-') # res = query_search(es, indexName='ott', doc_type='ott_type') # res = query_search(es,indexName='ott', doc_type='ott_type',query_type='term', key='sex', value='female') # print(res)