Cannot add runtime field to an existing index

I am trying to add a runtime field following the example from "Map a runtime field" in the documentation.

PUT my-index-000001/
{
  "mappings": {
    "runtime": {
      "day_of_week": {
        "type": "keyword",
        "script": {
          "source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ENGLISH))"
        }
      }
    },
    "properties": {
      "@timestamp": {"type": "date"}
    }
  }
}

The index my-index-000001 already exists. This command fails with a resource_already_exists_exception error. I expect it to succeed and add a day_of_week field to the index.

Why is this happening? The dynamic property is not set anywhere in my-index-000001, and I thought that dynamic field mapping was turned on by default.

I think you need to use the _mapping endpoint?

Here's my test, version 8.17.2

DELETE an-index-000001

PUT an-index-000001

PUT an-index-000001/_doc/0
{
  "field1" : "value0",
  "@timestamp" : "2025-03-06T23:10:20+00:00"
}

PUT an-index-000001/_mapping
{
  "runtime": {
    "day_of_week": {
      "type": "keyword",
      "script": {
        "source": "emit(doc['@timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ENGLISH))"
      }
    }
  },
  "properties": {
    "@timestamp": {
      "type": "date"
    }
  }
}

PUT an-index-000001/_doc/1
{
  "field1" : "value1",
  "@timestamp" : "2025-03-07T23:10:25+00:00"
}

GET an-index-000001/_search
{
  "fields": [ "field1" , "@timestamp" , "day_of_week"]
}

The search returns

{
  "took": 1,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 2,
      "relation": "eq"
    },
    "max_score": 1,
    "hits": [
      {
        "_index": "an-index-000001",
        "_id": "0",
        "_score": 1,
        "_source": {
          "field1": "value0",
          "@timestamp": "2025-03-06T23:10:20+00:00"
        },
        "fields": {
          "field1": [
            "value0"
          ],
          "@timestamp": [
            "2025-03-06T23:10:20.000Z"
          ],
          "day_of_week": [
            "Thursday"
          ]
        }
      },
      {
        "_index": "an-index-000001",
        "_id": "1",
        "_score": 1,
        "_source": {
          "field1": "value1",
          "@timestamp": "2025-03-07T23:10:25+00:00"
        },
        "fields": {
          "field1": [
            "value1"
          ],
          "@timestamp": [
            "2025-03-07T23:10:25.000Z"
          ],
          "day_of_week": [
            "Friday"
          ]
        }
      }
    ]
  }
}
1 Like