适用版本: 6.8-8.9
1. 错误异常的基本描述 #
当请求体里的 collapse 内部对象结构不合法时,解析阶段会抛出:
Invalid token in the inner collapse
这类错误通常不是搜索执行失败,而是 DSL 在解析阶段就被拒绝了。
2. 为什么会发生这个错误 #
collapse 的内部结构只能包含 Elasticsearch 认可的字段和对象层级。如果传入了错误的 token,例如:
- 在对象里写了数组
- 在应为对象的位置写了字符串
- 拼错了字段名
- 传入了不支持的嵌套结构
解析器会把它标记为 isParsedCorrectly == false,随后抛出 ParsingException。
3. 如何排查和解决这个异常 #
- 检查请求中的
collapse部分是否为合法 JSON 对象。 - 核对是否误把
inner_hits、field、max_concurrent_group_searches等字段写错层级。 - 如果请求由模板拼装生成,输出最终 JSON,确认不是模板条件分支把结构拼坏了。
例如下面就是容易出错的写法:
"collapse": {
"field": "user_id",
"inner_hits": "latest"
}
其中 inner_hits 若需要复杂结构,应写成对象而不是随意 token。
4. 如何解决这个错误 #
方案一:按官方 DSL 结构重写 collapse #
最稳妥的做法是从一个最小可用示例出发,再逐步补字段。
方案二:校验模板输出 #
如果使用搜索模板、代码拼接或网关改写 DSL,要记录最终发往 Elasticsearch 的完整请求体。
方案三:拆小定位 #
先保留:
"collapse": {
"field": "user_id"
}
确认可用后,再逐项恢复 inner_hits 等扩展配置。
5. 预防建议 #
- 不要手写过于复杂的 JSON 字符串拼接,优先使用结构化对象构建 DSL。
- 对
collapse这类嵌套对象做单元测试,至少验证生成结果是合法 JSON 且字段层级正确。 - 在日志里保留最终请求体,避免只看到异常信息却不知道真实提交内容。
6. 小结 #
Invalid token in the inner collapse 的核心含义是:collapse 内部 JSON 结构不符合解析器预期。修复关键是回到请求体本身,检查对象层级和字段类型,而不是从索引或集群状态上兜圈子。
相关错误 #
- unknown-type-for-collapse-field-how-to-solve-this-elasticsearch-exception
- no-mapping-found-for-field-in-order-to-collapse-on-how-to-solve-this-elasticsearch-exception
- cannot-expand-inner-hits-for-collapse-field-how-to-solve-this-elasticsearch-exception
附:日志上下文 #
}
}
}
}
if (isParsedCorrectly == false) {
throw new ParsingException(parser.getTokenLocation(); "Invalid token in the inner collapse");
} }; COLLAPSE_FIELD; ObjectParser.ValueType.OBJECT);
}
private String name;





