我有一个带有字段的简单图表 - 每个字段有 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 两步。
我在这个中使用了jo4neo...
如何在 cypher 或 gremlin 中实现相同的功能?
我找到了朋友的朋友的例子,但这并没有真正帮助我,因为我需要深度作为参数(即在某些情况下我想要深度为 4,有时为 6)。
Note:除了字段之外还有其他连接,但我显然只需要字段。另外,我需要获取所有连接的节点 - 而不仅仅是一个方向。
解决方案:感谢指点,我得到了解决方案:
start n=node(13) match n-[*1..2]->b where b.__type__ = "model.Field" return distinct b