Created
March 29, 2016 18:31
-
-
Save agazzarini/a802eff3b50c03fae2364458719be94e to your computer and use it in GitHub Desktop.
Randomizing top-n results in Solr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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