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

如何通过Python连接Memgraph Cloud?

如何用Python连接Memgraph Cloud

方法1:使用官方mgclient客户端(推荐)

Memgraph官方提供了Python绑定的客户端mgclient,专门用于连接Memgraph实例,步骤如下:

  1. 安装依赖包
    打开终端执行:
pip install mgclient
  1. 准备连接信息
    从Memgraph Cloud控制台获取以下信息:
  • 主机地址(比如memgraph-cloud-host.example.com)
  • Bolt端口(通常是7687)
  • 用户名(默认是memgraph)
  • 密码(实例创建时设置的)
  1. 编写连接代码
    Memgraph Cloud要求加密连接,需启用SSL配置:
import mgclient

# 替换成你的Memgraph Cloud连接信息
host = "你的主机地址"
port = 7687
username = "memgraph"
password = "你的密码"

# 建立加密连接
connection = mgclient.connect(
    host=host,
    port=port,
    username=username,
    password=password,
    sslmode=mgclient.SSLMODE_REQUIRED
)

# 测试连接:执行简单查询
cursor = connection.cursor()
cursor.execute("MATCH (n) RETURN count(n) AS node_count")
result = cursor.fetchone()
print(f"当前图中节点数量: {result['node_count']}")

# 关闭连接
connection.close()

方法2:使用Neo4j Python驱动(兼容Bolt协议)

Memgraph兼容Neo4j的Bolt协议,适合熟悉Neo4j生态的开发者:

  1. 安装依赖包
pip install neo4j
  1. 编写连接代码
    同样需启用SSL:
from neo4j import GraphDatabase

# 替换成你的连接信息,注意Bolt URI格式
uri = "bolt+s://你的主机地址:7687"
auth = ("memgraph", "你的密码")

driver = GraphDatabase.driver(uri, auth=auth)

# 测试连接
with driver.session() as session:
    result = session.run("MATCH (n) RETURN count(n) AS node_count")
    record = result.single()
    print(f"当前图中节点数量: {record['node_count']}")

driver.close()

常见注意事项

  • 确保网络能访问Memgraph Cloud的7687端口,防火墙需开放对应端口。
  • 不要硬编码密码,建议用环境变量管理敏感信息,比如:
    import os
    password = os.getenv("MEMGRAPH_PASSWORD")
    
  • 若遇到SSL证书验证问题,生产环境不建议直接关闭SSL,可指定CA证书路径;测试环境可临时添加ssl=False参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:31:11