I want to achieve some kind of "random" sort using hibernate search elasticsearch library. What I'm doing is the following:
Implement a FieldComparator:
public class RandomOrderFieldComparator extends FieldComparator<Integer> {
private final Random randomGenerator = new Random();
@Override
public int compare(int slot1, int slot2) {
return randomGenerator.nextInt();
}
@Override
public void setTopValue(Integer value) {
//not needed as the purpose is to generate random integers w
}
@Override
public Integer value(int slot) {
return randomGenerator.nextInt();
}
@Override
public LeafFieldComparator getLeafComparator(LeafReaderContext context) throws IOException {
return null;
}
}
Implement FieldComparatorSource
public class SampleFieldComparatorSource extends FieldComparatorSource {
@Override
public FieldComparator<?> newComparator(String fieldname, int numHits, int sortPos, boolean reversed) throws IOException {
return new RandomOrderFieldComparator();
}
}
Finally create a custom SortField providing the FieldComparatorSource:
queryBuilder
.sort()
.byNative(
new SortField(
"id",
new SampleFieldComparatorSource()
)
);
The problem is that it still generates a query using just a normal sort on the 'id' field and the comparator is never hit:
"sort": [
{
"id": {
"order": "asc"
}
}
]
What am I doing wrong and what is the best way to implement a "random" sort using the hibernate search library?