# ElasticsearchException: 运行时字段[my_field]不能在上下文中使用[query]，因为它定义为[script]类型

- **ID:** `elasticsearch/runtime-field-context-error`
- **领域:** elasticsearch
- **类别:** type_error
- **错误码:** `RUNTIME_FIELD_CONTEXT_MISMATCH`
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

运行时字段的`script`类型被用于期望其他类型（如`keyword`或`long`）的上下文，导致类型不匹配。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Elasticsearch 7.16 | active | — | — |
| Elasticsearch 8.2 | active | — | — |
| Elasticsearch 8.11 | active | — | — |

## 解决方案

1. ```
   更新运行时字段脚本以返回正确类型：`PUT my_index/_mapping {"runtime": {"my_field": {"type": "keyword", "script": {"source": "emit(doc['source_field'].value.toString())"}}}}`
   ```
2. ```
   在查询中使用Painless脚本转换代替运行时字段：`GET my_index/_search {"query": {"script_score": {"script": {"source": "doc['source_field'].value.length()"}}}}`
   ```

## 无效尝试

- **Changing the runtime field type to `keyword` without adjusting the script logic** — The script may output incompatible values (e.g., numbers) for a keyword field, leading to further errors. (75% 失败率)
- **Removing the runtime field and using a concrete mapping instead** — This requires reindexing, which is disruptive and may not be feasible in production. (60% 失败率)
- **Setting `ignore_malformed: true` on the index to bypass type errors** — This only applies to concrete fields, not runtime fields, and will not resolve the context mismatch. (90% 失败率)
