1
我試圖獲取一個字符串的數字。我正在使用正則表達式來完成此操作。當我得到結果時,我得到像「1」,「10」,「2」的東西。我想對它進行排序,所以我需要向左邊添加零以自然排序。無痛腳本 - 將字符串轉換爲清除
我的腳本是在這裏:
{
"from": 0,
"size": 40,
"sort": [
{
"fields.myfield.keyword": { "order": "asc" },
"_script": {
"type": "string",
"script": {
"inline":
"def m = /(\\d+$)/.matcher(doc['fields.myfield.keyword'].value);
if (m.find())
{
String s = m.group(1);
String.format(\"%05d\", s.toString());
}
else { return 0 }"
},
"order" : "asc"
}
}
],
"_source": { "include": ["fields.myfield"] }}
當我嘗試執行命令,我收到以下錯誤:
"failed_shards": [
{
"shard": 0,
"index": "myindex",
"node": "kctN6d5ITrqtIMj4cbChKQ",
"reason": {
"type": "script_exception",
"reason": "compile error",
"script_stack": [
"... ; String.format(\"%05d\", s.toString()); } else { re ...",
" ^---- HERE"
],
"script": "def m = /(\\d+$)/.matcher(doc['fields.myfield.keyword'].value); if (m.find()) { String s = m.group(1); String.format(\"%05d\", s.toString()); } else { return 0 }",
"lang": "painless",
"caused_by": {
"type": "class_cast_exception",
"reason": "Cannot cast from [String] to [def[]]."
}
}
}
如何添加零離開,而無需使用String.Formatter?
我在哪裏嘗試從字符串轉換爲DEF?
我沒有把握,但左零爲整,我認爲這將被忽略。我需要像「0001」,「0011」這樣的東西來自然排序。 – NatsuDragonEye