Elasticsearch简称ES,适合商品搜索、日志分析和大规模数据检索。Python可以通过elasticsearch客户端完成索引和文档操作。
注意:以下案例统一使用测试索引demo_products。不要直接替换为生产索引执行删除操作。生产环境的ES地址、账号和密码应该通过环境变量读取,不要直接写在代码中。
第一节:连接ES
from elasticsearch import Elasticsearch
es = Elasticsearch(
"http://127.0.0.1:9200",
request_timeout=30,
)
print(es.info())
生产环境应启用HTTPS和证书校验,避免使用verify_certs=False跳过证书检查。
第二节:索引增删改查
索引类似关系数据库中的表。创建索引时可以配置主分片、副本及字段类型。
index_name = "demo_products"
# 增:创建索引
if not es.indices.exists(index=index_name):
es.indices.create(
index=index_name,
settings={
"number_of_shards": 1,
"number_of_replicas": 0,
},
mappings={
"properties": {
"name": {"type": "keyword"},
"price": {"type": "double"},
}
},
)
# 查:读取Mapping
mapping = es.indices.get_mapping(index=index_name)
print(mapping)
# 改:增加字段
es.indices.put_mapping(
index=index_name,
properties={
"stock": {"type": "integer"},
},
)
# 改:调整动态设置
es.indices.put_settings(
index=index_name,
settings={
"index": {
"refresh_interval": "5s",
}
},
)
# 删:删除测试索引
# 注意:该操作会删除索引及全部数据,生产环境必须谨慎执行。
# es.indices.delete(index=index_name)
ES不能直接修改已经存在字段的数据类型。字段类型设计错误时,通常需要创建新索引,再通过reindex或重新导入数据完成迁移。
第三节:文档增删改查
# 增:写入文档
es.index(
index=index_name,
id="A001",
document={
"name": "Keyboard",
"price": 99.0,
"stock": 20,
},
refresh="wait_for",
)
# 查:根据ID读取
document = es.get(
index=index_name,
id="A001",
)
print(document["_source"])
# 查:根据条件搜索
result = es.search(
index=index_name,
query={
"term": {
"name": "Keyboard",
}
},
size=10,
)
print(result["hits"]["hits"])
# 改:局部更新
es.update(
index=index_name,
id="A001",
doc={
"price": 89.0,
},
refresh="wait_for",
)
# 删:删除文档
es.delete(
index=index_name,
id="A001",
refresh="wait_for",
)
正式业务建议设置稳定的文档_id。发生网络超时后,使用同一个_id重新写入只会覆盖原文档,可以降低重复数据风险。如果使用ES自动生成_id,超时重试可能产生重复文档。