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

如何在Docker部署的Memgraph平台中执行GQLAlchemy脚本?

在Docker运行的Memgraph上执行GQLAlchemy脚本的步骤

1. 本地安装GQLAlchemy库

GQLAlchemy是本地运行的Python库,用于连接Memgraph,先通过pip完成安装:

pip install gqlalchemy

2. 确认Memgraph容器的端口映射

确保你的Memgraph容器已经映射了7687端口(Memgraph默认Bolt协议端口),可以用docker ps查看容器状态,确认端口列存在0.0.0.0:7687->7687/tcp类的映射记录。如果之前启动容器时未配置端口映射,需重启容器补全配置:

docker run -d -p 7687:7687 --name memgraph memgraph/memgraph

3. 编写GQLAlchemy脚本

创建一个Python脚本文件(比如命名为memgraph_operation.py),示例内容如下,实现连接Memgraph、创建节点关系及查询操作:

from gqlalchemy import Memgraph, Node

# 连接Docker中运行的Memgraph实例
db = Memgraph(host="localhost", port=7687)

# 定义节点模型
class User(Node):
    name: str
    age: int

# 创建并保存节点
alice = User(name="Alice", age=30).save(db)
bob = User(name="Bob", age=25).save(db)

# 创建节点间的关系
db.execute("MATCH (u1:User), (u2:User) WHERE u1.name = 'Alice' AND u2.name = 'Bob' CREATE (u1)-[:FRIENDS_WITH]->(u2)")

# 查询并打印结果
query_result = db.execute("MATCH (u:User) RETURN u.name, u.age")
for row in query_result:
    print(f"用户名: {row['u.name']}, 年龄: {row['u.age']}")

4. 运行脚本

在终端中执行编写好的脚本:

python memgraph_operation.py

5. 验证执行结果

可以通过两种方式确认操作结果:

  • 若安装了Memgraph Lab,直接连接bolt://localhost:7687,执行Cypher查询查看数据;
  • 进入Memgraph容器的命令行客户端:
docker exec -it memgraph mgconsole

在mgconsole中执行查询语句验证:

MATCH (u:User)-[r:FRIENDS_WITH]->(v:User) RETURN u.name, v.name, type(r);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:50:38