Elasticsearch / NEST 6 - 将枚举存储为字符串
Elasticsearch / NEST 6 - storing enums as string
是否可以在 NEST6 中将枚举存储为字符串?
我已经试过了,但似乎不起作用。有什么建议吗?
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()
}
});
}
使用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
如果您想为所有枚举设置它,您可以使用
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
}
生成类似
的请求
POST http://localhost:9200/examples/product
{
"foo": "Bar"
}
我认为您尝试设置转换器的方式也应该有效,并且是一个错误,但它没有。我将打开一个问题来解决。
是否可以在 NEST6 中将枚举存储为字符串?
我已经试过了,但似乎不起作用。有什么建议吗?
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()
}
});
}
使用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
如果您想为所有枚举设置它,您可以使用
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
}
生成类似
的请求POST http://localhost:9200/examples/product
{
"foo": "Bar"
}
我认为您尝试设置转换器的方式也应该有效,并且是一个错误,但它没有。我将打开一个问题来解决。