how to add variables into neo4j cypher code inside python

I am trying to get a function argument into the cypher code in my python function. The function takes 3 arguments and adds a relation ship of given type between the persons and is as below (the function is based on the example from https://neo4j.com/docs/python-manual/current/get-started/):

def create_and_return_relationship(tx, person1_tid, person2_tid, rel_type):
        query = (
            "MATCH (p1:Person {tid: $person1_tid})"
            "MATCH (p2:Person {tid: $person2_tid})"
            "MERGE (p2)-[r: {REL: $rel_type}]->(p1)"
            "RETURN type(r)"
        )
        result = tx.run(query, person1_tid=person1_tid, person2_tid=person2_tid, rel_type=rel_type)
        try:
            return [{"p1": record["p1"]["name"], "p2": record["p2"]["name"]}
                    for record in result]

How ever when I run the script I get the below syntax error.

neo4j.exceptions.CypherSyntaxError: {code: Neo.ClientError.Statement.SyntaxError} {message: Invalid input '{': expected an identifier (line 1, column 90 (offset: 89))
"MATCH (p1:Person {tid: $person1_tid})MATCH (p2:Person {tid: $person2_tid})MERGE (p2)-[r: {REL: $rel_type}]->(p1)RETURN type(r)"
                                                                                          ^}

is it possible to use variables in the relation part of the cypher query?

1 answer

  • answered 2022-01-16 19:03 Tomaž Bratanič

    You cannot use variables for relationship type in Neo4j Cypher. You need to either do string concatenation or use apoc to merge dynamic relationship type:

    In your example, you would use:

    MATCH (p1:Person {tid: $person1_tid})
    MATCH (p2:Person {tid: $person2_tid})
    CALL apoc.merge.relationship(p1, $rel_type,{}, {},p2, {})
    YIELD rel
    RETURN rel;
    

    More info in docs: https://neo4j.com/labs/apoc/4.1/overview/apoc.merge/apoc.merge.relationship/

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum