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

如何使用Memgraph查询构建器执行Union操作?

使用Memgraph查询构建器执行Union操作

目前GQLAlchemy的Query Builder官方文档未直接提供Union操作的封装方法,但可以通过两种方式实现:

方法1:手动拼接Cypher UNION语句

直接编写包含UNION或UNION ALL的Cypher查询,通过Memgraph.execute()执行:

from gqlalchemy import Memgraph

# 连接Memgraph数据库
db = Memgraph()

# 定义两个需合并的查询
user_query = "MATCH (u:User) RETURN u.name AS name, u.email AS contact"
admin_query = "MATCH (a:Admin) RETURN a.name AS name, a.phone AS contact"

# 拼接UNION语句(UNION自动去重,UNION ALL保留重复结果)
union_query = f"{user_query} UNION {admin_query}"

# 执行并处理结果
results = db.execute(union_query)
for item in results:
    print(f"名称: {item['name']}, 联系方式: {item['contact']}")

方法2:结合Query Builder对象拼接

先通过Query Builder构建两个查询对象,提取其生成的Cypher语句后拼接UNION:

from gqlalchemy import Memgraph, Query

db = Memgraph()

# 用Query Builder构建第一个查询
user_builder = (
    Query(db)
    .match("(u:User)")
    .where("u.age > 18")  # 可添加过滤条件
    .return_("u.name AS name", "u.email AS contact")
)

# 构建第二个查询
admin_builder = (
    Query(db)
    .match("(a:Admin)")
    .where("a.status = 'active'")
    .return_("a.name AS name", "a.phone AS contact")
)

# 拼接UNION并执行
union_query = f"{user_builder.build()} UNION ALL {admin_builder.build()}"
results = db.execute(union_query)
for res in results:
    print(res)

关键注意事项

  • 两个查询返回的列名和数量必须完全一致,否则会触发Cypher语法错误
  • UNION会自动去除重复结果,UNION ALL会保留所有结果,根据业务需求选择
  • 如需对合并后的结果排序,可在拼接后的语句末尾添加ORDER BY子句

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:07:10