可以使用Go连接到Memgraph吗?

huangapple go评论83阅读模式
英文:

Can I connect to Memgraph using Go?

问题

我想从Go语言连接到正在运行的Memgraph数据库实例。我正在使用Docker,并且已经安装了Memgraph平台。我需要做什么?

英文:

I'd like to connect from Go to the running instance of the Memgraph database. I'm using Docker and I've installed the Memgraph Platform. What exactly do I need to do?

答案1

得分: 0

连接Go到Memgraph的过程非常简单。为此,您需要使用Bolt协议。以下是所需的步骤:

首先,创建一个新的应用程序目录/MyApp,并进入该目录。接下来,创建一个名为program.go的文件,其中包含以下代码:

package main

import (
    "fmt"

    "github.com/neo4j/neo4j-go-driver/v4/neo4j"
)

func main() {
    dbUri := "bolt://localhost:7687"
    driver, err := neo4j.NewDriver(dbUri, neo4j.BasicAuth("username", "password", ""))
    if err != nil {
        panic(err)
    }
    // 根据应用程序的生命周期要求处理驱动程序的生命周期,驱动程序的生命周期通常与应用程序的生命周期绑定,这通常意味着每个应用程序一个驱动程序实例
    defer driver.Close()
    item, err := insertItem(driver)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%v\n", item.Message)
}

func insertItem(driver neo4j.Driver) (*Item, error) {
    // 会话的生命周期短暂,创建成本低,并且不是线程安全的。在Web应用程序中,通常为每个请求创建一个或多个会话。确保在完成后调用会话的Close方法。
    // 对于多数据库支持,请将sessionConfig.DatabaseName设置为所请求的数据库。如果只使用读取,请将会话配置为读取模式。
    session := driver.NewSession(neo4j.SessionConfig{})
    defer session.Close()
    result, err := session.WriteTransaction(createItemFn)
    if err != nil {
        return nil, err
    }
    return result.(*Item), nil
}

func createItemFn(tx neo4j.Transaction) (interface{}, error) {
    records, err := tx.Run(
        "CREATE (a:Greeting) SET a.message = $message RETURN 'Node ' + id(a) + ': ' + a.message",
        map[string]interface{}{"message": "Hello, World!"})
    // 面对驱动程序本机错误,确保直接返回它们。根据错误,驱动程序可能会尝试重新执行函数。
    if err != nil {
        return nil, err
    }
    record, err := records.Single()
    if err != nil {
        return nil, err
    }
    // 您还可以通过名称检索值,例如`id, found := record.Get("n.id")`
    return &Item{
        Message: record.Values[0].(string),
    }, nil
}

type Item struct {
    Message string
}

现在,使用go mod init example.com/hello命令创建一个go.mod文件。我之前提到了Bolt驱动程序。您需要使用go get github.com/neo4j/neo4j-go-driver/v4@v4.3.1添加它。您可以使用go run .\program.go运行程序。

完整的文档位于Memgraph网站

英文:

The procedure for connecting fro Go to Memgraph is rather simple. For this you need to use Bolt protocol. Here are the needed steps:

First, create a new directory for your app, /MyApp, and position yourself in it. Next, create a program.go file with the following code:

package main
import (
"fmt"
"github.com/neo4j/neo4j-go-driver/v4/neo4j"
)
func main() {
dbUri := "bolt://localhost:7687"
driver, err := neo4j.NewDriver(dbUri, neo4j.BasicAuth("username", "password", ""))
if err != nil {
panic(err)
}
// Handle driver lifetime based on your application lifetime requirements  driver's lifetime is usually
// bound by the application lifetime, which usually implies one driver instance per application
defer driver.Close()
item, err := insertItem(driver)
if err != nil {
panic(err)
}
fmt.Printf("%v\n", item.Message)
}
func insertItem(driver neo4j.Driver) (*Item, error) {
// Sessions are short-lived, cheap to create and NOT thread safe. Typically create one or more sessions
// per request in your web application. Make sure to call Close on the session when done.
// For multi-database support, set sessionConfig.DatabaseName to requested database
// Session config will default to write mode, if only reads are to be used configure session for
// read mode.
session := driver.NewSession(neo4j.SessionConfig{})
defer session.Close()
result, err := session.WriteTransaction(createItemFn)
if err != nil {
return nil, err
}
return result.(*Item), nil
}
func createItemFn(tx neo4j.Transaction) (interface{}, error) {
records, err := tx.Run(
"CREATE (a:Greeting) SET a.message = $message RETURN 'Node ' + id(a) + ': ' + a.message",
map[string]interface{}{"message": "Hello, World!"})
// In face of driver native errors, make sure to return them directly.
// Depending on the error, the driver may try to execute the function again.
if err != nil {
return nil, err
}
record, err := records.Single()
if err != nil {
return nil, err
}
// You can also retrieve values by name, with e.g. `id, found := record.Get("n.id")`
return &Item{
Message: record.Values[0].(string),
}, nil
}
type Item struct {
Message string
}

Now, create a go.mod file using the go mod init example.com/hello command.
I've mentioned the Bolt driver earlier. You need to add it with go get github.com/neo4j/neo4j-go-driver/v4@v4.3.1. You can run your program with go run .\program.go.

The complete documentation is located at Memgraph site.

huangapple
  • 本文由 发表于 2022年11月15日 19:54:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/74445204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定