# ElasticsearchException: runtime field [my_field] cannot be used in context [query] because it is defined as [script] type

- **ID:** `elasticsearch/runtime-field-context-error`
- **Domain:** elasticsearch
- **Category:** type_error
- **Error Code:** `RUNTIME_FIELD_CONTEXT_MISMATCH`
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

A runtime field with a `script` type is used in a context that expects a different type (e.g., `keyword` or `long`), causing a type mismatch.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Elasticsearch 7.16 | active | — | — |
| Elasticsearch 8.2 | active | — | — |
| Elasticsearch 8.11 | active | — | — |

## Workarounds

1. **Update the runtime field script to return the correct type: `PUT my_index/_mapping {"runtime": {"my_field": {"type": "keyword", "script": {"source": "emit(doc['source_field'].value.toString())"}}}}`** (85% success)
   ```
   Update the runtime field script to return the correct type: `PUT my_index/_mapping {"runtime": {"my_field": {"type": "keyword", "script": {"source": "emit(doc['source_field'].value.toString())"}}}}`
   ```
2. **Use a painless script transformation in the query instead of a runtime field: `GET my_index/_search {"query": {"script_score": {"script": {"source": "doc['source_field'].value.length()"}}}}`** (80% success)
   ```
   Use a painless script transformation in the query instead of a runtime field: `GET my_index/_search {"query": {"script_score": {"script": {"source": "doc['source_field'].value.length()"}}}}`
   ```

## Dead Ends

- **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% fail)
- **Removing the runtime field and using a concrete mapping instead** — This requires reindexing, which is disruptive and may not be feasible in production. (60% fail)
- **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% fail)
