Search code examples
elasticsearchnest

Elasticsearch / NEST 6 - storing enums as string


Is it possible to store enums as string in NEST6?

I've tried this but it does not seem to work. Any suggestions?

var pool = new SingleNodeConnectionPool(new Uri(context.ConnectionString));
connectionSettings = new ConnectionSettings(pool, connection, SourceSerializer());

    private static ConnectionSettings.SourceSerializerFactory SourceSerializer()
    {
        return (builtin, settings) => new JsonNetSerializer(builtin, settings,
            () => new JsonSerializerSettings
            {
                Converters = new List<JsonConverter>
                {
                    new StringEnumConverter()
                }
            });
    }

Solution

  • Use the StringEnumAttribute attribute on the property. This signals to the internal serializer to serialize the enum as a string. In using this, you don't need to use the NEST.JsonNetSerializer package

    If you'd like to set it for all enums, you can do so with

    private static void Main()
    {
        var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
        var connectionSettings = new ConnectionSettings(
            pool, 
            (builtin, settings) => new JsonNetSerializer(builtin, settings,
                contractJsonConverters: new JsonConverter[] { new StringEnumConverter() }));
    
        var client = new ElasticClient(connectionSettings);
    
        client.Index(new Product { Foo = Foo.Bar }, i => i.Index("examples"));
    }
    
    public class Product
    {
        public Foo Foo { get;set; }
    }
    
    public enum Foo
    {
        Bar
    }
    

    which yields a request like

    POST http://localhost:9200/examples/product
    {
      "foo": "Bar"
    }
    

    I think the way that you're attempting to set converters should also work and is a bug that it doesn't. I'll open an issue to address.