How do I use a python variable value to name a new node created in neo4j

130 views Asked by At

I have the following line of code

tx.run(CREATE n) using the bolt library for neo4j to python.

I will be receiving a user input which I store in a variable, and I wish to name the node according to that. How should I approach this? Thanks

Another instance could be this. I get a CQL syntax error with this

    if(tx.run("MATCH(n:Player{name: playername_})" "RETURN n")):
        tx.run("CREATE (playername_:Player)")
        tx.run("MATCH(username_:User)(playername_:Player)" "CREATE (playername_)-[r:IN_TEAM]->(username_)")
    else:
        tx.run("MATCH(username_:User)(playername_:Player)" "CREATE (playername_)-[r:IN_TEAM]->(username_)")

The tx.run("CREATE (playername_:Player)") line throws up the following error

neo4j.exceptions.CypherSyntaxError: {code: Neo.ClientError.Statement.SyntaxError} {message: Variable `playername_` not defined (line 1, column 22 (offset: 21)) "MATCH(n:Player{name: playername_})RETURN n"

1

There are 1 answers

2
Lukasmp3 On

I believe this could help you:

playername = 'Joe'
username = 'Martin'

tx.run("CREATE (n:Player) SET n.playername = $playernamePar", playernamePar=playername)
tx.run("CREATE (n:User) SET n.username = $usernamePar", usernamePar=username)
tx.run("MATCH (p:Player),(u:User) 
        WHERE p.playername = $playernamePar 
        AND u.username = $usernamePar 
        CREATE (p)-[:inTeam]->(u)",
        playernamePar=playername, usernamePar=username)