如何在py2neo中将参数传递给cypher查询

时间:2014-07-20 07:38:15

标签: python neo4j cypher py2neo

我有一个变量 命名="的Rahul" 和, 我想以下列方式将此变量传递给Py2neo中的cypher查询:

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

但是我收到了错误 -

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

如何在py2neo中传递变量

3 个答案:

答案 0 :(得分:7)

如果name是参数,则需要将其括在花括号中。您的查询应该类似于

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

您的Python代码可能会看到以下几行

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

答案 1 :(得分:1)

如果您想在事务中包装查询,可以使用cypher模块创建会话,然后创建事务对象。执行此操作的语法与neo4j.CypherQuery中的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() 略有不同,在stephenmuss的答案中提到。

{{1}}

答案 2 :(得分:0)

获取节点的另一种方法是:

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