4

I have a variable name="Rahul" and, I want to pass this variable to cypher query in Py2neo in the following manner:

line=session.execute("MATCH (person)WHERE person.name=name RETURN person")

but i am getting an error -

"py2neo.cypher.InvalidSyntax: name not defined (line 1, column 33)"

how to pass the variable in py2neo

stephenmuss
  • 2,445
  • 2
  • 20
  • 29
Saubhagya Jena
  • 141
  • 1
  • 2
  • 3

4 Answers4

7

If name is a parameter you need to enclose it in curly braces. Your query should look something like

MATCH (person) WHERE person.name = {name} RETURN person

Your Python code may look along the following lines

graph_db = neo4j.GraphDatabaseService()
qs = 'MATCH (person) WHERE person.name = {name} RETURN person'
query = neo4j.CypherQuery(graph_db, qs)
results = query.execute(name='Rahul')
print results
stephenmuss
  • 2,445
  • 2
  • 20
  • 29
  • 4
    Starting with version 3.0.9, the `$name` syntax was added for parameters. The `{name}` syntax is now deprecated and will be removed in a later release. – cybersam Oct 26 '17 at 19:38
1

If you'd like to wrap your query in a transaction, you can use the cypher module to create a session, and then create a transaction object. The syntax to do this is slightly different from that in neo4j.CypherQuery, mentioned in the answer by stephenmuss.

from py2neo import neo4j, cypher
graph_db = neo4j.GraphDatabaseService('http://localhost:7474/db/data/')

# Create a Session
session = cypher.Session('http://localhost:7474')
# Create a transaction
tx = session.create_transaction()

# Write your query, and then include it in the transaction with a dictionary
# of parameters.
qs = 'MATCH (person) WHERE person.name = {name} RETURN person'
tx.append(qs, parameters={'name': 'Rahul'})
results = tx.commit()
Community
  • 1
  • 1
Brad Montgomery
  • 2,621
  • 1
  • 24
  • 24
  • 1
    Starting with version 3.0.9, the `$name` syntax was added for parameters. The `{name}` syntax is now deprecated and will be removed in a later release. – cybersam Oct 26 '17 at 19:38
0

Another way to get the nodes is:

from py2neo import Graph, authenticate

server = "localhost:7474"

# set up authentication parameters
authenticate(server, <user>, <password>)

graph = Graph("{0}/db/data".format(server))
results = graph.find("person", "name", "Rahul")
Paulo Fabrício
  • 319
  • 3
  • 17
0

Just to be clear, the generic answer to passing parameters to a py2neo query is this:

from py2neo import Graph

graph = Graph("URI", auth=("USER", "PASSWORD"))
graph.run("MATCH (p:Person) WHERE p.name=$name RETURN p", parameters={'name': 'Rahul'})

(Note the $-sign)

Bertil Johannes Ipsen
  • 1,656
  • 1
  • 14
  • 27