索引创建
- 版本化索引命名:采用类似
product_index_v1
、product_index_v2
这样的命名规则,清晰标识索引版本。
- 索引模板:定义索引模板来确保不同版本索引具有一致的映射和设置,如字段类型、分析器等。例如:
{
"template": "product_index_*",
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"product_name": { "type": "text" },
"price": { "type": "float" },
"description": { "type": "text" }
}
}
}
- 创建新索引:当有商品上新、促销等情况需要更新索引时,根据索引模板创建新的版本化索引。可以通过 Elasticsearch API 进行创建:
PUT product_index_v2
{
"settings": {
"index": {
"number_of_shards": 3,
"number_of_replicas": 1
}
},
"mappings": {
"properties": {
"product_name": { "type": "text" },
"price": { "type": "float" },
"description": { "type": "text" }
}
}
}
别名管理
- 创建别名:为索引创建别名,例如
product_search_alias
,初始时指向第一个版本的索引 product_index_v1
。
POST /_aliases
{
"actions": [
{
"add": {
"index": "product_index_v1",
"alias": "product_search_alias"
}
}
]
}
- 切换别名:当新的索引准备好后,通过原子操作将别名切换到新索引。这可以保证用户搜索请求在索引切换时的无缝衔接。
POST /_aliases
{
"actions": [
{
"remove": {
"index": "product_index_v1",
"alias": "product_search_alias"
}
},
{
"add": {
"index": "product_index_v2",
"alias": "product_search_alias"
}
}
]
}
- 别名的只读属性:在切换索引过程中,可以先将旧索引设置为只读,防止写入操作干扰切换过程。
PUT product_index_v1/_settings
{
"index.blocks.write": true
}
故障恢复
- 副本机制:通过设置多个副本(如上述索引模板中设置
number_of_replicas: 1
),当主分片出现故障时,副本分片可以自动提升为主分片,保证数据的可用性。
- 监控与自动恢复:利用 Elasticsearch 的监控工具(如 Elasticsearch Monitoring)实时监控索引的健康状态。如果发现某个索引或分片出现故障,可以通过自动化脚本(如使用 Elasticsearch API 结合编程语言)重新创建索引并恢复别名指向。例如:
from elasticsearch import Elasticsearch
es = Elasticsearch()
if es.cluster.health()['status'] == 'red':
# 重新创建索引
es.indices.create(index='product_index_recovered', body=index_template)
# 恢复别名
es.indices.update_aliases(body={
"actions": [
{
"add": {
"index": "product_index_recovered",
"alias": "product_search_alias"
}
}
]
})
监控与调优
- 监控指标:
- 索引健康状态:使用
/_cluster/health
API 查看索引的整体健康状况,green
表示一切正常,yellow
表示部分副本未分配,red
表示有主分片故障。
- 搜索性能:监控搜索请求的响应时间、吞吐量等指标。可以通过 Elasticsearch Monitoring 或自定义日志记录。
- 资源使用:监控节点的 CPU、内存、磁盘 I/O 等资源使用情况,确保 Elasticsearch 运行在合理的资源范围内。
- 调优策略:
- 索引设置调优:根据数据量和查询模式调整分片数量和副本数量。如果数据量不断增长,可以适当增加分片;如果对可用性要求极高,可以增加副本数量。
- 查询优化:分析慢查询,通过优化查询语句、调整索引映射等方式提高查询性能。例如,对经常用于过滤的字段设置为
keyword
类型,避免全文分析。
- 硬件优化:根据资源使用监控结果,合理调整服务器硬件配置,如增加内存、更换更快的磁盘等。