首页 > 解决方案 > Cypher file as parameter in py2neo python

问题描述

I am trying to pass a cypher file as parameter in py2neo to have the variables in the queries as other parameters. Instead of:

from py2neo import Graph

graph = Graph(password = "*****")

def test(some_things):
    result = graph.run(
                "MATCH (movie:movies)"
                "where movie.name =~ $name "
                "RETURN movie",{"name":"(?i).*" + some_things+ ".*"})
    return result

I am wondering if there is something like this:

from py2neo import Graph

graph = Graph(password = "*****")

def test(some_things):
    result = graph.run("some_cypher.cypher", some_things)
    return result

where some_cypher.cypher could be:

MATCH (movie:movies) where movie.name =~ $name RETURN movie, ,{"name":"(?i).*" + ?+ ".*"}

with ? being the parameter to be replaced in the python file by some_things.

标签: pythonneo4jpy2neo

解决方案


虽然在 py2neo 中没有直接从文件中读取的内置选项,但有一种机制可以根据需要获取一系列参数。所以,剩下的就是使用一个函数从文件中读取查询并使用参数。这应该类似于以下内容:

from py2neo import Graph

graph = Graph(password = "*****")


def run_query_from_file(cypher_file_path,  parameters=None, **kwparameters):
    with open(cypher_file_path, 'r') as cypher_file:
          cypher_query = cypher_file.read().strip()
    graph.run(cypher_query, parameters)

def test1(dict_of_parameters):
    result = run_query_from_file("some_cypher.cypher", dict_of_parameters)
    return result

def test2(**kwparameters):
    result = run_query_from_file("some_cypher.cypher", **kwparameters)
    return result

# Both should work
test1({'username': 'abc', 'password': '123'})
test2('username'='abc', 'password'='123')

其中some_cypher.cypher包含:

MERGE (user:User {username:$username}) WITH user, user.password as user_password SET user.password = $password RETURN user_password


推荐阅读