有没有选择从lucene索引中获取一个随机节点,其index.query如下所示?
Index<Node> index = graphDb.index().forNodes("actors");
Node rand = index.query("foo:bar").getRandom();
由于 JORN
答案 0 :(得分:1)
我的问题是逐步通过节点列表,但是按随机顺序。
我玩了一下,最后以“id cache”作为临时解决方案,只存储了具有特定属性(未使用和foo = bar)的节点。
如果您还要将新节点添加到缓存中并将其从缓存中删除,则可以更长时间地使用缓存。
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));
}