英文:
Elasticsearch condition on sorting in java
问题
以下是翻译好的部分:
对于单字段排序,我正在使用以下代码:
searchSourceBuilder.sort(SortBuilders.fieldSort("count").order(SortOrder.DESC));
但是现在我需要添加类似这样的条件:
searchSourceBuilder.sort(SortBuilders.fieldSort(count <= 0 ? "visitor" : "visitor" * "count").order(SortOrder.DESC));
我无法找到任何线索来完成这个操作。在Elasticsearch中是否有可能实现,还是我需要使用另一种方法?
英文:
For single field sorting I am using this code
searchSourceBuilder.sort(SortBuilders.fieldSort("count").order(SortOrder.DESC));
but now I need to add condition like this
searchSourceBuilder.sort(SortBuilders.fieldSort(count <= 0 ? "visitor":"visitor" * "count").order(SortOrder.DESC));
I am not getting any clue to do this. Is it possible at elasticsearch or I need to do it another way?
答案1
得分: 2
你需要使用的是 SortBuilders.scriptSort()
(基于脚本的排序),像这样:
Script script = new Script("doc.count.value <= 0 ? doc.visitor.value : doc.visitor.value * doc.count.value");
SortBuilders.scriptSort(script, ScriptSortType.NUMBER).order(SortOrder.DESC);
英文:
What you need to use is SortBuilders.scriptSort()
(script-based sorting), like this:
Script script = new Script( "doc.count.value <= 0 ? doc.visitor.value : doc.visitor.value * doc.count.value");
SortBuilders.scriptSort(script, ScriptSortType.NUMBER).order(SortOrder.DESC);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论