You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在GQLAlchemy中编写n跳遍历查询?含具体Cypher示例实现咨询

使用GQLAlchemy实现n跳遍历查询

下面提供两种实现对应Cypher语句功能的方法,以2跳遍历计数为例:

方法一:直接执行原生Cypher语句

这是最直接的方式,直接运行你提供的Cypher查询:

from gqlalchemy import Database

# 初始化数据库连接
db = Database("bolt://neo4j:your_password@localhost:7687")

# 执行原生Cypher查询
cypher_query = """
MATCH (n)-[2]->(c)
RETURN Count()
"""
result = db.execute(cypher_query)
# 获取计数结果
count_result = result.scalar()
print(count_result)

如果需要动态修改跳数n,可以用字符串格式化生成查询:

n = 2
cypher_query = f"""
MATCH (n)-[{n}]->(c)
RETURN Count()
"""

方法二:使用GQLAlchemy ORM API构建查询

通过ORM方式构建查询,更贴合Python代码风格:

首先定义通用节点模型(如果已有自定义节点类,可直接使用):

from gqlalchemy import Node, Relationship, Database, select, count

class GenericNode(Node):
    __abstract__ = True
    pass

然后构建2跳遍历的查询并执行:

db = Database("bolt://neo4j:your_password@localhost:7687")

# 构建2跳路径条件:任意节点经过2跳关系连接到另一节点
path = GenericNode.__node__ - (Relationship(type_="*2")) -> GenericNode.__node__

# 执行计数查询
query = select(count()).where(path)
result = db.execute(query)
count_result = result.scalar()
print(count_result)

若要实现动态n跳,只需修改Relationship的type_参数:

n = 2
path = GenericNode.__node__ - (Relationship(type_=f"*{n}")) -> GenericNode.__node__

内容的提问来源于stack exchange,提问作者KWriter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 10:55:26