Search code examples
gomemgraphdb

Can I connect to Memgraph using Go?


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?


Solution

  • 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.