当前位置: 首页 > news >正文

Python 操作 Elasticsearch

什么是 Elasticsearch

Elasticsearch 是一个基于 Lucene 的开源分布式搜索与分析引擎,能在海量数据中以毫秒级速度进行全文检索、结构化查询和实时数据分析,广泛用于站内搜索、日志分析和业务监控,数据以 JSON 文档形式存储,并支持水平扩展。


安装 Python Elasticsearch 客户端

安装最新的版本

# 安装最新的版本
pip install elasticsearch

安装指定的版本

# 安装指定的版本,假如要安装的版本是 8.14.0
pip install elasticsearch==8.14.0

对于 Elasticsearch 8.x,如果你启用了安全认证,需要加上 certifi

pip install certifi

连接 Elasticsearch 

连接无密码的 es

from elasticsearch import Elasticsearches = Elasticsearch("http://localhost:9200")if es.ping():print("Elasticsearch 连接成功")
else:raise ConnectionError("Elasticsearch 连接失败")

连接有密码的 es,有有效证书的

from elasticsearch import Elasticsearch# 如果需要用户名和密码
es = Elasticsearch(# es 地址"https://my-domain:9200",# 账号密码basic_auth=("账号", "密码"),# verify_certs=True: 告诉 Python 客户端, 请严格验证 SSL 证书链是否受信任。verify_certs=True
)if es.ping():print("Elasticsearch 连接成功")
else:raise ConnectionError("Elasticsearch 连接失败")

连接有密码的 es,无有效证书的

from elasticsearch import Elasticsearch# 如果需要用户名和密码
es = Elasticsearch(# es 地址"https://10.10.10.1:9200",# 账号密码basic_auth=("账号", "密码"),# verify_certs=False: 告诉 Python 客户端, 不检查 SSL 证书链是否受信任。verify_certs=False,# 不显示 证书无效 的警告ssl_show_warn=False
)if es.ping():print("Elasticsearch 连接成功")
else:raise ConnectionError("Elasticsearch 连接失败")

索引操作

创建索引

# 自定义索引名称
index_name = "products"mapping = {"mappings": {"properties": {"name": {"type": "text"},"price": {"type": "float"},"category": {"type": "keyword"},"created_at": {"type": "date"}}}
}# 创建索引
if not es.indices.exists(index=index_name):es.indices.create(index=index_name, body=mapping)print("索引创建成功")

查询所有索引

indices = es.indices.get_alias(name="*")
print(indices)

查询索引是否存在

# 索引存在 返回 True, 索引不存在 返回 False
print(es.indices.exists(index=index_name))

查询索引数据结构

mapping = es.indices.get_mapping(index=index_name)
print(mapping)

删除指定的索引

deleteResult = es.indices.delete(index="products")
print(deleteResult)     # 打印  {'acknowledged': True}

向索引中添加新字段

# 索引名称
index_name = "products"# 定义要添加的新字段 mapping
new_field = {"properties": {"age": {"type": "integer"}}
}# 更新 mapping
response = es.indices.put_mapping(index=index_name, body=new_field)
print(response)         # 打印 {'acknowledged': True}

同一集群 迁移单个索引

# 被迁移的索引
source_index = "old-index"
# 迁移到的目标索引
target_index = "new-index"# 1️ 创建新索引(可自定义结构)
new_mapping = {"mappings": {"properties": {"name": {"type": "text"},"age": {"type": "integer"}}}
}# 创建目标索引
es.indices.create(index=target_index, body=new_mapping)# 2️ 迁移数据
res = es.reindex(body={"source": {"index": source_index},"dest": {"index": target_index}
})

从一个集群到另一个集群 迁移单个索引

例如:有如下2个集群

源集群(old):http://192.168.1.10:9200

目标集群(new):http://192.168.1.20:9200

1. 在目标集群中注册源集群远程连接(白名单)

PUT _cluster/settings
{"persistent": {"reindex.remote.whitelist": ["192.168.1.10:9200"]}
}

2. 在目标集群执行 py 迁移代码

from elasticsearch import Elasticsearches = Elasticsearch(# 目标 es 地址"https://192.168.1.20:9200",# 账号密码basic_auth=("elastic", "123456"),# verify_certs=False: 告诉 Python 客户端, 不检查 SSL 证书链是否受信任。verify_certs=False,# 不显示 证书无效 的警告ssl_show_warn=False
)if es.ping():print("Elasticsearch 连接成功")
else:raise ConnectionError("Elasticsearch 连接失败")# 迁移
es.reindex(body={"source": {"remote": {"host": "http://192.168.1.10:9200","username": "elastic","password": "123456"},"index": "old-index"},"dest": {"index": "new-index"}
})

添加 Document 操作

添加一条 doc,索引不存在时创建

index_name = "products"doc = {"name": "Alice","age": 25
}# _id 自动生成的方式
res = es.index(index=index_name, document=doc)# 指定 _id 
# res = es.index(index=index_name, id="001", document=doc)print(res)      # 打印 {'_index': 'products', '_id': '7z7kYZoBTWmfHFoJzD9j', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 1, '_primary_term': 1}

ps. 如果想索引不存在 就不添加,使用 es.indices.exists(index=index_name) 进行判断

只在文档不存在时添加(幂等创建)

try:es.create(index="users", id="user_1001", document={"name": "Bob","age": 30})
except:print("文档已存在")

不存在则添加,存在则更新

es.update(index="users",id="user_1003",doc={"name": "David", "age": 27},doc_as_upsert=True
)

批量添加数据

from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk# 如果需要用户名和密码
es = Elasticsearch(# es 地址"https://10.10.10.1:9200",# 账号密码basic_auth=("账号", "密码"),# verify_certs=False: 告诉 Python 客户端, 不检查 SSL 证书链是否受信任。verify_certs=False,# 不显示 证书无效 的警告ssl_show_warn=False
)if es.ping():print("Elasticsearch 连接成功")
else:raise ConnectionError("Elasticsearch 连接失败")# 要添加的批量数据
actions = [{"_index": "users", "_id": 1, "_source": {"name": "Alice", "age": 25}},{"_index": "users", "_id": 2, "_source": {"name": "Bob", "age": 30}},{"_index": "users", "_id": 3, "_source": {"name": "Charlie", "age": 22}},
]# 批量添加
success, _ = bulk(es, actions)
print("成功写入文档数:", success)

查询 Document 操作

根据 _id 查询单条 doc

http://www.dtcms.com/a/585967.html

相关文章:

  • 微网站建设找哪家公司好中国网站备案取消
  • AI Agent设计模式 Day 3:Self-Ask模式:自我提问驱动的推理链
  • RAG论文阅读笔记
  • 网站建设优化推广修改wordpress数据库域名
  • 西安成品网站建设临沂最新消息
  • 影视网站搭建技术大纲
  • 多粒子模型-简单化学反应1
  • 基于Springboot的影视推荐系统的设计与实现371d749h(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
  • 网站设计与制作说明书应聘网站优化的简历怎么做
  • 网站项目云主机玩游戏怎么样
  • 什么是PMOS?什么是NMOS?两者有什么区别?
  • Selective Kernel Networks (SKNet)
  • Unreal5从入门到精通之 游戏技能系统(Gameplay Ability System)
  • 首钢水钢赛德建设有限公司网站广电如何做视频网站
  • 简洁网站欣赏制作自己的网站代码吗
  • 如何将图片进行压缩-图片压缩格式+压缩方法
  • 桂林临桂区建设局网站seo建站平台哪家好
  • tornado+gunicorn部署设置max_body_size
  • 大鹏网络网站建设报价asp 建站
  • SSM基于Java的医疗器械销售系统oy281(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
  • CTFHub Web进阶-PHP:Bypass_disable_function通关9之iconv,bypass iconv1,bypass iconv2
  • 排序算法介绍
  • 服装私人订制网站高端网站建设公司名字
  • CSP-S 练习题:美丽的集合(ST表、二分查找、数论基础-GCD 的应用)
  • 建设一个本地网站网站内容怎么编辑
  • 接口测试基础知识
  • 新网站建设的感想做网站虚拟主机配置
  • LeetCode 419 - 棋盘上的战舰
  • 【视觉】对比分析 GigE Vision、USB3Vision、UCV三种协议
  • 无锡网站制作8揭阳专业做网站公司