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']}")
posted @   二月雪  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示