所以,我正在开发一个应用程序,我需要一个搜索工具,将索引照片和文档-但有时我不知道文档起源的确切月份或日期,所以到目前为止,我一直将日期存储在我的MySQL表作为date
或datetime
字段,允许可选值:
2015-03-11 // Valid MySQL date
2015-12-00 // Also a valid MySQL date, but a null day to represent 'it is not known'
2015-00-00 // Another valid MySQL date, with a null date and month to represent 'this document came from the year 2015, but at some unknown point'
现在,这实际上工作得很好,MySQL仍然会以适当的方式对日期进行排序。
然而,现在我开始使用Elasticsearch构建搜索工具,它显然对这种语法不满意。尝试索引日期时间值超出范围的文档(如2015-00-00
),结果如下:
{
"error":"MapperParsingException[failed to parse [originated_at]]; nested: MapperParsingException[failed to parse date field [2015-00-00], tried both date format [dateOptionalTime], and timestamp number with locale []]; nested: IllegalFieldValueException[Cannot parse '"2015-00-00'": Value 0 for monthOfYear must be in the range [1,12]]; ",
"status":400
}
原因很明显。然而,可选日期是一个要求,我需要我选择的解决方案来允许这一点。
让Elasticsearch允许我存储可选的日期属性并且仍然能够按日期排序和搜索的最佳方法是什么?
在您的映射中,您可以使用||
分隔的几种不同格式声明日期字段,如下所示:
{
"date_field": {
"type": "date",
"format": "yyyy||yyyy-MM||yyyy-MM-dd"
}
}
因此,您将能够存储以下任何日期:
- 2015(即
yyyy
) - 2015-12(即
yyyy-MM
) - 2015-12-01(即
yyyy-MM-dd
)
设置映射:
{
"yourIndex": {
"properties": {
"date": {
"type": "date",
"format": "yyyy-MM-dd HH:mm:ss"
}
}
}
}
还有,看这里- Elasticsearch映射日期格式