python操作es的基本功能

本文介绍使用Python语言对Elasticsearch进行增删改查等基本操作的方法,包括创建、删除、更新文档及批量操作等内容,并提供具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值