详细介绍了Wes的想法.在自定义PathEvaluator中,您需要设置分支状态以记住第一个关系的方向.所有后续访问都会检查最后一个关系是否与方向匹配.在伪代码中:
class SameDirectionPathEvaluator implements PathEvaluator {
public Evaluation evaluate(Path path, BranchState 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;
}
}
请注意我没有编译或测试上面的代码 – 它只是为了草拟这个想法.
UPDATE
似乎有一种更有效的方法来做到这一点.由于遍历在调用赋值器之前使用扩展器,因此在扩展器中实现此行为更有意义:
class ConstantDirectionExpander implements PathExpander() {
@Override
public Iterable expand(Path path, BranchState state) {
if (path.length()==0) {
return path.endNode().getRelationships(types);
} else {
Direction direction = getDirectionOfLastRelationship(path);
return path.endNode().getRelationships(direction, types);
}
}
@Override
public PathExpander 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)