2012-08-16 121 views
1
得到一个随机节点

是否有任何选项从下面的index.query获取lucene索引中的随机节点?neo4j从索引

Index<Node> index = graphDb.index().forNodes("actors"); 
Node rand = index.query("foo:bar").getRandom(); 

感谢 乔恩

回答

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)); 
}