我面临一个看似简单的问题。我想Neo4j
使用遍历Java API遍历图的节点。我只想包括所有关系具有相同方向的路径。如果我做类似的事情
db.traversalDescription().relationships(<type>, Direction.BOTH)
像
[a]-[:TYPE]->[b]<-[:TYPE]-[c]
也包括我不想要的。我只想要像
[a]-[:TYPE]->[b]-[:TYPE]->[c]
[a]<-[:TYPE]-[b]<-[:TYPE]-[c]
有人可以帮忙吗?看来解决方案应该很简单。
详细介绍Wes的想法。在您的定制中,PathEvaluator
您需要设置分支状态以记住第一个关系的方向。所有后续访问都检查最后一个关系是否与方向匹配。用伪代码:
class SameDirectionPathEvaluator implements PathEvaluator<Direction> {
public Evaluation evaluate(Path path, BranchState<Direction> state) {
if (path.length()==0) {
return Evaluation.EXCLUDE_AND_CONTINUE;
} else if (path.length()==1) {
state.setState(getDirectionOfLastRelationship(path));
return Evaluation.INCLUDE_AND_CONTINUE;
} else {
if (state.getState().equals(getDirectionOfLastRelationship(path)) {
return Evaluation.INCLUDE_AND_CONTINUE;
} else {
return Evaluation.EXCLUDE_AND_PRUNE;
}
}
}
private Direction getDirectionOfLastRelationship(Path path) {
assert path.length() > 0;
Direction direction = Direction.INCOMING
if (path.endNode().equals(path.lastRelationship().getEndNode()) {
direction = Direction.OUTGOING;
}
return direction;
}
}
请注意,我没有编译或测试上面的代码-只是为了勾勒出这个想法。
似乎有一种更有效的方法来执行此操作。由于遍历在调用评估程序之前使用扩展器,因此在扩展器中实现此行为更有意义:
class ConstantDirectionExpander implements PathExpander<STATE>() {
@Override
public Iterable<Relationship> expand(Path path, BranchState<STATE> state) {
if (path.length()==0) {
return path.endNode().getRelationships(types);
} else {
Direction direction = getDirectionOfLastRelationship(path);
return path.endNode().getRelationships(direction, types);
}
}
@Override
public PathExpander<STATE> reverse() {
return this;
}
private Direction getDirectionOfLastRelationship(Path path) {
assert path.length() > 0;
Direction direction = Direction.INCOMING;
if (path.endNode().equals(path.lastRelationship().getEndNode())) {
direction = Direction.OUTGOING;
}
return direction;
}
}
在遍历中,您需要使用InitialBranchSate
:
TraversersDescription td = graphDatabaseService.traversalDescriptioin().
.expand(new ConstantDirectionExpander(reltype))
.traverse(startNode)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句