Saubhagya Jena
Saubhagya Jena

Reputation: 141

how to pass parameter to cypher query in py2neo

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

Upvotes: 4

Views: 7047

Answers (4)

Bertil Johannes Ipsen
Bertil Johannes Ipsen

Reputation: 1776

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)

Upvotes: 1

Paulo Fabrício
Paulo Fabrício

Reputation: 329

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")

Upvotes: 0

Brad Montgomery
Brad Montgomery

Reputation: 2681

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()

Upvotes: 1

stephenmuss
stephenmuss

Reputation: 2445

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

Upvotes: 7

Related Questions