How to create a runtime field with an array

Hello,

I was wondering how I can create a runtime field based on a value inside of a field array.

For example I have this keyword field:

fruit.names : [kiwi, bananas, apple]

I want to create a new field based on couple of conditions,

if banana found in fruit.names , emit("Yellow")
if carrot  found in fruit.names, emit("Red")

Hi!

Try this:

DELETE test
POST test/_doc
{
  "fruits" : ["kiwi", "bananas", "apple"]
}
POST test/_doc
{
  "fruits" : ["kiwi", "bananas", "carrot"]
}
GET test/_search
{
  "fields": [
    "color"
  ], 
  "runtime_mappings": {
    "color": {
      "type": "keyword",
      "script": {
        "source": """
        if (doc['fruits.keyword'].contains("bananas")) emit("Yellow");
        if (doc['fruits.keyword'].contains("carrot")) emit("Red");
        """
      }
    }
  }
}

This gives:

{
  "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": "test",
        "_id": "GapMa5EBgHbtuK4M7gUY",
        "_score": 1,
        "_source": {
          "fruits": [
            "kiwi",
            "bananas",
            "apple"
          ]
        },
        "fields": {
          "color": [
            "Yellow"
          ]
        }
      },
      {
        "_index": "test",
        "_id": "GqpRa5EBgHbtuK4MEAXy",
        "_score": 1,
        "_source": {
          "fruits": [
            "kiwi",
            "bananas",
            "carrot"
          ]
        },
        "fields": {
          "color": [
            "Red",
            "Yellow"
          ]
        }
      }
    ]
  }
}

Does it help?

that works! thanks @dadoonet