Python操作Elasticsearch例子

这篇博客介绍了如何使用Python库Elasticsearch连接、创建和删除索引,以及如何增删和查询数据。示例展示了添加、删除文档,通过ID或条件删除数据,并进行了简单的全文搜索和数据计数操作。

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

分布式搜索引擎Elasticsearch非常受欢迎,对应Python库为elasticsearch

from elasticsearch import Elasticsearch
# 连接引擎
es = Elasticsearch(hosts=['127.0.0.1:9200'],http_auth=('elastic','password'))
# 创建索引
es.indices.create(index='test-index', ignore=400)
# 删除索引
es.indices.delete(index='test-index', ignore=[400,404])

下段为对引擎进行增加和删除数据操作部分;

msg = {'author': 'user','text': 'this is a test msg'}
# 对索引添加数据,无需设置ID,会自动添加
res = es.index(index="test-index", document=msg)
# 对索引添加数据,需要设置ID,ID不能重复
res = es.create(index="test-index", id=1314, document=msg)

# 删除索引中对应ID数据
res = es.delete(index="test-index", id=1314)
# 删除索引中对应author为user的数据
query = {"query": {"match": {'author': 'user'}}}
res = es.delete_by_query(index="test-index", body=query)

 下段为使用引擎进行简单搜索的操作部分;

# 查询索引中对应author为user的数据
query = {"match": {'author': 'user'}}
res = es.search(index="test-index", query=query)
# 查询索引中所有数据
query = {"match_all":{}}
res = es.search(index="test-index", query=query)

# 查询索引的数据量
res = es.count(index="test-index")
# 查询索引中对应author为user的数据量
query = {"query": {"match": {'author': 'user'}}}
res = es.count(index="test-index", body=query)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值