简体   繁体   中英

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 .

While there is no built-in option to read directly from a file in py2neo, there is a mechanism to get a sequence of parameters as you want. So, what remains is just using a function to read the query from the file and use the parameters. This should look something along the lines of:

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

where some_cypher.cypher contains:

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

There is no such functionality built into py2neo. You'll have to roll your own function if you want to do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM