5

How do I define a field in elasticsearch to always return an array.

I have a field KEYWORDS in elasticsearch that sometimes have one keyword

Elasticsearch then returns that field as a string rather than a list, this breaks the deserializer as it is expecting a list rather than a string.

This is how I defined keyword mapping:

"KEYWORDS": {
  "type": "text",
  "fields": {
    "keyword": {
      "type": "text"

    }
  }
},

2 Answers 2

9

What you are trying to achieve should be handled while indexing a document. Since there is no such specific data type for array. So for e.g. if you want to have a field that store/return array of integers all you need is to define the field as type integer and while indexing always make sure that value against that field is an array even if the value is single.

So,

PUT test
{
  "mappings": {
    "_doc": {
      "properties": {
        "intArray": {
          "type": "integer"
        }
      }
    }
  }
}

PUT test/_doc/1
{
   "intArray": [10, 12, 50]
}

PUT test/_doc/1
{
   "intArray": [7]
}

Same goes for any other data type as well.

Sign up to request clarification or add additional context in comments.

Comments

1

In Elasticsearch, there is no dedicated array type. By default any field could contain 0 or more values.

This makes impossible to force Elasticsearch to return always JSON array. E.g. if your document will have just 1 value, it will be returned as pair - field: value

I’m afraid you should have this conversion/enforcement on the client side

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.