在Cypher查询中允许深度参数

时间:2019-03-05 15:56:05

标签: python neo4j cypher

我正在使用Neo4j Bolt Driver 1.7 for Python从特定数据库中提取路径,这是导致问题的代码示例。

from neo4j import GraphDatabase

uri = "bolt://0.0.0.0:7878"
driver = GraphDatabase.driver(uri, auth=("neo4j", "neo4j"))

db = driver.session()
query =  '''
    MATCH tree = (n:Class)-[r:SUBCLASSOF*{depth}]->(parent)      # <---- ERROR here
    WHERE n.obo_id = {go}
    RETURN [n in nodes(tree) | n.obo_id] as GOID
'''
results = []
goid = "GO:0051838"
for record in db.run(query, go=goid, depth="..2"):
    results.append(record["GOID"])

print(results)

当我使用{depth}参数时,出现以下错误:

Traceback (most recent call last):
  File "neoEnrich.py", line 16, in <module>
    for record in db.run(query, go=goid, depth="..2"):
  File "/usr/local/lib/python3.6/site-packages/neo4j/__init__.py", line 499, in run
    self._connection.fetch()
  File "/usr/local/lib/python3.6/site-packages/neobolt/direct.py", line 414, in fetch
    return self._fetch()
  File "/usr/local/lib/python3.6/site-packages/neobolt/direct.py", line 454, in _fetch
    response.on_failure(summary_metadata or {})
  File "/usr/local/lib/python3.6/site-packages/neobolt/direct.py", line 738, in on_failure
    raise CypherError.hydrate(**metadata)
neobolt.exceptions.CypherSyntaxError: Parameter maps cannot be used in MATCH patterns (use a literal map instead, eg. "{id: {param}.id}") (line 2, column 38 (offset: 42))
"    MATCH tree = (n:Class)-[r:SUBCLASSOF*{depth}]->(parent)"
                                          ^

当用{depth}替换..2时,我得到了期望的结果:

[['GO:0051838', 'GO:0051801'],
 ['GO:0051838', 'GO:0051801', 'GO:0051883'],
 ['GO:0051838', 'GO:0051801', 'GO:0051715'],
 ['GO:0051838', 'GO:0051873'],
 ['GO:0051838', 'GO:0051873', 'GO:0051883'],
 ['GO:0051838', 'GO:0051873', 'GO:0051852']]

这里是否有允许深度参数的方法?因为用户将指定深度(将是功能参数)。

4 个答案:

答案 0 :(得分:1)

不允许使用参数设置节点标签,关系标签,关系深度。

如果您确实需要此深度作为参数,请在python中创建一个作为字符串的查询,并将关系深度作为参数传递给它。

保留查询中的其他参数(此处为go)。

答案 1 :(得分:0)

MATCH tree = (n:Class)-[r:SUBCLASSOF*..10]->(parent)
WHERE LENGTH(tree)<=$depth

答案 2 :(得分:0)

您可以将parameters用于APOC函数apoc.path.expandminLevelmaxLevel参数。

例如:

MATCH (n:Class)
WHERE n.obo_id = $go
CALL apoc.path.expand(n, "SUBCLASSOF>", "", 1, $depth) YIELD path
RETURN [n IN NODES(path) | n.obo_id] AS GOID

答案 3 :(得分:0)

感谢@Raj的回答,我发现最简单的解决方案是使用.format()

查询变为:

query =  '''
    MATCH tree = (n:Class)-[r:SUBCLASSOF*{depth}]->(parent)
    WHERE n.obo_id = "{go}"
    RETURN [n in nodes(tree) | n.obo_id] as GOID
'''

然后构造查询并执行db.run()

full_query = query .format(go=goid, depth="..2")
for record in db.run(full_query):
    ...