我有一个弹性的搜索索引,我不能设置每个字段的映射,所以日期是字符串…
有人知道我会如何对字符串日期进行排序吗?
我已经看过_script了
{
"query" : {
....
},
"sort" : {
"_script" : {
"script" : "doc['field_name'].value",
"type" : "string",
"order" : "asc"
}
}
}但这是失败的,因为它是一个被分析的领域。
任何建议都是很棒的!
谢谢
发布于 2013-08-23 23:46:04
如果日期的格式是已知的,您可以将该格式添加到dynamic_date_formats (查看此link)设置。当你为一个新的字符串字段建立索引时,它将被转换为date类型,该类型可以用普通的方式排序。
示例:
创建不带属性的索引:
curl -XPUT http://localhost:9200/dates -d '
{
"dates" : {
"dynamic_date_formats" : ["yyyy-MM-dd", "dd-MM-yyyy"],
"properties" : {
}
}
}'索引2文档:
curl -XPUT 'http://localhost:9200/dates/dates/1' -d '
{
"arbitraryDate": "2013-01-01"
}'
curl -XPUT 'http://localhost:9200/dates/dates/2' -d '
{
"arbitraryDate": "2012-01-01"
}'如果您检查映射,您将看到该字段不是字符串:
curl -XGET 'http://localhost:9200/dates/_mapping'结果:
{
"dates": {
"dates": {
"properties": {
"arbitraryDate": {
"type": "date",
"format": "dateOptionalTime"
}
}
}
}
}现在,您可以轻松地进行排序:
curl -XGET 'http://localhost:9200/dates/_search' -d '
{
"query": {
"match_all": {}
},
"sort": [
{
"arbitraryDate": {
"order": "asc"
}
}
]
}'发布于 2022-01-26 06:59:49
你可以像下面这样使用Elasticearch的无痛脚本;
{
"size": "100",
"query": {
"match_all": {}
},
"sort": [
{
"_script": {
"type": "number",
"script": {
"source": "String dateAsString = doc['field_name'].value; String dateformat = 'yyyy-MM-ddZ'; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateformat); return ZonedDateTime.parse(dateAsString, formatter).toInstant().toEpochMilli()"
},
"order": "desc"
}
}
]
}https://stackoverflow.com/questions/18405195
复制相似问题