3

我有一个带有字段的简单图表 - 每个字段都有 4 个邻居(东北-东南-西):

@NodeEntity
public class Field {
    @GraphId
    Long id;
    Field north;
    Field east;
    Field south;
    Field west;
    //.. other stuff
}

我设置了一个图形数据库(neo4j),所以这些都很好并且连接起来(就像一个网格)。我现在要做的是从一个起始节点获取所有节点,即 5 跳。

使用经典遍历,这可以正常工作,如下所示:

public  Collection<Field> getFieldsWithDepth(Field startField, final int depth) {       
    Node fieldNode = this.getGraphdb().getNodeById(startField.getId());
    Traverser traverser = fieldNode.traverse(Traverser.Order.BREADTH_FIRST, // check direct relations first, then go deeper 
            new StopEvaluator() {

                @Override
                public boolean isStopNode(TraversalPosition pos) {
                    if (pos.depth()==depth)
                        return true;
                    else
                        return false;
                }
            },  // worst case: go to end of graph 
            new ReturnableEvaluator() {

                @Override
                public boolean isReturnableNode(TraversalPosition pos) {
                    return true;
                }
            },
            Relations.north,    
            Direction.OUTGOING,
            Relations.east,
            Direction.OUTGOING,
            Relations.west,
            Direction.OUTGOING,
            Relations.south,
            Direction.OUTGOING
            );

    ArrayList<Field> fields = new ArrayList<Field>();
    for (Node node : traverser.getAllNodes())
    {
        fields.add((Field)this.getGraph().get(node));
    }
    return fields;
}

因此,如果我有这样的“地图”:

  1   2   | 3|   4    5 
  6  |7|  | 8| | 9|  10
|11| |12| *13* |14| |15|
 16  |17| |18| |19|  20
 21   22  |23|  24   25 

我用起始节点“13”和“深度”为 2 进行查询,我需要得到标记的 12 个节点——因为它们距离 13 有 2 步。

我在这个中使用了 jo4neo...

如何在 cypher 或 gremlin 中实现相同的功能?

我找到了朋友之友的例子,但这并没有真正帮助我,因为我需要将深度作为参数(即在某些情况下,我希望深度为 4,有时为 6)。

注意:除了 Fields 之外还有其他连接,但我显然只需要字段。此外,我需要获取所有连接的节点 - 而不仅仅是一个方向。

解决方案:感谢指针,我得到了解决方案:

start n=node(13) match n-[*1..2]->b where b.__type__ = "model.Field" return distinct b
4

2 回答 2

4

http://docs.neo4j.org/chunked/snapshot/query-match.html#match-variable-length-relationships

START a=node(3)
MATCH a-[:FRIEND*1..3]->x
RETURN a,x

如果您只需要 3 个步骤:

MATCH a-[:FRIEND*3..3]->x

希望这可以帮助!

于 2012-01-10T15:02:21.207 回答
0

以及如何查找深度级别?意味着作为*1..3显示“A->B, A->B->C & A->B->C->D”作为安德烈斯的密码查询的结果,我想找到一个深度计数,即, 1 在 A->B 的情况下;2 在 A->B->C 等情况下。

于 2014-03-13T06:47:15.547 回答