登录
首页 >  Golang >  Go问答

可以用 Go语言连接到Memgraph吗?

来源:stackoverflow

时间:2024-02-29 20:27:24 355浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《可以用 Go语言连接到Memgraph吗?》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

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


正确答案


从 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)
    }
    // 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
}

现在,使用 go mod init example.com/hello 命令创建 go.mod 文件。 我之前已经提到过 bolt 驱动程序。您需要使用 go get github.com/neo4j/neo4j-go-driver/[email protected] 添加它。您可以使用 go run .\program.go 来运行您的程序。

完整文档位于 Memgraph site

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>