I have a mapping with a field type of "text" that contains a date:
My mapping looks like this:
"title" : "Nebula",
"has_store" : true,
"createdAt" : "Wed Nov 25 2020 05:37:08 GMT+0000 (Coordinated Universal Time)",
How can I sort by this date createdAt
to get the newest items first?
My query is using ElasticSearch.js
bool: {
must: [{
multi_match: {
query: data.searchTerm,
fields: [
"data.title^2.5",
],
operator: "or",
lenient: "true",
type: 'best_fields',
fuzziness: "AUTO"
}
}],
}
},
from: Number(data.lastKey),
size: Number(data.size)
}
Is there a way to use scripts to do this? If so - how can I process the date into a real date object?
Or is there a way to sort by dates using the string format I have currently?
It'd be best to reindex your fields as dates
but if you have to sort by dates which are inside text
, here's how you do it:
GET your_index/_search
{
"sort": [
{
"_script": {
"type": "number",
"script": {
"lang": "painless",
"source": """
def df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z '('zzzz')'");
return df.parse(doc['createdAt.keyword'].value).getTime();
"""
},
"order": "desc"
}
}
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.