为什么这个错误发生 #
invalid_index_name_exception 表示使用的索引名称不符合 Easysearch 的命名规则或包含非法字符。
这个错误可能由以下原因引起:
- 非法字符:索引名包含不允许的字符
- 以特殊字符开头:索引名以
-、_或+开头 - 大写字母:索引名包含大写字母(必须全小写)
- 空名称:索引名为空
- 名称过长:索引名超过 255 字节
- 包含空格:索引名包含空格字符
- 特殊保留字符:包含
#、\、/、*、?、"、<、>、|等特殊字符 - 以点开头:索引名以
.开头(除.和..外)
如何修复这个错误 #
1. 遵循命名规则 #
# 有效的索引名称示例
my-index
logs-2023
app_data
test123
# 无效的索引名称示例
MyIndex # 包含大写字母
my-index # 以 - 开头
my index # 包含空格
my@index # 包含特殊字符
2. 转换为小写 #
# 将索引名转换为小写
PUT /<my-lowercase-index-name>
{
"settings": {
"number_of_shards": 3
}
}
3. 移除特殊字符 #
# 使用下划线或连字符替代特殊字符
# 不要用:my@index
# 使用:my_index 或 my-index
PUT /my_index
4. 避免以特殊字符开头 #
# 不要以 -、_ 或 + 开头
# 错误:-myindex、_myindex、+myindex
# 正确:myindex、my-index
5. 处理日期格式的索引名 #
# 使用正确的日期格式
PUT /logs-2023-01-01
PUT /app-%7Bnow%7Bd%7D # URL 编码的 {now/d}
# 或使用索引模板
PUT /_index_template/logs-template
{
"index_patterns": ["logs-*"],
"template": {
"settings": {
"number_of_shards": 1
}
}
}
6. 检查索引名长度 #
# 索引名不应超过 255 字节
# 限制索引名的长度,特别是使用日期前缀时
PUT /very-long-prefix-name-that-exceeds-limit-avoid-this
# 改为:
PUT /vlp-2023-01-01
7. 使用别名 #
# 创建有意义的索引名,然后用别名提供简化访问
PUT /app-prod-2023-01-01
POST /_aliases
{
"actions": [
{
"add": {
"index": "app-prod-2023-01-01",
"alias": "app-current"
}
}
]
}
8. URL 编码特殊请求 #
# 如果必须在 API 中使用特殊字符,进行 URL 编码
# 但仍建议使用符合规范的索引名
curl -X PUT "localhost:9200/my%5Findex"
9. 使用索引模板自动化命名 #
# 使用组件模板和索引模板统一命名规范
PUT /_component_template/logs-settings
{
"template": {
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
}
}
}
PUT /_index_template/logs-template
{
"index_patterns": ["logs-*"],
"composed_of": ["logs-settings"]
}
10. 验证索引名 #
# 在创建前验证索引名是否符合规则
# 基本规则:
# - 只能包含小写字母、数字、-、_
# - 不能以 -、_、+ 开头
# - 不能是 . 或 ..
# - 不能包含 #、\、/、*、?、"、<、>、|、空格
# - 长度不超过 255 字节
预防措施 #
- 制定统一的索引命名规范
- 使用索引模板确保新索引符合命名规则
- 使用日期后缀组织时间序列数据
- 在代码中添加索引名验证逻辑
- 使用有意义的索引名前缀区分不同应用
- 避免在索引名中使用用户输入(未经验证)
- 使用别名简化复杂索引名的访问
- 在开发环境测试索引名创建





