Search code examples
elasticsearchelastic-stackelasticsearch-mapping

Define array of strings field in elastic search


How to define a field that accepts an array of strings like ["A", "B", "C"].

I have tried to do the following: crated a field in my index:

    {
      "properties": 
      {
        "date": {"type": "date"},
        "imageUrls": { "type": "nested" },
        }
    }

And I write the document

..../_doc/1

method: POST

body:

{
    "imageUrls": ["A", "B", "C"]
}

Always getting this error:

{
    "error": {
        "root_cause": [
            {
                "type": "mapper_parsing_exception",
                "reason": "object mapping for [imageUrls] tried to parse field [null] as object, but found a concrete value"
            }
        ],
        "type": "mapper_parsing_exception",
        "reason": "object mapping for [imageUrls] tried to parse field [null] as object, but found a concrete value"
    },
    "status": 400
}

Solution

  • Single values in a nested mapping are not allowed. From the docs -- the system

    allows arrays of objects to be indexed in a way that they can be queried independently of each other.

    That is to say,

    PUT ahm
    {
      "mappings": {
        "properties": {
          "date": {
            "type": "date"
          },
          "imageUrls": {
            "type": "nested",
            "properties": {
              "url": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword"
                  }
                }
              }
            }
          }
        }
      }
    }
    

    and then

    POST ahm/_doc
    {
      "imageUrls": [
        {
          "url": "A"
        },
        {
          "url": "B"
        },
        {
          "url": "C"
        }
      ]
    }
    

    This is quite nonsensical as-is but if more properties were added to the array objects, it would start to make sense.