这是我的问题。由于项目需要,我们必须以相同的格式将我们的日期保存在elasticsearch索引中。我们尝试过的是下一个方法 -
var connectionPool = new SniffingConnectionPool(nodeList);
var connectionSettings = new ConnectionSettings(connectionPool)
.SetJsonSerializerSettingsModifier(
m => m.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffffffK")
// other configuration goes here
但它没有成功。通过ES索引搜索,我看到日期的尾随零点丢失(如2015-05-05T18:55:27Z预期2015-05-05T18:55:27.0000000Z)。下一个选项也没有帮助:
var connectionPool = new SniffingConnectionPool(nodeList);
var connectionSettings = new ConnectionSettings(connectionPool)
.SetJsonSerializerSettingsModifier(m =>
{
m.Converters.Add(new IsoDateTimeConverter { DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"});
})
// other configuration goes here
在运行时挖掘ElasticClient时,我发现最终有一个合同解析器似乎覆盖了所有这些设置:
public class ElasticContractResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
JsonContract contract = base.CreateContract(objectType);
...
if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
contract.Converter = new IsoDateTimeConverter();
...
if (this.ConnectionSettings.ContractConverters.HasAny())
{
foreach (var c in this.ConnectionSettings.ContractConverters)
{
var converter = c(objectType);
if (converter == null)
continue;
contract.Converter = converter;
break;
}
}
return contract;
}
}
因此,如果我没有明确指定转换器(通过Connection Settings.AddContractJsonConverters()),我的json设置将会消失,因为 IsoDateTimeConverter 已实例化默认设置,而不是我通过 SetJsonSerializerSettingsModifier 传递的设置。
有没有人遇到过这个问题?或者我只是遗漏了什么?提前谢谢!
答案 0 :(得分:0)
这就是我根据需要处理自定义日期格式的方式:
public class Document
{
[ElasticProperty(DateFormat = "yyyy-MM-dd", Type = FieldType.Date)]
public string CreatedDate { get; set; }
}
client.Index(new Document {CreatedDate = DateTime.Now.ToString("yyyy-MM-dd")});
ES中的文档
{
"_index": "indexname",
"_type": "document",
"_id": "AU04kd4jnBKFIw7rP3gX",
"_score": 1,
"_source": {
"createdDate": "2015-05-09"
}
}
希望它会对你有所帮助。