索引(Index)
本章定位:Index 是 Elasticsearch 的最高层容器概念。理解 Index 的创建、设置和生命周期是使用 ES 的第一步。
定义与作用
Index(索引)是文档的集合,具有特定的 Settings 和 Mappings。每个 Index 被切割为 N 个主分片(Primary Shard),每个主分片可以有 M 个副本(Replica)。
解决的痛点:将海量数据分布在多个分片上,实现并行处理和水平扩展。
完整示例:创建与管理索引
# 创建索引
PUT /courses
{
"settings": {
"number_of_shards": 5,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"title": { "type": "text", "analyzer": "ik_max_word" },
"category": { "type": "keyword" },
"price": { "type": "float" }
}
}
}
# 查看索引
GET /courses
# 删除索引
DELETE /courses
# 关闭/打开索引(释放内存)
POST /courses/_close
POST /courses/_open
小结
Index 创建时核心决策:分片数(不可修改)和副本数(可动态调整)。number_of_shards 过少限制扩展,过多浪费资源。通用公式:分片数 ≈ 数据节点数 × 1~3。