5

I want to pass parameter in CREATE using Python e.g: '''

n = "abc"
a = 1234

cqlCreate = "CREATE (cornell:university { name: $n,yob:$a})"

''''

but it dosen't work.. any suggestions please

jose_bacoy
  • 12,227
  • 1
  • 20
  • 38
Sama
  • 75
  • 10

3 Answers3

6

It actually depends on the Python driver that you are using to connect to Neo4j (check https://neo4j.com/developer/python/ to see the list of available drivers). If you are using the official neo4j-driver, the code you wrote is correct. In order execute the Cypher query, you could do something like this:

from neo4j import GraphDatabase

uri = # insert neo4j uri
user = # insert neo4j username
password = # insert neo4j password

n = "abc"
a = 1234
query = "CREATE (cornell:university { name: $n,yob:$a})"

driver = GraphDatabase.driver(uri, auth=(user, password))
session = driver.session()
result = session.run(query, n=n, a=a)
session.close()
driver.close()

Although âńōŋŷXmoůŜ's answer will probably work, it is not recommended way to it.

See also:

  • While frowned upon, to me, the f-string method is more flexible, because sometimes we want to parametrize the node labels too, which is currently not supported by Cypher.(https://neo4j.com/docs/cypher-manual/current/syntax/parameters/) – Shern Feb 18 '22 at 02:07
4

You can use the f-strings in Python. See example below. Note that

  1. You need to use {{ as escape character for {

2 You need to use \ as escape character for "

n = "abc"
a = 1234

cqlCreate = f"CREATE (cornell:university {{name: \"{n}\", yob: {a}}})"
print (cqlCreate)

Result:
CREATE (cornell:university {name: "abc", yob: 1234})

reference: https://www.python.org/dev/peps/pep-0498/

jose_bacoy
  • 12,227
  • 1
  • 20
  • 38
1

I had tried below format and was working perfectly for me. I am using neo4j 5.3.0

    info='Public'

    cypherQ= "MATCH  (n1{name:$info}), (a1{ID:'PL07227'}) RETURN exists( (n1)-[:my_dummy_relation]-(a1) )"

    session.run(cypherQ, info=info)
Tono Kuriakose
  • 718
  • 6
  • 19