Neo4j定制过程:如何传递查询参数?



我正试图根据文档和那里引用的模板为Neo4J GraphDB编写一个自定义过程。该过程最终应该使用GDSL为具有作为过程参数提供的特定标签的节点生成图形投影。为此,当然有必要将标签传递给将在自定义过程中执行的查询。但是,我似乎不知道如何将参数传递给查询字符串。

@Procedure(value = "custom.projectGraph")
@Description("Generates a projection of the graph.")
public Stream<ProRecord> projectGraph(@Name("graph") String graph) {
Map<String, Object> params = Map.of (
"graph", graph
);
return tx.execute("call gds.graph.project.cypher("$graph", "
+ ""MATCH (n:$graph) return id(n) as id", "
+ ""MATCH (src:$graph)-[]-(dst:$graph) "
+ "RETURN id(src) AS source, id(dst) AS target") "
+ "YIELD graphName", params)
.stream()
.map(result -> (String) result.get("graphName"))
.map(ProRecord::new);
}
public static final class ProRecord {
public final String graphName;
public ProRecord(String graphName) {
this.graphName = graphName;
}
}

不幸的是,这段代码没有按预期工作,抛出了以下异常:

Invalid input '$': expected an identifier

我确实从其他示例中复制了带有$-字符的前缀占位符的语法,因为我在库的JavaDoc中找不到任何关于传递查询参数的提示。这是自定义neo4j过程的正确文档吗?我是否可能在这里使用错误的方法来发出我的查询?如果有人能在那件事上给我指点一下方向,那就太好了。

通常,当您使用字符串参数时,$param会自动加引号,不像String.format这样。

因此在你的查询中有两个问题:

  • "$graph":在这种情况下,你是双重引用参数,尽量只写$graph而不是
  • n:$graph这样的事情不能不幸地完成,neo4j参数处理不能识别在哪里引用和不引用,所以你可以使用String.format或concat字符串与参数(例如"MATCH (n:" + $graph + ") return id(n)...")。

所以,简而言之,这段代码应该适用于您的情况:

return tx.execute("call gds.graph.project.cypher($graph, " +
"'MATCH (n:' + $graph + ') return id(n) as id', " +
"'MATCH (src:' + $graph + ')-[]-(dst:' + $graph + ') RETURN id(src) AS source, id(dst) AS target') YIELD graphName", 
params)
.stream()
.map(result -> (String) result.get("graphName"))
.map(ProRecord::new);

最新更新