python - 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
.
解决方案
虽然在 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
推荐阅读
- javascript - CSS 中的 SVG 动画
- python - Python pandas 中的灵活链接
- docker - 无法在 kubernetes 命名空间下启动 pod
- mysql - 同一列上的索引和分区
- python - 在 Python 中为每个 Celery 任务分配特定数量的工人
- html - HTLM 下载文件,在浏览器中输入 url
- reactjs - 两个 React 不同且已安装的组件可以使用 props 相互通信吗?
- node.js - Firebase 函数,增加一个值
- azure - 一次删除所有 Azure 策略
- java - Java REST 客户端 - javax.ws.rs.ProcessingException: javax/xml/bind/annotation/XmlTransient