Elasticsearch / NEST 6 - storing enums as string

三世轮回 提交于 2019-12-11 04:05:42

问题


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()
                }
            });
    }

回答1:


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.



来源:https://stackoverflow.com/questions/49224866/elasticsearch-nest-6-storing-enums-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!