Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Randomizing top-n results in Solr
import java.io.IOException;
import java.util.Map;
import java.util.Random;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.DoubleDocValues;
public class RandomValueSource extends ValueSource {
final static ThreadLocal<Random> RANDOMIZERS = new ThreadLocal<Random>() {
protected Random initialValue() {
return new Random();
}
};
@Override
public String description() {
return "rnd()";
}
@Override
@SuppressWarnings("rawtypes")
public FunctionValues getValues(Map context, AtomicReaderContext readerContext) throws IOException {
return new DoubleDocValues(this) {
@Override
public float floatVal(int doc) {
return RANDOMIZERS.get().nextFloat();
}
@Override
public int intVal(int doc) {
return RANDOMIZERS.get().nextInt();
}
@Override
public long longVal(int doc) {
return RANDOMIZERS.get().nextLong();
}
@Override
public double doubleVal(int doc) {
return RANDOMIZERS.get().nextDouble();
}
@Override
public String strVal(int doc) {
return Double.toString(RANDOMIZERS.get().nextDouble());
}
@Override
public Object objectVal(int doc) {
return RANDOMIZERS.get().nextDouble();
}
@Override
public String toString(int doc) {
return description();
}
};
}
@Override
public boolean equals(final Object o) {
return o == this;
}
@Override
public int hashCode() {
return RANDOMIZERS.get().hashCode();
}
import org.apache.lucene.queries.function.ValueSource;
import org.apache.solr.search.FunctionQParser;
import org.apache.solr.search.SyntaxError;
import org.apache.solr.search.ValueSourceParser;
public class RandomValueSourceParser extends ValueSourceParser {
@Override
public ValueSource parse(final FunctionQParser fp) throws SyntaxError {
return new RandomValueSource();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.