简介
Elasticsearch 是一款基于 Apache Lucene 构建的强大分布式搜索引擎,专为全文搜索、日志记录、监控以及海量数据分析而设计。要在 Python 中集成 Elasticsearch,官方提供了 elasticsearch-py 客户端,它通过 Python 代码为你提供访问所有 Elasticsearch API 的完整能力。
借助 elasticsearch-py 库,开发者可以在 Python 应用中直接实现高级搜索、数据聚合以及海量数据处理,无论是构建 Web 服务、分析工具还是监控系统,都能轻松胜任。
elasticsearch-py 库介绍
Elasticsearch-py 是 Elasticsearch 的官方 Python 客户端。该库通过 RESTful API 提供对 Elasticsearch 所有功能的底层访问,同时为 Python 开发者提供了便捷的接口。
核心特性:
- 官方支持:由 Elastic 团队开发和维护
- 全面兼容:支持所有版本的 Elasticsearch
- 自动节点发现:可自动检测并连接集群节点
- 连接池:高效管理集群连接
- 错误处理:内置完善的异常处理机制
- 序列化:自动将 Python 对象转换为 JSON 格式
安装与集群连接
安装
pip install elasticsearch
如需使用 SSL 证书:
pip install elasticsearch[async]
连接本地集群
from elasticsearch import Elasticsearch
es = Elasticsearch("http://localhost:9200")
连接远程集群(需认证)
es = Elasticsearch(
"https://your-cluster:9200",
basic_auth=("user", "password"),
verify_certs=True
)
使用 API 密钥连接
es = Elasticsearch(
"https://your-cluster:9200",
api_key="your_api_key",
verify_certs=True
)
连接多个节点
es = Elasticsearch(
[
"https://node1:9200",
"https://node2:9200",
"https://node3:9200"
],
basic_auth=("user", "password")
)
Elasticsearch 核心概念
- 索引:类似于关系型数据库中的表,用于存储结构相似的文档
- 文档:存储在索引中的 JSON 对象,相当于表中的一条记录
- 字段:文档的属性,相当于表中的列
- 映射:定义文档结构及字段类型的描述
- 分片:索引数据的物理存储单元
- 副本:分片的备份,用于保证高可用性
索引管理
创建索引与映射
mapping = {
"mappings": {
"properties": {
"title": {"type": "text", "analyzer": "standard"},
"tags": {"type": "keyword"},
"published": {"type": "date"},
"content": {"type": "text"},
"author": {"type": "keyword"},
"views": {"type": "integer"}
}
},
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
}
}
es.indices.create(index="articles", body=mapping)
删除索引
es.indices.delete(index="articles")