在 Neo4j 中,有什么方法可以在使用 Java API 时限制路径中的节点和关系类型?

In Neo4j, is there any way to restrict nodes and relation types in path while using Java API?

我有源节点和目标节点我想对路径中的节点和关系类型进行限制。我正在使用 Neo4j Java API.

考虑以下玩具示例,

我们有三个人节点 A、B 和 C。

源节点:A & 目标节点:B。它们之间可能存在许多其他类型的路径。我想将路径限制为特定格式,例如 -

(person) -[worksAt]-> (company) -[CompetitorOf]-> (company) <-[worksAt]- (person)

这可以通过密码查询很容易地实现,但我想知道有什么方法可以使用 Java API.

注意:

  1. 请不要建议对路径长度进行限制,那 不能解决问题。我想限制节点和关系 在路径中输入。
  2. 上面提到的例子是玩具例子。我正在尝试处理的图表更复杂,并且有许多可能的路径无法遍历和验证各个路径。

从您的问题中并不清楚您实际尝试计算的是什么。你有 A 和 B,想知道他们的公司是否是竞争对手?你有C,想找出他们的朋友中有谁在竞争公司工作吗?

无论如何,如果您正在使用遍历 API(您说的是路径),您可以编写自定义 PathExpander which will use the last relationship in the Path 来确定要遍历的下一种关系。

如果您只是手动遍历关系,我看不出问题所在:只需在每一步使用适当的参数调用 Node.getRelationships(RelationshipType, Direction)

与您在 Cypher 中所做的相反,您不会声明您在路径中寻找的模式,您只需计算路径以遵循所需的模式。

仔细阅读 Neo4j java documentation 并试验代码后,我得到了以下解决方案 -

过滤 PathFinder create a custom PathExpander using PathExpanderBuilder 探索的路径。

PathExpanderBuilder pathExpanderBuilder = PathExpanderBuilder.empty();

pathExpanderBuilder.add(RelationshipType.withName("worksat"), Direction.OUTGOING);
pathExpanderBuilder.add(RelationshipType.withName("competitorof"), Direction.BOTH);
pathExpanderBuilder.add(RelationshipType.withName("worksat"), Direction.INCOMING);

PathExpander<Object> pathExpander pathExpander = pathExpanderBuilder.build();

创建自定义 PathExpander 后,您可以使用它来创建适当的 PathFinder,它将通过 PathFinder.

过滤遍历
PathFinder<Path> allPathFinder = GraphAlgoFactory.allSimplePaths(this.pathExpander, 4);


Iterable<Path> allPaths = allPathFinder.findAllPaths(sourceNode, targetNode);

在我们的示例中,sourceNode 将是节点 'A',targetNode 将是节点 'B'。