How to read Different field names with same field value - Elasticsearch

Hi,

When indexing or searching to different indices, it's generally going to be easier to create separate POCO classes for each index. Those classes can model their properties to align closely with the fields in the index. Using the same model is challenging since the deserialiser has no way to know what to expect in the JSON.

If you only need to use your type for deserialisation, another option to consider is including two properties that align to both variations of field name. Then provide a computed property to access whichever has been set during deserialisation. Something like this:

public class Fields
{

    [Text(Name = "CorrelationId")]
    public string CorrelationId { get; set; }

    [Text(Name = "UniqueCorrelationId")]
    public string UniqueCorrelationId { get; set; }

    [Text(Name = "CorrelationId")]
    public string FinalCorrelationId => CorrelationId ?? UniqueCorrelationId;

}

Depending on your requirements, that may be sufficient.

Other options include registering a custom source serialisation and providing your own custom converters/formatters to handle the deserialisation. This is going to be more complex and harder to maintain.

The auto-mapping functionality is designed to provide a best guess for the mapping of C# properties to Elasticsearch fields, but it's generalised with common rules. If your requirements deviate from the generic case, you will need to handle those yourself, with attributes or fluent mapping syntax. In your example, you need the Text attribute to override the default name inferred for the property, since the default behaviour is to assume the name will be camel-cased in the JSON. You can read more about this and how to change that behaviour in our documentation.

Cheers,
Steve

1 Like