Python Elasticsearch 创建数据索引和实现搜索
安装依赖库elasticsearch
pip install elasticsearch
代码实现
from elasticsearch import Elasticsearch
# =============初始化ES数据库对象===============
# 连接 Elasticsearch
es = Elasticsearch("http://localhost:9200")
# 检查集群健康状态
health = es.cluster.health()
print("集群健康状态:", health)
# ==============创建数据索引======================
# 定义索引名称和映射
index_name = "articles"
mapping = {
"mappings": {
"properties": {
"title": {
"type": "text",
"analyzer": "standard"
}
}
}
}
# 创建索引
if not es.indices.exists(index=index_name):
es.indices.create(index=index_name, body=mapping)
print(f"索引 {index_name} 创建成功")
else:
print(f"索引 {index_name} 已存在")
# 插入文档
documents = [
{"title": "Introduction to Elasticsearch"},
{"title": "Advanced Elasticsearch Techniques"},
{"title": "Elasticsearch for Beginners"}
]
for i, doc in enumerate(documents):
es.index(index=index_name, id=i + 1, document=doc)
print(f"文档 {i + 1} 插入成功")
# ================数据模糊搜索=================
# 搜索文档
query = {
"query": {
"match": {
"title": "Elasticsearch"
}
}
}
response = es.search(index=index_name, body=query)
# 输出搜索结果
print("搜索结果:")
for hit in response["hits"]["hits"]:
print(f"ID: {hit['_id']}, 标题: {hit['_source']['title']}")

浙公网安备 33010602011771号