面试题答案
一键面试自定义ElasticSearch自动创建索引机制
- 配置文件:在Elasticsearch的配置文件
elasticsearch.yml
中,没有直接针对自定义自动创建索引机制的特定配置项。但可以设置cluster.routing.allocation.disk.threshold_enabled
等通用配置来影响索引的分配等,间接与自动创建索引相关。比如,为防止磁盘满导致创建索引失败,合理设置磁盘阈值:
cluster.routing.allocation.disk.threshold_enabled: true
cluster.routing.allocation.disk.watermark.low: 85%
cluster.routing.allocation.disk.watermark.high: 90%
cluster.routing.allocation.disk.watermark.flood_stage: 95%
- API调用:
- Index Template API:
- 定义索引模板,通过PUT请求到
/_template/<template_name>
。例如,假设要对以user_
前缀开头的索引使用特定类型映射规则:
- 定义索引模板,通过PUT请求到
- Index Template API:
PUT /_template/user_template
{
"index_patterns": ["user_*"],
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"user_id": {
"type": "keyword"
},
"user_name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
}
}
}
}
}
这里index_patterns
指定了匹配的索引前缀,settings
定义了索引的分片和副本数,mappings
定义了字段的类型映射规则。
- Ingest Node Pipeline API:如果需要对数据进行预处理,例如对特定前缀字段进行格式化等操作,可以使用Ingest Node Pipeline。首先创建一个管道,通过PUT请求到
/_ingest/pipeline/<pipeline_name>
:
PUT /_ingest/pipeline/user_preprocess
{
"description": "Pre - process user - related data",
"processors": [
{
"set": {
"field": "user_id",
"value": "{{ctx.user_id | lower}}"
}
}
]
}
然后在创建索引或索引文档时,可以指定这个管道。例如创建索引时:
PUT user_test
{
"settings": {
"index": {
"ingest.pipeline": "user_preprocess"
}
}
}
- 性能优化点:
- 模板复杂度:避免在索引模板中定义过于复杂的映射。复杂的映射(如过多的嵌套对象、大量的自定义字段数据类型等)会增加索引创建和文档索引的时间。尽量保持映射简洁,仅包含业务必需的字段和设置。
- 分片和副本设置:在索引模板中合理设置分片和副本数。分片数过多会导致资源浪费和性能下降,过少则可能影响索引的并行处理能力。例如,对于读多写少的场景,可以适当增加副本数,但要注意副本同步带来的网络开销。一般来说,先通过测试确定合适的分片和副本数量,对于小型数据集,3 - 5个分片可能就足够,而对于大型数据集,可能需要根据数据量和节点数进行调整。
- Ingest Pipeline性能:如果使用Ingest Pipeline,要注意处理器的数量和复杂度。每个处理器都会增加数据处理的时间,尽量减少不必要的处理器,并优化处理器逻辑。例如,避免在处理器中进行复杂的循环或大量的字符串操作等昂贵的操作。
- 缓存使用:Elasticsearch会缓存一些索引相关的元数据等信息。确保缓存配置合理,例如合理设置
indices.query.cache.size
等缓存参数,以提高索引创建和查询的性能。但要注意,缓存设置过大会占用过多内存,影响其他Elasticsearch功能的运行。