Go 驱动程序

本节介绍 Neo4j 1.8 Go 驱动程序和 4.x Go 驱动程序之间的重大更改。

Neo4j 的最新版 Go 驱动程序可在 Go 驱动程序的官方页面 上找到。

  • 所有导入语句都需要更改为 "github.com/neo4j/neo4j-go-driver/v4/neo4j"

  • NewSession 不再返回错误。

  • Result 现在公开了 Single 方法,该方法输出查询返回的唯一记录。

  • Record 现在直接公开了 KeysValues

示例 1. 1.8 Go 驱动程序和 4.x Go 驱动程序之间更改的示例
4.x Go 驱动程序的示例代码 1.8 Go 驱动程序的示例代码
package main
import (
	"fmt"
	"github.com/neo4j/neo4j-go-driver/v4/neo4j"
)
func main() {
    // [...]
	session := driver.NewSession(neo4j.SessionConfig{
		AccessMode:   neo4j.AccessModeWrite,
		Bookmarks:    []string{bookmark},
		DatabaseName: "neo4j",
	})
	defer session.Close()
	transaction, err := session.BeginTransaction()
	handleError(err)
	defer transaction.Close()
	result, err := transaction.Run(
		`CREATE (a:Greeting) SET a.message = $message RETURN a.message + ", from node " + id(a)`,
		map[string]interface{}{
			"message": "helloWorld",
		},
	)
	record, err := result.Single()
	handleError(err)
	greeting := record.Values[0]
	fmt.Println(greeting)
	handleError(transaction.Commit())
}
package main
import (
	"fmt"
	"github.com/neo4j/neo4j-go-driver/neo4j"
)
func main() {
    // [...]
	session, err := driver.NewSession(neo4j.SessionConfig{
		AccessMode:   neo4j.AccessModeWrite,
		Bookmarks:    []string{bookmark},
		DatabaseName: "neo4j",
	})
	handleError(err)
	defer session.Close()
	transaction, err := session.BeginTransaction()
	handleError(err)
	defer transaction.Close()
	result, err := transaction.Run(
		`CREATE (a:Greeting) SET a.message = $message RETURN a.message + ", from node " + id(a)`,
		map[string]interface{}{
			"message": "helloWorld",
		},
	)
	record, err := single(result)
	handleError(err)
	greeting := record.Values()[0]
	fmt.Println(greeting)
	handleError(transaction.Commit())
}
func single(result neo4j.Result) (neo4j.Record, error) {
	if !result.Next() {
		return nil, fmt.Errorf("expected at least 1 result, got none")
	}
	record := result.Record()
	if result.Next() {
		return nil, fmt.Errorf("expected exactly 1 result, got at least 1 more")
	}
	return record, nil
}