Neo4j Python MERGE 语句上的驱动程序语法错误

Neo4j Python Driver Syntax Error on MERGE statement

我写了一个 python 脚本来与 neo4j 数据库交互。

result_a = tx.run("MERGE (n:Word$tag_a { name: $name_a}) ON CREATE SET n.corpus = 1 ON MATCH SET n.corpus = n.corpus + 1 RETURN id(n) AS node_id", tag_a=tag_a, name_a=name_a)

其中 $tag_a 包含一个以 : 开头的字符串,$name_a 包含一个字符串

当我执行我的代码时,我得到了这个异常:

neo4j.exceptions.CypherSyntaxError: {code: Neo.ClientError.Statement.SyntaxError} {message: Invalid input '{': expected ")" (line 1, column 21 (offset: 20))
"MERGE (n:Word$tag_a { name: $name_a}) ON CREATE SET n.corpus = 1 ON MATCH SET n.corpus = n.corpus + 1 RETURN id(n) AS node_id"
                     ^}

当我在 neo4j 控制台中执行类似的语句时,我没有收到任何错误:

neo4j@neo4j> MERGE (n:Word:G { name: 'test'}) ON CREATE SET n.corpus = 1 ON MATCH SET n.corpus = n.corpus + 1 RETURN id(n) AS node_id
             ;
+---------+
| node_id |
+---------+
| 0       |
+---------+

1 row
ready to start consuming query after 843 ms, results consumed after another 528 ms
Added 1 nodes, Set 2 properties, Added 2 labels

好像不能像我这样使用$tag_a。有没有办法在不以可能不安全的方式制作查询的情况下解决这个问题?

neo4j 版本 neo4j 4.3.2

python 版本 3.8.10

我建议你使用 f-string,然后使用 python 语法传递你需要的参数。

query = f"MERGE (n:Word{tag_a} {{ name: {name_a}}}) ON CREATE SET n.corpus = 1 ON MATCH SET n.corpus = n.corpus + 1 RETURN id(n) AS node_id"
result_a = tx.run(query)

请注意始终对查询大括号进行转义(重复)