使用Python操作ElasticSearch
安装依赖
pip install elasticsearch
安装完成后我们即可使用 from elasticsearch import Elasticsearch 进行连接与操作。
连接 ElasticSearch
from elasticsearch import Elasticsearch
创建客户端(以本地 ES 实例为例)
es = Elasticsearch("http://localhost:9200")
# es = Elasticsearch(hosts=[settings.ES_HOST], http_auth=(settings.ES_ACCOUNT, settings.ES_PASSWORD))
# 测试连接
if es.ping():
print("连接成功!")
else:
print("连接失败")
注意:ElasticSearch 8.x 开始默认开启安全认证,需要提供 basic_auth,否则连接会失败。
创建索引(含映射)
index_name = "books"
# 自定义索引结构(mapping)
mapping = {
"mappings": {
"properties": {
"title": {"type": "text"},
"author": {"type": "keyword"},
"published_year": {"type": "integer"}
}
}
}
# 创建索引
if not es.indices.exists(index=index_name):
es.indices.create(index=index_name, body=mapping)
print(f"索引 {index_name} 创建成功!")
添加数据
doc = {
"title": "我是书名",
"author": "作者",
"published_year": 2028
}
# 添加文档(不指定 ID)
res = es.index(index="books", document=doc)
print("文档 ID:", res["_id"])
查询数据
# 查询所有图书
query = {
"query": {
"match_all": {}
}
}
res = es.search(index="books", body=query)
for hit in res["hits"]["hits"]:
print(hit["_source"])
更新数据
doc_id = "数据ID"
update_body = {
"doc": {
"published_year": 2024
}
}
es.update(index="books", id=doc_id, body=update_body)
删除指定数据与索引
# 删除指定数据
es.delete(index="books", id=doc_id)
# 删除整个索引
es.indices.delete(index="books")

浙公网安备 33010602011771号