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

能否通过多种驱动访问Memgraph?含Python、JavaScript连接需求

连接Memgraph Platform 2.6.0实例的多种方式

Memgraph兼容Neo4j的Bolt协议,所以除了你正在用的GQLAlchemy,还可以通过多种兼容Bolt的驱动或官方驱动连接。以下是Python和JavaScript的具体实现方式:

Python 连接方式

1. GQLAlchemy(当前使用的工具)

直接通过GQLAlchemy的Memgraph类连接,适配Docker默认配置:

from gqlalchemy import Memgraph

# 连接本地Docker运行的Memgraph实例
memgraph = Memgraph(host="localhost", port=7687)

# 执行测试查询
result = memgraph.execute_and_fetch("MATCH (n) RETURN count(n) AS count")
for record in result:
    print(f"节点总数: {record['count']}")

2. Neo4j Python 驱动

利用Bolt协议兼容性,使用Neo4j官方Python驱动连接:

  • 先安装依赖:pip install neo4j
  • 连接代码:
from neo4j import GraphDatabase

# 初始化驱动
driver = GraphDatabase.driver("bolt://localhost:7687")

# 会话内执行查询
with driver.session() as session:
    result = session.run("MATCH (n) RETURN count(n) AS count")
    print(f"节点总数: {result.single()['count']}")

# 关闭驱动连接
driver.close()

3. PyMemgraph(Memgraph官方Python驱动)

官方维护的轻量驱动,更适配Memgraph特性:

  • 安装依赖:pip install pymemgraph
  • 连接代码:
from pymemgraph import Memgraph

memgraph = Memgraph(host="localhost", port=7687)

# 执行查询并获取结果
result = memgraph.execute("MATCH (n) RETURN count(n) AS count")
print(f"节点总数: {result[0]['count']}")

JavaScript 连接方式

1. Neo4j JavaScript 驱动

同样基于Bolt协议,适用于Node.js环境:

  • 安装依赖:npm install neo4j-driver
  • 连接代码:
const neo4j = require('neo4j-driver');

// 初始化驱动(Memgraph默认无需账号密码)
const driver = neo4j.driver('bolt://localhost:7687', neo4j.auth.basic('', ''));

async function runQuery() {
    const session = driver.session();
    try {
        const result = await session.run('MATCH (n) RETURN count(n) AS count');
        console.log(`节点总数: ${result.records[0].get('count')}`);
    } finally {
        await session.close();
    }
    await driver.close();
}

runQuery();

2. Memgraph官方JavaScript驱动

官方提供的专属驱动,更贴合Memgraph功能:

  • 安装依赖:npm install memgraph-driver
  • 连接代码:
const { Memgraph } = require('memgraph-driver');

async function connectAndQuery() {
    const memgraph = new Memgraph('bolt://localhost:7687');
    const result = await memgraph.execute('MATCH (n) RETURN count(n) AS count');
    console.log(`节点总数: ${result[0].count}`);
    await memgraph.close();
}

connectAndQuery();

注意:如果你的Docker容器不是绑定本地端口7687,需要替换为实际映射的端口;若设置了账号密码,需在驱动初始化时添加对应认证参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:21:35