redisgraph

package module
v0.0.0-...-f68e26f Latest Latest
Warning

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

Go to latest
Published: May 21, 2023 License: BSD-3-Clause Imports: 8 Imported by: 0

README

license CircleCI GitHub issues Codecov Go Report Card GoDoc

redisgraph-go

Forum Discord

redisgraph-go is a Golang client for the RedisGraph module. It relies on redigo for Redis connection management and provides support for RedisGraph's QUERY, EXPLAIN, and DELETE commands.

Installation

Simply do:

$ go get github.com/amer/redisgraph-go

Usage

The complete redisgraph-go API is documented on GoDoc.

package main

import (
	"fmt"
	"os"

	"github.com/gomodule/redigo/redis"
	rg "github.com/redislabs/redisgraph-go"
)

func main() {
	conn, _ := redis.Dial("tcp", "127.0.0.1:6379")
	defer conn.Close()

	graph := rg.GraphNew("social", conn)

	graph.Delete()

	john := rg.Node{
		Label: "person",
		Properties: map[string]interface{}{
			"name":   "John Doe",
			"age":    33,
			"gender": "male",
			"status": "single",
		},
	}
	graph.AddNode(&john)

	japan := rg.Node{
		Label: "country",
		Properties: map[string]interface{}{
			"name": "Japan",
		},
	}
	graph.AddNode(&japan)

	edge := rg.Edge{
		Source:      &john,
		Relation:    "visited",
		Destination: &japan,
	}
	graph.AddEdge(&edge)

	graph.Commit()

	query := `MATCH (p:person)-[v:visited]->(c:country)
           RETURN p.name, p.age, c.name`

	// result is a QueryResult struct containing the query's generated records and statistics.
	result, _ := graph.Query(query)

	// Pretty-print the full result set as a table.
	result.PrettyPrint()

	// Iterate over each individual Record in the result.
	fmt.Println("Visited countries by person:")
	for result.Next() { // Next returns true until the iterator is depleted.
		// Get the current Record.
		r := result.Record()

		// Entries in the Record can be accessed by index or key.
		pName := r.GetByIndex(0)
		fmt.Printf("\nName: %s\n", pName)
		pAge, _ := r.Get("p.age")
		fmt.Printf("\nAge: %d\n", pAge)
	}

	// Path matching example.
	query = "MATCH p = (:person)-[:visited]->(:country) RETURN p"
	result, err := graph.Query(query)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println("Pathes of persons visiting countries:")
	for result.Next() {
		r := result.Record()
		p, ok := r.GetByIndex(0).(rg.Path)
		fmt.Printf("%s %v\n", p, ok)
	}
}

Running the above produces the output:

+----------+-------+--------+
|  p.name  | p.age | c.name |
+----------+-------+--------+
| John Doe |    33 | Japan  |
+----------+-------+--------+

Query internal execution time 1.623063

Name: John Doe

Age: 33

Running queries with timeouts

Queries can be run with a millisecond-level timeout as described in the module documentation. To take advantage of this feature, the QueryOptions struct should be used:

options := NewQueryOptions().SetTimeout(10) // 10-millisecond timeout
res, err := graph.QueryWithOptions("MATCH (src {name: 'John Doe'})-[*]->(dest) RETURN dest", options)

ParameterizedQueryWithOptions and ROQueryWithOptions endpoints are also exposed by the client.

Running tests

A simple test suite is provided, and can be run with:

$ go test

The tests expect a Redis server with the RedisGraph module loaded to be available at localhost:6379

License

redisgraph-go is distributed under the BSD3 license - see LICENSE

Documentation

Index

Examples

Constants

View Source
const (
	LABELS_ADDED            string = "Labels added"
	NODES_CREATED           string = "Nodes created"
	NODES_DELETED           string = "Nodes deleted"
	RELATIONSHIPS_DELETED   string = "Relationships deleted"
	PROPERTIES_SET          string = "Properties set"
	RELATIONSHIPS_CREATED   string = "Relationships created"
	INDICES_CREATED         string = "Indices created"
	INDICES_DELETED         string = "Indices deleted"
	INTERNAL_EXECUTION_TIME string = "Query internal execution time"
	CACHED_EXECUTION        string = "Cached execution"
)

Variables

This section is empty.

Functions

func BuildParamsHeader

func BuildParamsHeader(params map[string]interface{}) string

func ToString

func ToString(i interface{}) string

Types

type Edge

type Edge struct {
	ID          uint64
	Relation    string
	Source      *Node
	Destination *Node
	Properties  map[string]interface{}
	// contains filtered or unexported fields
}

Edge represents an edge connecting two nodes in the graph.

func EdgeNew

func EdgeNew(relation string, srcNode *Node, destNode *Node, properties map[string]interface{}) *Edge

EdgeNew create a new Edge

func (Edge) DestNodeID

func (e Edge) DestNodeID() uint64

DestNodeID returns edge destination node ID

func (Edge) Encode

func (e Edge) Encode() string

Encode makes Edge satisfy the Stringer interface

func (*Edge) GetProperty

func (e *Edge) GetProperty(key string) interface{}

GetProperty retrieves property from edge

func (*Edge) SetProperty

func (e *Edge) SetProperty(key string, value interface{})

SetProperty assign a new property to edge

func (Edge) SourceNodeID

func (e Edge) SourceNodeID() uint64

SourceNodeID returns edge source node ID

func (Edge) String

func (e Edge) String() string

Returns a string representation of edge

type Graph

type Graph struct {
	Id    string
	Nodes map[string]*Node
	Edges []*Edge
	Conn  redis.Conn
	// contains filtered or unexported fields
}

Graph represents a graph, which is a collection of nodes and edges.

func GraphNew

func GraphNew(Id string, conn redis.Conn) Graph

New creates a new graph.

Example
conn, _ := redis.Dial("tcp", "localhost:6380")

graph := redisgraph.GraphNew("social", conn)

q := "CREATE (w:WorkPlace {name:'RedisLabs'}) RETURN w"
res, _ := graph.Query(q)

res.Next()
r := res.Record()
w := r.GetByIndex(0).(*redisgraph.Node)
fmt.Println(w.Label)
Output:

WorkPlace
Example (Pool)
host := "localhost:6380"
pool := &redis.Pool{Dial: func() (redis.Conn, error) {
	return redis.Dial("tcp", host)
}}

graph := redisgraph.GraphNew("social", pool.Get())

q := "CREATE (w:WorkPlace {name:'RedisLabs'}) RETURN w"
res, _ := graph.Query(q)

res.Next()
r := res.Record()
w := r.GetByIndex(0).(*redisgraph.Node)
fmt.Println(w.Label)
Output:

WorkPlace
Example (Tls)
// Consider the following helper methods that provide us with the connection details (host and password)
// and the paths for:
//     tls_cert - A a X.509 certificate to use for authenticating the  server to connected clients, masters or cluster peers. The file should be PEM formatted
//     tls_key - A a X.509 private key to use for authenticating the  server to connected clients, masters or cluster peers. The file should be PEM formatted
//	   tls_cacert - A PEM encoded CA's certificate file
host, password := getConnectionDetails()
tlsready, tls_cert, tls_key, tls_cacert := getTLSdetails()

// Skip if we dont have all files to properly connect
if tlsready == false {
	return
}

// Load client cert
cert, err := tls.LoadX509KeyPair(tls_cert, tls_key)
if err != nil {
	log.Fatal(err)
}

// Load CA cert
caCert, err := ioutil.ReadFile(tls_cacert)
if err != nil {
	log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)

clientTLSConfig := &tls.Config{
	Certificates: []tls.Certificate{cert},
	RootCAs:      caCertPool,
}

// InsecureSkipVerify controls whether a client verifies the
// server's certificate chain and host name.
// If InsecureSkipVerify is true, TLS accepts any certificate
// presented by the server and any host name in that certificate.
// In this mode, TLS is susceptible to man-in-the-middle attacks.
// This should be used only for testing.
clientTLSConfig.InsecureSkipVerify = true

pool := &redis.Pool{Dial: func() (redis.Conn, error) {
	return redis.Dial("tcp", host,
		redis.DialPassword(password),
		redis.DialTLSConfig(clientTLSConfig),
		redis.DialUseTLS(true),
		redis.DialTLSSkipVerify(true),
	)
}}

graph := redisgraph.GraphNew("social", pool.Get())

q := "CREATE (w:WorkPlace {name:'RedisLabs'}) RETURN w"
res, _ := graph.Query(q)

res.Next()
r := res.Record()
w := r.GetByIndex(0).(*redisgraph.Node)
fmt.Println(w.Label)
Output:

func (*Graph) AddEdge

func (g *Graph) AddEdge(e *Edge) error

AddEdge adds an edge to the graph.

func (*Graph) AddNode

func (g *Graph) AddNode(n *Node)

AddNode adds a node to the graph.

func (*Graph) CallProcedure

func (g *Graph) CallProcedure(procedure string, yield []string, args ...interface{}) (*QueryResult, error)

CallProcedure invokes procedure.

func (*Graph) Commit

func (g *Graph) Commit() (*QueryResult, error)

Commit creates the entire graph, but will re-add nodes if called again.

func (*Graph) Delete

func (g *Graph) Delete() error

Delete removes the graph.

func (*Graph) ExecutionPlan

func (g *Graph) ExecutionPlan(q string) (string, error)

ExecutionPlan gets the execution plan for given query.

func (*Graph) Flush

func (g *Graph) Flush() (*QueryResult, error)

Flush will create the graph and clear it

func (*Graph) Labels

func (g *Graph) Labels() []string

Labels retrieves all node labels.

func (*Graph) Merge

func (g *Graph) Merge(p string) (*QueryResult, error)

Merge pattern

func (*Graph) ParameterizedQuery

func (g *Graph) ParameterizedQuery(q string, params map[string]interface{}) (*QueryResult, error)

func (*Graph) ParameterizedQueryWithOptions

func (g *Graph) ParameterizedQueryWithOptions(q string, params map[string]interface{}, options *QueryOptions) (*QueryResult, error)

ParameterizedQueryWithOptions issues a parameterized query with the given timeout

func (*Graph) PropertyKeys

func (g *Graph) PropertyKeys() []string

PropertyKeys retrieves all properties names.

func (*Graph) Query

func (g *Graph) Query(q string) (*QueryResult, error)

Query executes a query against the graph.

func (*Graph) QueryWithOptions

func (g *Graph) QueryWithOptions(q string, options *QueryOptions) (*QueryResult, error)

QueryWithOptions issues a query with the given timeout

func (*Graph) ROQuery

func (g *Graph) ROQuery(q string) (*QueryResult, error)

ROQuery executes a read only query against the graph.

func (*Graph) ROQueryWithOptions

func (g *Graph) ROQueryWithOptions(q string, options *QueryOptions) (*QueryResult, error)

ROQueryWithOptions issues a read-only query with the given timeout

func (*Graph) RelationshipTypes

func (g *Graph) RelationshipTypes() []string

RelationshipTypes retrieves all edge relationship types.

type Node

type Node struct {
	ID         uint64
	Labels     []string
	Alias      string
	Properties map[string]interface{}
	// contains filtered or unexported fields
}

Node represents a node within a graph

func NodeNew

func NodeNew(labels []string, alias string, properties map[string]interface{}) *Node

NodeNew create a new Node

func (Node) Encode

func (n Node) Encode() string

Encode makes Node satisfy the Stringer interface

func (Node) GetProperty

func (n Node) GetProperty(key string) interface{}

GetProperty retrieves property from node

func (*Node) SetProperty

func (n *Node) SetProperty(key string, value interface{})

SetProperty asssign a new property to node

func (Node) String

func (n Node) String() string

Returns a string representation of a node

type Path

type Path struct {
	Nodes []*Node
	Edges []*Edge
}

func PathNew

func PathNew(nodes []interface{}, edges []interface{}) Path

func (Path) EdgeCount

func (p Path) EdgeCount() int

func (Path) FirstNode

func (p Path) FirstNode() *Node

func (Path) GetEdge

func (p Path) GetEdge(index int) *Edge

func (Path) GetEdges

func (p Path) GetEdges() []*Edge

func (Path) GetNode

func (p Path) GetNode(index int) *Node

func (Path) GetNodes

func (p Path) GetNodes() []*Node

func (Path) LastNode

func (p Path) LastNode() *Node

func (Path) NodesCount

func (p Path) NodesCount() int

func (Path) String

func (p Path) String() string

type QueryOptions

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

QueryOptions are a set of additional arguments to be emitted with a query.

func NewQueryOptions

func NewQueryOptions() *QueryOptions

NewQueryOptions instantiates a new QueryOptions struct.

func (*QueryOptions) GetTimeout

func (options *QueryOptions) GetTimeout() int

GetTimeout retrieves the timeout of the QueryOptions struct

func (*QueryOptions) SetTimeout

func (options *QueryOptions) SetTimeout(timeout int) *QueryOptions

SetTimeout sets the timeout member of the QueryOptions struct

type QueryResult

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

QueryResult represents the results of a query.

func QueryResultNew

func QueryResultNew(g *Graph, response interface{}) (*QueryResult, error)

func (*QueryResult) CachedExecution

func (qr *QueryResult) CachedExecution() int

func (*QueryResult) Empty

func (qr *QueryResult) Empty() bool

func (*QueryResult) IndicesCreated

func (qr *QueryResult) IndicesCreated() int

func (*QueryResult) IndicesDeleted

func (qr *QueryResult) IndicesDeleted() int

func (*QueryResult) InternalExecutionTime

func (qr *QueryResult) InternalExecutionTime() float64

Returns the query internal execution time in milliseconds

func (*QueryResult) LabelsAdded

func (qr *QueryResult) LabelsAdded() int

func (*QueryResult) Next

func (qr *QueryResult) Next() bool

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

func (*QueryResult) NodesCreated

func (qr *QueryResult) NodesCreated() int

func (*QueryResult) NodesDeleted

func (qr *QueryResult) NodesDeleted() int

func (*QueryResult) PrettyPrint

func (qr *QueryResult) PrettyPrint()

PrettyPrint prints the QueryResult to stdout, pretty-like.

func (*QueryResult) PropertiesSet

func (qr *QueryResult) PropertiesSet() int

func (*QueryResult) Record

func (qr *QueryResult) Record() *Record

Record returns the current record.

func (*QueryResult) RelationshipsCreated

func (qr *QueryResult) RelationshipsCreated() int

func (*QueryResult) RelationshipsDeleted

func (qr *QueryResult) RelationshipsDeleted() int

type QueryResultHeader

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

type Record

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

func (*Record) Get

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

func (*Record) GetByIndex

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

func (*Record) Keys

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

func (*Record) Values

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

type ResultSetColumnTypes

type ResultSetColumnTypes int
const (
	COLUMN_UNKNOWN ResultSetColumnTypes = iota
	COLUMN_SCALAR
	COLUMN_NODE
	COLUMN_RELATION
)

type ResultSetScalarTypes

type ResultSetScalarTypes int
const (
	VALUE_UNKNOWN ResultSetScalarTypes = iota
	VALUE_NULL
	VALUE_STRING
	VALUE_INTEGER
	VALUE_BOOLEAN
	VALUE_DOUBLE
	VALUE_ARRAY
	VALUE_EDGE
	VALUE_NODE
	VALUE_PATH
	VALUE_MAP
	VALUE_POINT
)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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