0

How should I implement script sort in spring-data-elasticsearch 5.3.x

NativeQueryBuilder nativeQueryBuilder= new NativeQueryBuilder();
nativeQueryBuilder.withQuery(query);
nativeQueryBuilder.withSort(Sort.Order.desc('key'));
return elasticsearchTemplate.search(nativeQueryBuilder.build(), xxx.class);

Now, I want to add a script-based sorting on top of this. I know how to write the script, but it seems that script-based sorting is not supported in the context of NativeQueryBuilder.

1 Answer 1

0

you need to use the NativeSearchQueryBuilder and add a ScriptSortBuilder to it. Here is how you can do it:

// Create the query
QueryBuilder query = QueryBuilders.matchAllQuery();

// add the script
Script script = new Script("your_script");

// Create the ScriptSortBuilder
ScriptSortBuilder scriptSortBuilder = new ScriptSortBuilder(script, ScriptSortBuilder.ScriptSortType.NUMBER);
scriptSortBuilder.order(SortOrder.DESC);

// Build 
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(query);
nativeSearchQueryBuilder.withSort(scriptSortBuilder);

// Execute
NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
return elasticsearchTemplate.search(searchQuery,YourClass.class);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. Actually, ScriptSortBuilder and NativeSearchQueryBuilder have been removed in the new version of the SDK. This was the original way of writing it. My final solution was to design the sorting field in the script as an independent index field, because after the script's sorting was verified through DSL, I found that the impact on performance was really too great, so it didn't meet my expectations.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.