elasticsearch的常规操作--增删改查和批量处理
from elasticsearch import Elasticsearch
# 连接到Elasticsearch
es = Elasticsearch("http://localhost:9200")
# 索引一个文档
doc_id = es.index(index="myindex", id=1, document={"name": "John", "age": 30})['result']
# 获取一个文档
doc = es.get(index="myindex", id=1)
# 更新一个文档
es.update(index="myindex", id=1, document={"doc": {"name": "Jane"}})
# 删除一个文档
es.delete(index="myindex", id=1)
# 批量索引文档
bulk_data = [
{
"_index": "myindex",
"_id": 2,
"_source": {"name": "Alice", "age": 25}
},
{
"_index": "myindex",
"_id": 3,
"_source": {"name": "Bob", "age": 35}
}
]
es.bulk(index="myindex", body=bulk_data)
# 批量获取文档
res = es.mget(index="myindex", id=[2, 3])
# 批量更新文档
bulk_update_data = [
{
"update": {
"_index": "myindex",
"_id": 2,
"doc": {"age": 27}
}
},
{
"update": {
"_index": "myindex",
"_id": 3,
"doc": {"age": 37}
}
}
]
es.bulk(index="myindex", body=bulk_update_data)
# 批量删除文档
bulk_delete_data = [
{
"delete": {
"_index": "myindex",
"_id": 2
}
},
{
"delete": {
"_index": "myindex",
"_id": 3
}
}
]
es.bulk(index="myindex", body=bulk_delete_data)
这段代码展示了如何使用Elasticsearch Python API进行基本的增删改查操作以及批量处理。注意,这里的代码仅用于演示目的,并假设Elasticsearch服务器运行在本地的9200端口。在实际应用中,你需要根据你的环境配置Elasticsearch连接。
评论已关闭