一、引言:为什么选择Python+Elasticsearch?
Elasticsearch作为分布式搜索引擎,在日志分析、全文检索等场景中表现卓越。Python凭借其简洁语法和丰富生态,成为操作ES的首选语言。本文将带您从环境搭建到性能调优,系统掌握Python操作ES的核心技能。
二、环境准备:三步完成基础配置
-
安装依赖
pip install elasticsearch[async] # 包含同步/异步客户端
-
连接ES集群
- 基础连接:
from elasticsearch import Elasticsearch es = Elasticsearch(["http://localhost:9200"])
- 安全连接(Elasticsearch 8.x+):
es = Elasticsearch( ["https://es-server:9200"], basic_auth=("user", "pass"), ca_certs="/path/to/ca.crt" )
- 基础连接:
-
验证连接
print(es.info()) # 返回集群信息则成功
三、核心操作:CRUD与高级查询
1. 索引管理
-
创建索引(含映射):
mapping = { "mappings": { "properties":