Extending NEST types

edit

Sometimes you might want to provide a custom implementation of a type perhaps to work around an issue or because you’re using a third-party plugin that extends the features of Elasticsearch, and NEST does not provide support out of the box.

public class MyPluginProperty : IProperty
{
    IDictionary<string, object> IProperty.LocalMetadata { get; set; }
    public string Type { get; set; } = "my_plugin_property";
    public PropertyName Name { get; set; }

    public MyPluginProperty(string name, string language)
    {
        this.Name = name;
        this.Language = language;
        this.Numeric = true;
    }

    [PropertyName("language")]
    public string Language { get; set; }

    [PropertyName("numeric")]
    public bool Numeric { get; set; }
}

PropertyNameAttribute can be used to mark properties that should be serialized. Without this attribute, NEST won’t pick up the property for serialization.

Now that we have our own IProperty implementation we can add it to our propertes mapping when creating an index

var createIndexResponse = _client.CreateIndex("myindex", c => c
    .Mappings(ms => ms
        .Map<Project>(m => m
            .Properties(props => props
                .Custom(new MyPluginProperty("fieldName", "dutch"))
            )
        )
    )
);

which will serialize to the following JSON request

{
  "mappings": {
    "doc": {
      "properties": {
        "fieldName": {
          "type": "my_plugin_property",
          "language": "dutch",
          "numeric": true
        }
      }
    }
  }
}

Whilst NEST can serialize our my_plugin_property, it does not know how to deserialize it; We plan to make this more pluggable in the future