neo4j

package module
v1.7.0-alpha2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 20, 2018 License: Apache-2.0 Imports: 14 Imported by: 0

README

neo4j-go-driver

This is the pre-release version of the official Neo4j Go Driver. It is based on our C Connector, and depends on seabolt to be available on the host system.

Requirements

This package requires the following tools/libraries to be installed in order to be built.

  1. seabolt (see requirements here)
  2. pkg-config tool for your platform
  3. working cgo environment for your platform

Building

Linux (Ubuntu)
  1. Make sure you have pkg-config installed via apt install pkg-config
  2. Clone seabolt (assume <seabolt_dir> to be the absolute path in which the clone resides) and make sure you can build it successfully (follow it's own instructions)
  3. Add/Update environment variable PKG_CONFIG_PATH to include <seabolt_dir>/build
  4. Add/Update environment variable LD_LIBRARY_PATH to include <seabolt_dir>/build/lib
  5. Get this package via go get github.com/neo4j/neo4j-go-driver
MacOS
  1. Install pkg-config via brew install pkg-config
  2. Clone seabolt (assume <seabolt_dir> to be the absolute path in which the clone resides) and make sure you can build it successfully,
  3. Add/Update environment variable PKG_CONFIG_PATH to include build subdirectory of seabolt, i.e. $PKG_CONFIG_PATH:<seabolt_dir>/build
  4. Add/Update environment variable LD_LIBRARY_PATH to include <seabolt_dir>/build/lib
  5. Go Get this package via go get github.com/neo4j/neo4j-go-driver
Windows
  1. Install a mingw toolchain (for instance MSYS2 from https://www.msys2.org/) for cgo support (seabolt include some instructions),
  2. Clone seabolt (assume <seabolt_dir> to be the absolute path in which the clone resides) and make sure you can build it successfully,
  3. Add/Update environment variable PKG_CONFIG_PATH to include build subdirectory of seabolt, i.e. %PKG_CONFIG_PATH%;<seabolt_dir>/build
  4. Update environment variable PATH to include <seabolt_dir>/build/bin
  5. Go Get this package via go get github.com/neo4j/neo4j-go-driver

Versioning

Although master branch contains the source code for the latest available release, we are also tagging releases after semantic versioning scheme so that dep will find latest release and add the driver as a dependency on your project.

Getting the Driver

Add the driver as a dependency with dep.

dep ensure -add github.com/neo4j/neo4j-go-driver

Minimum Viable Snippet

Connect, execute a statement and handle results

var (
	driver neo4j.Driver
	session *neo4j.Session
	result *neo4j.Result
	err error
)

if driver, err = neo4j.NewDriver("bolt://localhost:7687", neo4j.BasicAuth("username", "password", "")); err != nil {
	return err // handle error
}
// 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()

if session, err = driver.Session(neo4j.AccessModeWrite); err != nil {
	return err
}
defer session.Close() 

result, err = session.Run("CREATE (n:Item { id: $id, name: $name }) RETURN n.id, n.name", &map[string]interface{}{
	"id": 1,
	"name": "Item 1",
})
if err != nil {
	return err // handle error
}

for result.Next() {
	fmt.Printf("Created Item with Id = '%d' and Name = '%s'\n", result.Record().GetByIndex(0).(int64), result.Record().GetByIndex(1).(string))
}
if err = result.Err(); err != nil {
	return err // handle error
}

There are a few points that need to be highlighted:

  • Each Driver instance maintains a pool of connections inside, as a result, it is recommended to only use one driver per application.
  • It is considerably cheap to create new sessions and transactions, as sessions and transactions do not create new connections as long as there are free connections available in the connection pool.
  • The driver is thread-safe, while the session or the transaction is not thread-safe.
Parsing Result Values
Record Stream

A cypher execution result is comprised of a stream of records followed by a result summary. The records inside the result can be accessed via Next()/Record() functions defined on Result. It is important to check Err() after Next() returning false to find out whether it is end of result stream or an error that caused the end of result consumption.

Accessing Values in a Record

Values in a Record can be accessed either by index or by alias. The return value is an interface{} which means you need to convert the interface to the type expected

value := record.GetByIndex(0)
if value, ok := record.Get('field_name'); ok {
	// a value with alias field_name was found
	// process value
}
Value Types

The driver currently exposes values in the record as an interface{} type. The underlying types of the returned values depend on the corresponding Cypher types.

The mapping between Cypher types and the types used by this driver (to represent the Cypher type):

Cypher Type Driver Type
null null
List []interface{}
Map map[string]interface{}
Boolean bool
Integer int64
Float float
String string
ByteArray []byte
Node Node
Relationship Relationship
Path not supported yet

Documentation

Index

Constants

View Source
const (
	// ERROR is the level that error messages are written
	ERROR LogLevel = 1
	// WARNING is the level that warning messages are written
	WARNING = 2
	// INFO is the level that info messages are written
	INFO = 3
	// DEBUG is the level that debug messages are written
	DEBUG = 4
)
View Source
const (
	// StatementTypeUnknown identifies an unknown statement type
	StatementTypeUnknown StatementType = 0
	// StatementTypeReadOnly identifies a read-only statement
	StatementTypeReadOnly = 1
	// StatementTypeReadWrite identifies a read-write statement
	StatementTypeReadWrite = 2
	// StatementTypeWriteOnly identifies a write-only statement
	StatementTypeWriteOnly = 3
	// StatementTypeSchemaWrite identifies a schema-write statement
	StatementTypeSchemaWrite = 4
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AccessMode

type AccessMode int

AccessMode defines modes that routing driver decides to which cluster member a connection should be opened.

const (
	// AccessModeWrite tells the driver to use a connection to 'Leader'
	AccessModeWrite AccessMode = 0
	// AccessModeRead tells the driver to use a connection to one of the 'Follower' or 'Read Replica'.
	AccessModeRead = 1
)

type AuthToken

type AuthToken struct {
	// contains filtered or unexported fields
}

AuthToken contains credentials to be sent over to the neo4j server.

func BasicAuth

func BasicAuth(username string, password string, realm string) AuthToken

BasicAuth generates a basic authentication token with provided username and password

func CustomAuth

func CustomAuth(scheme string, username string, password string, realm string, parameters *map[string]interface{}) AuthToken

CustomAuth generates a custom authentication token with provided parameters

func KerberosAuth

func KerberosAuth(ticket string) AuthToken

KerberosAuth generates a kerberos authentication token with provided base-64 encoded kerberos ticket

func NoAuth

func NoAuth() AuthToken

NoAuth generates an empty authentication token

type Config

type Config struct {
	// Whether to turn on/off TLS encryption (default: true)
	Encrypted bool
	// Logging target the driver will send its log outputs
	Log Logging
	// Maximum amount of duration a retriable operation would continue retrying
	MaxTransactionRetryDuration time.Duration
	// Maximum number of connections per URL to allow on this driver
	MaxConnectionPoolSize int
}

A Config contains options that can be used to customize certain aspects of the driver

type Counters

type Counters struct {
	// contains filtered or unexported fields
}

Counters contains statistics about the changes made to the database made as part of the statement execution.

func (*Counters) ConstraintsAdded

func (counters *Counters) ConstraintsAdded() int

func (*Counters) ConstraintsRemoved

func (counters *Counters) ConstraintsRemoved() int

func (*Counters) IndexesAdded

func (counters *Counters) IndexesAdded() int

func (*Counters) IndexesRemoved

func (counters *Counters) IndexesRemoved() int

func (*Counters) LabelsAdded

func (counters *Counters) LabelsAdded() int

func (*Counters) LabelsRemoved

func (counters *Counters) LabelsRemoved() int

func (*Counters) NodesCreated

func (counters *Counters) NodesCreated() int

func (*Counters) NodesDeleted

func (counters *Counters) NodesDeleted() int

func (*Counters) PropertiesSet

func (counters *Counters) PropertiesSet() int

func (*Counters) RelationshipsCreated

func (counters *Counters) RelationshipsCreated() int

func (*Counters) RelationshipsDeleted

func (counters *Counters) RelationshipsDeleted() int

type Driver

type Driver interface {
	// The url this driver is bootstrapped
	Target() url.URL
	Session(accessMode AccessMode, bookmarks ...string) (*Session, error)
	// Close the driver and all underlying connections
	Close() error
	// contains filtered or unexported methods
}

Driver represents a pool(s) of connections to a neo4j server or cluster. It's safe for concurrent use.

func NewDriver

func NewDriver(target string, auth AuthToken, configurers ...func(*Config)) (Driver, error)

NewDriver is the entry method to the neo4j driver to create an instance of a Driver

type InputPosition

type InputPosition struct {
	// contains filtered or unexported fields
}

InputPosition contains information about a specific position in a statement

func (*InputPosition) Column

func (pos *InputPosition) Column() int

func (*InputPosition) Line

func (pos *InputPosition) Line() int

func (*InputPosition) Offset

func (pos *InputPosition) Offset() int

type LogLevel

type LogLevel int

LogLevel is the type that default logging implementations use for available log levels

type Logging

type Logging interface {
	ErrorEnabled() bool
	WarningEnabled() bool
	InfoEnabled() bool
	DebugEnabled() bool

	Errorf(message string, args ...interface{})
	Warningf(message string, args ...interface{})
	Infof(message string, args ...interface{})
	Debugf(message string, args ...interface{})
}

Logging is the interface that any provided logging target must satisfy for the neo4j driver to send its logging messages

func ConsoleLogger

func ConsoleLogger(level LogLevel) Logging

ConsoleLogger returns a simple logger that writes its messages to the console

func NoOpLogger

func NoOpLogger() Logging

NoOpLogger returns a logger that doesn't generate any output at all

type Node

type Node interface {
	Id() int64
	Labels() []string
	Props() map[string]interface{}
}

Node represents a node in the neo4j graph database

type Notification

type Notification struct {
	// contains filtered or unexported fields
}

Notification contains information about notifications generated by the server

func (*Notification) Code

func (notification *Notification) Code() string

func (*Notification) Description

func (notification *Notification) Description() string

func (*Notification) Position

func (notification *Notification) Position() *InputPosition

func (*Notification) Severity

func (notification *Notification) Severity() string

func (*Notification) Title

func (notification *Notification) Title() string

type Plan

type Plan struct {
	// contains filtered or unexported fields
}

Plan describes the plan that the database planner produced

func (*Plan) Arguments

func (plan *Plan) Arguments() map[string]interface{}

func (*Plan) Children

func (plan *Plan) Children() []Plan

func (*Plan) Identifiers

func (plan *Plan) Identifiers() []string

func (*Plan) Operator

func (plan *Plan) Operator() string

type ProfiledPlan

type ProfiledPlan struct {
	// contains filtered or unexported fields
}

Profile describes the plan that the database planner produced and executed

func (*ProfiledPlan) Arguments

func (plan *ProfiledPlan) Arguments() map[string]interface{}

func (*ProfiledPlan) Children

func (plan *ProfiledPlan) Children() []ProfiledPlan

func (*ProfiledPlan) DbHits

func (plan *ProfiledPlan) DbHits() int64

func (*ProfiledPlan) Identifiers

func (plan *ProfiledPlan) Identifiers() []string

func (*ProfiledPlan) Operator

func (plan *ProfiledPlan) Operator() string

func (*ProfiledPlan) Records

func (plan *ProfiledPlan) Records() int64

type Record

type Record struct {
	// contains filtered or unexported fields
}

Record contains ordered keys and values that are returned from a statement executed on the server

func (*Record) Get

func (record *Record) Get(key string) (interface{}, bool)

Get returns the value (if any) corresponding to the given key

func (*Record) GetByIndex

func (record *Record) GetByIndex(index int) interface{}

GetByIndex returns the value at given index

func (*Record) Keys

func (record *Record) Keys() []string

Keys returns the keys available

func (*Record) Values

func (record *Record) Values() []interface{}

Values returns the values

type Relationship

type Relationship interface {
	Id() int64
	StartId() int64
	EndId() int64
	Type() string
	Props() map[string]interface{}
}

Relationship represents a relationship in the neo4j graph database

type Result

type Result struct {
	// contains filtered or unexported fields
}

Result provides access to the result of the executing statement

func (*Result) Consume

func (result *Result) Consume() (*ResultSummary, error)

Consume consumes the entire result and returns the summary information about the statement execution

func (*Result) Err

func (result *Result) Err() error

Err returns the latest error that caused this Next to return false

func (*Result) Keys

func (result *Result) Keys() ([]string, error)

Keys returns the keys available on the result set

func (*Result) Next

func (result *Result) Next() bool

Next returns true only if there is a record to be processed

func (*Result) Record

func (result *Result) Record() *Record

Record returns the current record

func (*Result) Summary

func (result *Result) Summary() (*ResultSummary, error)

Summary returns the summary information about the statement execution

type ResultSummary

type ResultSummary struct {
	// contains filtered or unexported fields
}

ResultSummary contains information about statement execution.

func (*ResultSummary) Counters

func (summary *ResultSummary) Counters() *Counters

func (*ResultSummary) Notifications

func (summary *ResultSummary) Notifications() []Notification

func (*ResultSummary) Plan

func (summary *ResultSummary) Plan() *Plan

func (*ResultSummary) Profile

func (summary *ResultSummary) Profile() *ProfiledPlan

func (*ResultSummary) ResultAvailableAfter

func (summary *ResultSummary) ResultAvailableAfter() time.Duration

func (*ResultSummary) ResultConsumedAfter

func (summary *ResultSummary) ResultConsumedAfter() time.Duration

func (*ResultSummary) Server

func (summary *ResultSummary) Server() *ServerInfo

func (*ResultSummary) Statement

func (summary *ResultSummary) Statement() *Statement

func (*ResultSummary) StatementType

func (summary *ResultSummary) StatementType() StatementType

type ServerInfo

type ServerInfo struct {
	// contains filtered or unexported fields
}

ServerInfo contains basic information of the server

func (*ServerInfo) Address

func (server *ServerInfo) Address() string

func (*ServerInfo) Version

func (server *ServerInfo) Version() string

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session represents a logical connection (which is not tied to a physical connection) to the server

func (*Session) BeginTransaction

func (session *Session) BeginTransaction() (*Transaction, error)

BeginTransaction starts a new explicit transaction on this session

func (*Session) Close

func (session *Session) Close() error

Close closes any open resources and marks this session as unusable

func (*Session) LastBookmark

func (session *Session) LastBookmark() string

func (*Session) ReadTransaction

func (session *Session) ReadTransaction(work TransactionWork) (interface{}, error)

ReadTransaction executes the given unit of work in a AccessModeRead transaction with retry logic in place

func (*Session) Run

func (session *Session) Run(cypher string, params *map[string]interface{}) (*Result, error)

Run executes an auto-commit statement and returns a result

func (*Session) WriteTransaction

func (session *Session) WriteTransaction(work TransactionWork) (interface{}, error)

WriteTransaction executes the given unit of work in a AccessModeWrite transaction with retry logic in place

type Statement

type Statement struct {
	// contains filtered or unexported fields
}

Statement represents a statement along with its parameters (if any)

func (*Statement) Cypher

func (statement *Statement) Cypher() string

func (*Statement) Params

func (statement *Statement) Params() *map[string]interface{}

type StatementType

type StatementType int

StatementType defines the type of the statement

type Transaction

type Transaction struct {
	// contains filtered or unexported fields
}

Transaction represents a transaction in the Neo4j database

func (*Transaction) Close

func (transaction *Transaction) Close() error

Close rolls back the actual transaction if it's not already committed/rolled back and closes all resources associated with this transaction

func (*Transaction) Commit

func (transaction *Transaction) Commit() error

Commit commits the transaction

func (*Transaction) Rollback

func (transaction *Transaction) Rollback() error

Rollback rolls back the transaction

func (*Transaction) Run

func (transaction *Transaction) Run(cypher string, params *map[string]interface{}) (*Result, error)

Run executes a statement on this transaction and returns a result

type TransactionWork

type TransactionWork func(transaction *Transaction) (interface{}, error)

TransactionWork represents a unit of work that will be executed against the provided transaction

Directories

Path Synopsis
internal
mocking
Package connector-mocks is a generated GoMock package.
Package connector-mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL