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

如何使用Go语言连接Docker部署的Memgraph Platform实例?

用Go连接Docker部署的Memgraph Platform操作步骤

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

先检查Docker中Memgraph容器的运行状态和端口映射情况,执行命令:

docker ps

确认输出里的Memgraph容器存在,且端口映射包含0.0.0.0:7687->7687/tcp(Memgraph默认使用Bolt协议的7687端口)。如果没有端口映射,重启容器并添加端口参数:

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

2. 安装Go语言的Memgraph兼容驱动

Memgraph兼容Neo4j的Bolt协议,直接使用Neo4j官方Go驱动即可,执行命令安装依赖:

go get github.com/neo4j/neo4j-go-driver/v5

3. 编写Go连接与测试代码

创建一个main.go文件,编写如下代码实现连接、验证和数据操作:

package main

import (
	"context"
	"fmt"
	"github.com/neo4j/neo4j-go-driver/v5/neo4j"
)

func main() {
	// 初始化驱动,本地容器用bolt://localhost:7687,默认无认证
	driver, err := neo4j.NewDriver("bolt://localhost:7687", neo4j.NoAuth())
	if err != nil {
		panic(err)
	}
	defer driver.Close(context.Background())

	// 验证连接有效性
	if err = driver.VerifyConnectivity(context.Background()); err != nil {
		panic("连接Memgraph失败: " + err.Error())
	}
	fmt.Println("已成功连接Memgraph!")

	// 创建会话执行查询
	session := driver.NewSession(context.Background(), neo4j.SessionConfig{})
	defer session.Close(context.Background())

	// 执行创建节点的测试查询
	result, err := session.Run(context.Background(), 
		"CREATE (n:GoTest {name: $name}) RETURN n.name", 
		map[string]interface{}{"name": "Memgraph连接测试"})
	if err != nil {
		panic(err)
	}

	// 处理查询结果
	for result.Next(context.Background()) {
		fmt.Printf("测试节点创建成功,节点名称: %v\n", result.Record().Values[0])
	}

	if err = result.Err(); err != nil {
		panic(err)
	}
}

4. 运行程序验证连接

在代码目录下执行命令:

go run main.go

如果控制台输出连接成功和节点创建成功的信息,说明Go程序已成功连接到Docker中的Memgraph实例。

额外注意事项

  • 如果Memgraph容器部署在远程主机,将连接地址中的localhost替换为远程主机的IP或域名。
  • 若Memgraph配置了用户名密码,将neo4j.NoAuth()替换为neo4j.BasicAuth("用户名", "密码", "")。
  • 可通过Memgraph Lab(Memgraph Platform自带的可视化工具,默认端口3000)查看数据,验证操作结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 16:25:24