1 回答

TA貢獻1839條經驗 獲得超15個贊
從 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使用go mod init example.com/hello命令創建一個文件。我之前提到過 Bolt 驅動器。您需要添加它go get github.com/neo4j/neo4j-go-driver/[email protected]。你可以運行你的程序go run .\program.go。
- 1 回答
- 0 關注
- 92 瀏覽
添加回答
舉報