我有一个弹性搜索字段ID
,这是一个数字,但在索引中设置为"文本"我无法更改索引,因为需要重新加载大量数据。我正在写一个脚本来做这个排序,但得到一个"Bad_request"错误。
Script script = new Script(ScriptType.INLINE, "painless", "ctx._source.ID.keyword", Collections.emptyMap());
ScriptSortBuilder.ScriptSortType sortType = ScriptSortBuilder.ScriptSortType.NUMBER;
builder.sort(SortBuilders.scriptSort(script, sortType).order(SortOrder.DESC));
searchRequest.source(builder);
response = restsearchClient.search(searchRequest, RequestOptions.DEFAULT);
我已经尝试了以下idorcode值:doc['ID']
,doc['ID.keyword']
,ctx._source.ID
,ctx._source.ID.keyword
。
请建议!
如果我的理解正确,那么你要排序的数字是存储为字符串,而不是作为整数在Elasticsearch。
下面是Elasticsearch查询示例:
{
"query": {
"match_all": {}
},
"sort": {
"_script": {
"type": "Number",
"order": "desc",
"script": {
"lang": "painless",
"source": """
String s = doc['ID.keyword'].value;
int idvalue = Integer.parseInt(s);
return idvalue;
"""
}
}
}
}
下面是Java代码:
Script script = new Script(ScriptType.INLINE, "painless", "String s = doc['ID.keyword'].value;int idvalue = Integer.parseInt(s);return idvalue;", Collections.emptyMap());
ScriptSortBuilder.ScriptSortType sortType = ScriptSortBuilder.ScriptSortType.NUMBER;
builder.sort(SortBuilders.scriptSort(script, sortType).order(SortOrder.DESC));