is there any option to get a random node from a lucene index with a index.query like below?
Index<Node> index = graphDb.index().forNodes("actors");
Node rand = index.query("foo:bar").getRandom();
Thanks jörn
My problem was gradually work through a list of nodes, but in random order.
I played a bit around end ended up with a "id cache" as a temporary solution where only nodes with a specific attribute (not used and foo=bar) are stored.
You could use the cache longer if you'll add new nodes also to the cache and delete them from the cache as well.
private ArrayList<Long> myIndexIDs = new ArrayList<Long>();
private int minCacheSize = 100;
private int maxCacheSize = 5000;
public Node getRandomNode() {
boolean found = false;
Node n = null;
int index = getMyNodeIndex();
long id = myIndexIDs.get(index);
System.out.println(String.format("found id %d at index: %d", id, index));
ExecutionResult result = search.execute("START n=node(" + id + ") RETURN n");
for (Map<String, Object> row : result) {
n = (Node) row.get("n");
found = true;
break;
}
if (found) {
myIndexIDs.remove(index);
myIndexIDs.trimToSize();
}
return n;
}
// fill the arraylist with node ids
private void createMyNodeIDs() {
System.out.println("create node cache");
IndexHits<Node> result = this.myIndex.query("used:false");
int count = 0;
while (result.hasNext() && count <= this.maxCacheSize) {
Node n = result.next();
if (!(n.hasProperty("foo") && "bar" == (String) n.getProperty("foo"))) {
myIndexIDs.add(n.getId());
count++;
}
}
result.close();
}
// returns a random index from the cache
private int getMyIndexNodeIndex() {
// create a new index if you're feeling that it became too small
if (this.myIndexIDs.size() < this.minCacheSize) {
createMyNodeIDs();
}
// the current size of the cache
System.out.println(this.myIndexIDs.size());
// http://stackoverflow.com/a/363732/520544
return (int) (Math.random() * ((this.myIndexIDs.size() - 1) + 1));
}