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']}")
标签:
python
, Elasticsearch
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具