Mani
Mani

Reputation: 783

NEST: How to handle array fields which contains a single value (Newtonsoft Json Serialization error)

During the evaluation of ElasticSearch in combination with NEST I faced a new problem. The problem is regarding to fields which are array types plus the fact that array types are automatically supported in ES. I have a field ProductIds which can contain 1 or n values. The mapping is defined as following:

[…]
    "ProductIds" : {
        "type" : " integer",
        "store" : "yes"
    },
[…]

If the field contains a couple of Ids the query result in ES looks like this:

ProductIds: [
    1,
    2
]

The fact that array types are automatically, the field looks like this if it contains only a single value:

    ProductIds: 1

This circumstances leads to the following problem: I do have a Nest-query which is mapped to an certain class. In this class the attribute ProductIds is defined as a List<int> (I also tried it with an integer array). This works perfectly fine as long as there is more than a single value. If the field contains only a single value in ES it’s saved as a primitive data type. This leads to an error in Newtonsoft.JSON:

Connection error. at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)

at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)

at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)

So any suggestions how to solve this problem? TIA

Upvotes: 3

Views: 3051

Answers (1)

Martijn Laarman
Martijn Laarman

Reputation: 13536

You are not the first to run into this a solution has been provided here: https://github.com/Mpdreamz/NEST/issues/227#issuecomment-16550076

Support for this out of the box in NEST is planned too.

Upvotes: 4

Related Questions