1

是否有任何选项可以从带有 index.query 的 lucene 索引中获取随机节点,如下所示?

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

谢谢乔恩

4

1 回答 1

1

我的问题是逐步通过节点列表工作,但顺序是随机的。

我玩了一会儿,最终以“id 缓存”作为临时解决方案,其中仅存储具有特定属性(未使用且 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));
}
于 2012-08-19T21:59:28.263 回答