elasticsearch.net 和 Nest 中的日期格式问题 (C#)
本文关键字:问题 格式 日期 net Nest elasticsearch | 更新日期: 2023-09-27 18:37:19
我有以下C#模型:
[ElasticType(Name = "myType")]
public class MyType
{
...
[ElasticProperty(Name = "ElasticId")]
[DataMember(Name = "ElasticId")]
public string ElasticId { get; set; }
...
[ElasticProperty(Name = "DateToBeUsed", Type = FieldType.Date, DateFormat = "date_hour_minute_second_millis")]
public string DateToBeUsed { get; set; }
...
}
"date_hour_minute_second_millis"对应于以下格式:yyyy-MM-dd'T'HH:mm:ss。SSS(http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping-date-format.html)
映射 ES 是使用 "map" 方法使用 Nest 完成的,并对应于:
"mappings": {
"myType": {
"properties": {
...,
"ElasticId": {
"type": "string"
},
...,
"DateToBeUsed": {
"type": "date",
"format": "date_hour_minute_second_millis"
},
...
}
}
}
我在此索引中插入一个文档:
"_source": {
...,
"ElasticId": "2",
...,
"DateToBeUsed": "2012-05-21T09:51:34.073",
...
}
我的问题是当我想通过 Nest 检索此对象时。
DateToBeUsed 的值始终使用以下格式进行格式化:MM/dd/yyyy HH:mm:ss(例如 : 05/21/2012 09:51:34)
(使用感知,该值的格式正确。
1°)这正常吗?
我需要检索与我提供给 ES 的日期格式相同的日期格式。(我认为使用与映射中描述的相同格式应该是正常的)
2°)是否有"干净"的解决方案来解决此问题?(检索文档后重新格式化日期不是一个"干净"的解决方案......
感谢您的回答!再见。
我尝试使用以下代码重现您所看到的内容,但日期值按预期在Get
调用中返回:
string indexName = "so-27927069";
// --- create index ---
client.CreateIndex(cid => cid.Index(indexName));
Console.WriteLine("created index");
// --- define map ---
client.Map<MyType>(m => m
.Index(indexName)
.Type("myType")
.MapFromAttributes());
Console.WriteLine("set mapping");
// ---- index -----
client.Index<MyType>(
new MyType
{
DateToBeUsed = new DateTime(2012, 5, 21, 9, 51, 34, 73)
.ToString("yyyy-MM-ddThh:mm:ss.fff"),
ElasticId = "2"
},
i => i
.Index(indexName)
.Type("myType")
.Id(2)
);
Console.WriteLine("doc indexed");
// ---- get -----
var doc = client.Get<MyType>(i => i
.Index(indexName)
.Type("myType")
.Id(2)
);
Console.WriteLine();
Console.WriteLine("doc.Source.DateToBeUsed: ");
Console.WriteLine(doc.Source.DateToBeUsed);
Console.WriteLine();
Console.WriteLine("doc.RequestInformation.ResponseRaw: ");
Console.WriteLine(Encoding.UTF8.GetString(doc.RequestInformation.ResponseRaw));
我看到以下结果作为输出:
created index
set mapping
doc indexed
doc.Source.DateToBeUsed:
2012-05-21T09:51:34.073
doc.RequestInformation.ResponseRaw:
{"_index":"so-27927069","_type":"myType","_id":"2","_version":1,"found":true,"_source":{
"ElasticId": "2",
"DateToBeUsed": "2012-05-21T09:51:34.073"
}}
(通过 Fiddler 观察流量,我看到ResponseRaw
值与响应Get
请求的有效负载完全匹配。
我使用的是 Elasticsearch 版本 1.5.2 和 NEST 版本 1.6.0。 (也许您看到的问题在此期间的某个时候得到了解决......