Skip to content

Instantly share code, notes, and snippets.

@ali-ince
Created April 9, 2019 09:08
Show Gist options
  • Save ali-ince/558d3c2a300d803ffc0bfdcbf166f3ff to your computer and use it in GitHub Desktop.
Save ali-ince/558d3c2a300d803ffc0bfdcbf166f3ff to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/fatih/structs"
"github.com/neo4j/neo4j-go-driver/neo4j"
)
type User struct {
Id int
Name string
DateOfBirth time.Time
}
var uri = "bolt://localhost:7687"
var username = "neo4j"
var password = "password"
var query = "UNWIND $list AS item CREATE (u:User) SET u = item RETURN u.Id"
func mapUsers(users []User) []map[string]interface{} {
var result = make([]map[string]interface{}, len(users))
for index, item := range users {
result[index] = structs.Map(item)
}
return result
}
func run() error {
var (
driver neo4j.Driver
session neo4j.Session
tx neo4j.Transaction
result neo4j.Result
err error
)
var users = []User{
User{1, "name 1", time.Date(1990, time.November, 10, 0, 0, 0, 0, time.UTC)},
User{2, "name 2", time.Date(1975, time.June, 10, 0, 0, 0, 0, time.UTC)},
User{3, "name 3", time.Date(1957, time.March, 10, 0, 0, 0, 0, time.UTC)},
User{4, "name 4", time.Date(1999, time.July, 10, 0, 0, 0, 0, time.UTC)},
User{5, "name 5", time.Date(2002, time.May, 10, 0, 0, 0, 0, time.UTC)},
User{6, "name 6", time.Date(1985, time.February, 10, 0, 0, 0, 0, time.UTC)},
User{7, "name 7", time.Date(2010, time.January, 10, 0, 0, 0, 0, time.UTC)},
}
useConsoleLogger := func() func(config *neo4j.Config) {
return func(config *neo4j.Config) {
config.Log = neo4j.ConsoleLogger(neo4j.ERROR)
}
}
// Construct a new driver
if driver, err = neo4j.NewDriver(uri, neo4j.BasicAuth(username, password, ""), useConsoleLogger()); err != nil {
return err
}
defer driver.Close()
// Acquire a session
if session, err = driver.Session(neo4j.AccessModeRead); err != nil {
return err
}
defer session.Close()
if tx, err = session.BeginTransaction(); err != nil {
return err
}
defer tx.Close()
if result, err = tx.Run(query, map[string]interface{}{"list": mapUsers(users)}); err != nil {
return err
}
for result.Next() {
fmt.Println(result.Record().GetByIndex(0))
}
if err = result.Err(); err != nil {
return err
}
return tx.Commit()
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
os.Exit(1)
}
os.Exit(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment