Search code examples
pythonstringvariablesneo4jstatements

Python Neo4j using string variables in Cypher statements


I am obviously misunderstanding something about the format of the session.run method in the python Neo4j module.

This works:

session.run("statement1"
            "statement2"
             "statement3"
             "statement4", variable list)

But now I need to modify the strings externally to the method: eg I would like to do

s1 = "statement1"
s2 = "statement2"
session.run(s1
            s2
            "statement3"
            "statement4", variable list)

So that I can modify the statement in ways that cannot be handled by the .run method - eg modifying labels on the fly.

But I get a syntax error

I don't understand why this does not work. What am I doing wrong? How can I introduce variables such as label names into a run command like that?

Thanks


Actual code is this:

    s1 = "MERGE (a:Animal:Female {tag: {tag}})"
    session.run(s1
             " MERGE (d:Animal:Female {tag: {dam}})"
            "MERGE (s:Animal:Male {tag: {sire}})"
            "MERGE (d)-[:DamTo{dob:{dob}}]->(a)"
            "MERGE (s)-[:SireTo{dob:{dob}}]->(a)" , tag = tag, dob = dob, dam = dam, sire = sire )

Error message:

" MERGE (d:Animal:Female {tag: {dam}})"
                                      ^
SyntaxError: invalid syntax

Solution

  • In Python, adjacent string literals are automatically concatenated. However, a string variable does not support automatic concatenation.

    Try changing this:

             s1
             " MERGE (d:Animal:Female {tag: {dam}})"
    

    to this:

             s1 +
             " MERGE (d:Animal:Female {tag: {dam}})"
    

    The other automatic concatenations should still work.