### Initialize Go Module Source: https://github.com/falkordb/falkordb-go/blob/master/README.md Before installing the client, ensure your project is initialized as a Go module. ```bash go mod init github.com/my/repo ``` -------------------------------- ### Install falkordb-go Client Source: https://github.com/falkordb/falkordb-go/blob/master/README.md Install the v2 of the falkordb-go client library using go get. ```bash $ go get github.com/FalkorDB/falkordb-go/v2 ``` -------------------------------- ### Install FalkorDB Go Client Source: https://context7.com/falkordb/falkordb-go/llms.txt Use 'go get' to install the FalkorDB Go client library. ```bash go get github.com/FalkorDB/falkordb-go/v2 ``` -------------------------------- ### Connect to FalkorDB Cluster Source: https://context7.com/falkordb/falkordb-go/llms.txt Creates a FalkorDB client using Redis Cluster connection options. Allows querying a distributed FalkorDB setup. ```go db, err := falkordb.FalkorDBNewCluster(&falkordb.ConnectionClusterOption{ Addrs: []string{ "node1:6379", "node2:6379", "node3:6379", }, Password: "clusterpass", }) if err != nil { log.Fatal(err) } defer db.Conn.Close() graph := db.SelectGraph("social") _, err = graph.Query("CREATE (:Person {name: 'Alice'})", nil, nil) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Retrieve Query Execution Plan Source: https://context7.com/falkordb/falkordb-go/llms.txt Use `Graph.ExecutionPlan` to get a string representation of the query execution plan. This is useful for optimizing queries and debugging index usage. ```go graph := db.SelectGraph("social") plan, err := graph.ExecutionPlan( "MATCH (p:Person {name: 'Alice'})-[:KNOWS]->(f:Person) RETURN f.name", ) if err != nil { log.Fatal(err) } fmt.Println(plan) // Results // Project // Conditional Traverse // Node By Label Scan | (p:Person) ``` -------------------------------- ### Access Record Fields by Name and Index in Go Source: https://context7.com/falkordb/falkordb-go/llms.txt Access individual fields within a `Record` using `Get()` with a column name or `GetByIndex()` with a zero-based index. Values are returned as specific types like `*Node`, `*Edge`, or scalar types. ```go result, _ := graph.Query( "MATCH (p:Person) RETURN p.name, p.age, p.active", nil, nil, ) for result.Next() { r := result.Record() // By key name, found := r.Get("p.name") if found { fmt.Println("Name:", name.(string)) } // By index age, err := r.GetByIndex(1) if err != nil { log.Fatal(err) // falkordb.ErrRecordNoValue if out of range } fmt.Println("Age:", age.(int64)) // All keys and values fmt.Println("Keys:", r.Keys()) fmt.Println("Values:", r.Values()) } ``` -------------------------------- ### Record - Access individual result fields Source: https://context7.com/falkordb/falkordb-go/llms.txt A Record object holds a single row from a QueryResult. Fields can be accessed by their column name using Get() or by their zero-based index using GetByIndex(). ```APIDOC ## Record.Get(key string) ### Description Retrieves a field value from the record by its column name. ### Parameters - **key** (string) - Required - The name of the column to retrieve. ### Returns - `interface{}`: The value of the field. - `bool`: `true` if the key was found, `false` otherwise. ## Record.GetByIndex(index int) ### Description Retrieves a field value from the record by its zero-based index. ### Parameters - **index** (int) - Required - The index of the field to retrieve. ### Returns - `interface{}`: The value of the field. - `error`: An error if the index is out of range (e.g., `falkordb.ErrRecordNoValue`). ## Record.Keys() ### Description Returns a list of all column names (keys) in the record. ### Returns - `[]string`: A slice of strings representing the column names. ## Record.Values() ### Description Returns a list of all field values in the record. ### Returns - `[]interface{}`: A slice of interfaces representing the field values. ``` -------------------------------- ### Manage FalkorDB Server Configuration Source: https://context7.com/falkordb/falkordb-go/llms.txt Shows how to read and update FalkorDB server configuration parameters at runtime using ConfigGet and ConfigSet. Ensure you have the necessary permissions to modify server settings. ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "localhost:6379"}) // Read current timeout setting val, err := db.ConfigGet("TIMEOUT") if err != nil { log.Fatal(err) } fmt.Println("Current TIMEOUT:", val) // Update query timeout to 1000ms err = db.ConfigSet("TIMEOUT", 1000) if err != nil { log.Fatal(err) } fmt.Println("TIMEOUT updated to 1000ms") // Verify val, _ = db.ConfigGet("TIMEOUT") fmt.Println("Updated TIMEOUT:", val) ``` -------------------------------- ### Run Tests Source: https://github.com/falkordb/falkordb-go/blob/master/README.md Execute the provided test suite for the falkordb-go client. Assumes a FalkorDB server is running on localhost:6379. ```bash $ go test ``` -------------------------------- ### Basic FalkorDB Connection and Query Source: https://github.com/falkordb/falkordb-go/blob/master/README.md Connect to a FalkorDB instance, select a graph, and execute a Cypher query to create nodes and relationships. Handles query errors and pretty-prints results. ```go package main import ( "fmt" "log" "github.com/FalkorDB/falkordb-go/v2" ) func main() { db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "0.0.0.0:6379"}) // db, _ := falkordb.FalkorDBNewCluster(&falkordb.ConnectionClusterOption{Addrs: []string{"0.0.0.0:6379"}}) graph := db.SelectGraph("social") query := "CREATE (:Person {name: 'John Doe', age: 33, gender: 'male', status: 'single'})-[:VISITED]->(:Country {name: 'Japan'})" _, err := graph.Query(query, nil, nil) if err != nil { log.Fatal(err) } 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, err := graph.Query(query, nil, nil) if err != nil { log.Fatal(err) } // 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, nil, nil) if err != nil { log.Fatal(err) } fmt.Println("Pathes of persons visiting countries:") for result.Next() { r := result.Record() p, ok := r.GetByIndex(0).(falkordb.Path) fmt.Printf("%s %v\n", p, ok) } } ``` -------------------------------- ### Traverse and Inspect Graph Paths Source: https://context7.com/falkordb/falkordb-go/llms.txt Demonstrates how to query for paths in the graph and then iterate through the nodes and edges of the returned path. Use when your queries involve path patterns like MATCH p = ... ```go result, _ := graph.Query( "MATCH p = (:Person {name: 'Alice'})-[:KNOWS*1..3]->(:Person) RETURN p LIMIT 1", nil, nil, ) result.Next() r := result.Record() pIface, _ := r.GetByIndex(0) path := pIface.(falkordb.Path) fmt.Println("Nodes in path:", path.NodesCount()) fmt.Println("Edges in path:", path.EdgeCount()) fmt.Println("First node:", path.FirstNode().GetProperty("name")) fmt.Println("Last node:", path.LastNode().GetProperty("name")) fmt.Println("Path string:", path.String()) // <(0)-[0]->(1)-[1]->(2)> for i, node := range path.GetNodes() { fmt.Printf(" Node[%d]: %v\n", i, node.GetProperty("name")) } for i, edge := range path.GetEdges() { fmt.Printf(" Edge[%d]: %s\n", i, edge.Relation) } ``` -------------------------------- ### Load, List, and Delete User Defined Functions (UDFs) Source: https://context7.com/falkordb/falkordb-go/llms.txt Demonstrates the lifecycle management of JavaScript-based User Defined Functions (UDFs) in FalkorDB. This includes loading, listing, using, deleting, and flushing UDF libraries. ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "localhost:6379"}) defer db.Conn.Close() library := "MathUtils" source := ` function square(x) { return x * x; } function cube(x) { return x * x * x; } falkor.register('square', square); falkor.register('cube', cube); ` // Load the UDF library if err := db.UDFLoad(library, source); err != nil { log.Fatal("UDFLoad:", err) } // List loaded libraries udfs, err := db.UDFList() if err != nil { log.Fatal("UDFList:", err) } fmt.Printf("Loaded UDFs: %v\n", udfs) // Loaded UDFs: [[MathUtils [square cube]]] // Use a UDF in a Cypher query graph := db.SelectGraph("demo") result, err := graph.Query("RETURN MathUtils.square(7)", nil, nil) if err != nil { log.Fatal(err) } result.Next() val, _ := result.Record().GetByIndex(0) fmt.Println("7² =", val) // 7² = 49 // Remove a specific UDF library if err := db.UDFDelete(library); err != nil { log.Fatal("UDFDelete:", err) } // Or remove all UDF libraries if err := db.UDFFlush(); err != nil { log.Fatal("UDFFlush:", err) } ``` -------------------------------- ### Select a Graph Source: https://context7.com/falkordb/falkordb-go/llms.txt Returns a `*Graph` handle for a named graph. The graph is created implicitly on the first write query if it doesn't exist. No network call is made at selection time. ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "localhost:6379"}) graph := db.SelectGraph("social") fmt.Println("Working with graph:", graph.Id) // Output: Working with graph: social ``` -------------------------------- ### Connect with Mutual TLS Source: https://context7.com/falkordb/falkordb-go/llms.txt Establishes a connection with full client-certificate TLS authentication for secure production deployments. Requires client certificate, key, and CA certificate. ```go import ( "crypto/tls" "crypto/x509" "os" "github.com/FalkorDB/falkordb-go/v2" ) cert, err := tls.LoadX509KeyPair("client.crt", "client.key") if err != nil { log.Fatal(err) } caCert, err := os.ReadFile("ca.crt") if err != nil { log.Fatal(err) } caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) tlsCfg := &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: caCertPool, } db, err := falkordb.FalkorDBNew(&falkordb.ConnectionOption{ Addr: "secure-falkordb:6380", Password: "secret", TLSConfig: tlsCfg, }) if err != nil { log.Fatal(err) } defer db.Conn.Close() graph := db.SelectGraph("social") res, err := graph.Query("MATCH (n) RETURN count(n)", nil, nil) if err != nil { log.Fatal(err) } res.Next() r := res.Record() count, _ := r.GetByIndex(0) fmt.Println("Node count:", count) ``` -------------------------------- ### Connect using URL Source: https://context7.com/falkordb/falkordb-go/llms.txt Parses a connection URL to establish a FalkorDB client connection. Supports 'falkor://' (plain) and 'falkors://' (TLS) schemes. ```go // Plain connection db, err := falkordb.FromURL("falkor://:mypassword@localhost:6379/0") if err != nil { log.Fatal(err) } defer db.Conn.Close() // TLS connection dbTLS, err := falkordb.FromURL("falkors://:mypassword@secure-host:6380/0") if err != nil { log.Fatal(err) } defer dbTLS.Conn.Close() ``` -------------------------------- ### Pretty Print Query Results in Go Source: https://context7.com/falkordb/falkordb-go/llms.txt Use `PrettyPrint()` to display the entire result set as a formatted ASCII table to standard output, followed by query statistics. This is useful for quick inspection of tabular results. ```go graph := db.SelectGraph("social") result, err := graph.Query( "MATCH (p:Person) RETURN p.name, p.age LIMIT 5", nil, nil, ) if err != nil { log.Fatal(err) } result.PrettyPrint() ``` -------------------------------- ### Manage User Defined Functions (UDFs) Source: https://github.com/falkordb/falkordb-go/blob/master/README.md Load, list, use, delete, and flush User Defined Functions (UDFs) written in JavaScript with the FalkorDB Go client. ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "0.0.0.0:6379"}) // Define a UDF library library := "StringUtils" source := " function UpperCaseOdd(s) { return s.split('').map((char, i) => (i % 2 !== 0 ? char.toUpperCase() : char)).join(''); } falkor.register('UpperCaseOdd', UpperCaseOdd); " // Load the UDF library err := db.UDFLoad(library, source) // List all loaded UDF libraries udfs, err := db.UDFList() // Use the UDF in a query graph := db.SelectGraph("demo") result, _ := graph.Query("RETURN StringUtils.UpperCaseOdd('hello')", nil, nil) // Delete a specific UDF library err = db.UDFDelete(library) // Or flush all UDF libraries err = db.UDFFlush() ``` -------------------------------- ### ConfigGet / ConfigSet — Read and write DB-level configuration Source: https://context7.com/falkordb/falkordb-go/llms.txt Allows reading and updating FalkorDB server configuration parameters at runtime, such as `TIMEOUT` and `MAX_QUEUED_QUERIES`. ```APIDOC ## ConfigGet / ConfigSet — Read and write DB-level configuration Reads or updates FalkorDB server configuration parameters at runtime. See the [FalkorDB configuration reference](https://docs.falkordb.com/configuration.html) for available keys such as `TIMEOUT`, `MAX_QUEUED_QUERIES`, and `RESULTSET_SIZE`. ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "localhost:6379"}) // Read current timeout setting val, err := db.ConfigGet("TIMEOUT") if err != nil { log.Fatal(err) } fmt.Println("Current TIMEOUT:", val) // Update query timeout to 1000ms err = db.ConfigSet("TIMEOUT", 1000) if err != nil { log.Fatal(err) } fmt.Println("TIMEOUT updated to 1000ms") // Verify val, _ = db.ConfigGet("TIMEOUT") fmt.Println("Updated TIMEOUT:", val) ``` ``` -------------------------------- ### Connect to Standalone FalkorDB Source: https://context7.com/falkordb/falkordb-go/llms.txt Creates a new FalkorDB client for a standalone server. Supports automatic adaptation to Redis Sentinel topology. Connection options include address, password, TLS, and pool sizing. ```go package main import ( "fmt" "log" "github.com/FalkorDB/falkordb-go/v2" ) func main() { db, err := falkordb.FalkorDBNew(&falkordb.ConnectionOption{ Addr: "localhost:6379", Password: "mysecret", }) if err != nil { log.Fatal(err) } defer db.Conn.Close() graphs, err := db.ListGraphs() if err != nil { log.Fatal(err) } fmt.Println("Graphs:", graphs) // Output: Graphs: [social analytics] } ``` -------------------------------- ### FromURL Source: https://context7.com/falkordb/falkordb-go/llms.txt Parses a connection URL and returns a FalkorDB client. Supports both plain and TLS connections. ```APIDOC ## FromURL ### Description Parses a connection URL and returns a `FalkorDB` client. Supports `falkor://` (plain) and `falkors://` (TLS) schemes, which are automatically translated to `redis://` and `rediss://` respectively. ### Method `falkordb.FromURL(url string) (*falkordb.FalkorDB, error)` ### Parameters #### Path Parameters - **url** (string) - Required - The connection URL string. ### Request Example ```go // Plain connection db, err := falkordb.FromURL("falkor://:mypassword@localhost:6379/0") if err != nil { log.Fatal(err) } defer db.Conn.Close() // TLS connection dbTLS, err := falkordb.FromURL("falkors://:mypassword@secure-host:6380/0") if err != nil { log.Fatal(err) } defer dbTLS.Conn.Close() ``` ### Response #### Success Response (200) - **FalkorDB** (*falkordb.FalkorDB) - A client instance connected to FalkorDB. - **error** (error) - An error if the URL parsing or connection fails. ``` -------------------------------- ### FalkorDBNew with TLS Source: https://context7.com/falkordb/falkordb-go/llms.txt Establishes a connection with mutual TLS authentication for secure and authenticated connections. ```APIDOC ## FalkorDBNew with TLS ### Description Establishes a connection with full client-certificate TLS, useful for production deployments requiring encrypted and authenticated connections. ### Method `falkordb.FalkorDBNew(option *falkordb.ConnectionOption) (*falkorDB.FalkorDB, error)` ### Parameters #### Request Body - **option** (*falkordb.ConnectionOption) - Required - Connection options for the FalkorDB client. - **Addr** (string) - The address of the FalkorDB server. - **Password** (string) - The password for authentication. - **TLSConfig** (*tls.Config) - Required - TLS configuration for mutual TLS authentication. - **Certificates** ([]tls.Certificate) - Client certificates for authentication. - **RootCAs** (*x509.CertPool) - CA certificates for verifying the server. ### Request Example ```go import ( "crypto/tls" "crypto/x509" "os" "github.com/FalkorDB/falkordb-go/v2" ) cert, err := tls.LoadX509KeyPair("client.crt", "client.key") if err != nil { log.Fatal(err) } caCert, err := os.ReadFile("ca.crt") if err != nil { log.Fatal(err) } caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) tlsCfg := &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: caCertPool, } db, err := falkordb.FalkorDBNew(&falkordb.ConnectionOption{ Addr: "secure-falkordb:6380", Password: "secret", TLSConfig: tlsCfg, }) if err != nil { log.Fatal(err) } defer db.Conn.Close() graph := db.SelectGraph("social") res, err := graph.Query("MATCH (n) RETURN count(n)", nil, nil) if err != nil { log.Fatal(err) } res.Next() r := res.Record() count, _ := r.GetByIndex(0) fmt.Println("Node count:", count) ``` ### Response #### Success Response (200) - **FalkorDB** (*falkordb.FalkorDB) - A client instance connected to FalkorDB with TLS enabled. - **error** (error) - An error if the connection fails. ``` -------------------------------- ### List All Graphs Source: https://context7.com/falkordb/falkordb-go/llms.txt Returns a slice of strings containing all graph names currently stored in the FalkorDB instance. ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "localhost:6379"}) graphs, err := db.ListGraphs() if err != nil { log.Fatal(err) } for _, name := range graphs { fmt.Println("-", name) } // Output: // - social // - analytics ``` -------------------------------- ### Query with Timeout Option Source: https://github.com/falkordb/falkordb-go/blob/master/README.md Execute a FalkorDB query with a specified millisecond timeout using QueryOptions. ```go options := NewQueryOptions().SetTimeout(10) // 10-millisecond timeout res, err := graph.Query("MATCH (src {name: 'John Doe'})-[*]->(dest) RETURN dest", nil, options) ``` -------------------------------- ### Graph.ExecutionPlan Source: https://context7.com/falkordb/falkordb-go/llms.txt Retrieves a human-readable string describing the execution plan FalkorDB will use for a given Cypher query. This is useful for query optimization and debugging index usage. ```APIDOC ## Graph.ExecutionPlan — Retrieve the query execution plan Returns a human-readable string describing the execution plan FalkorDB will use for a given Cypher query. Useful for query optimization and debugging index usage. ### Request Example ```go graph := db.SelectGraph("social") plan, err := graph.ExecutionPlan( "MATCH (p:Person {name: 'Alice'})-[:KNOWS]->(f:Person) RETURN f.name", ) if err != nil { log.Fatal(err) } fmt.Println(plan) // Results // Project // Conditional Traverse // Node By Label Scan | (p:Person) ``` ``` -------------------------------- ### FalkorDBNew Source: https://context7.com/falkordb/falkordb-go/llms.txt Creates a new FalkorDB client connected to a standalone server. It supports various connection options including authentication and TLS. ```APIDOC ## FalkorDBNew ### Description Creates a new `FalkorDB` client connected to a standalone server. Automatically detects and adapts to Redis Sentinel topology when the target address is a Sentinel node. The `ConnectionOption` type is an alias for `redis.Options`, supporting all go-redis connection fields including TLS, auth, pool sizing, and retry behavior. ### Method `falkordb.FalkorDBNew(option *falkordb.ConnectionOption) (*falkordb.FalkorDB, error)` ### Parameters #### Request Body - **option** (*falkordb.ConnectionOption) - Required - Connection options for the FalkorDB client. - **Addr** (string) - The address of the FalkorDB server. - **Password** (string) - The password for authentication. - **DB** (int) - The database number to use. - **MaxRetries** (int) - The maximum number of retries for connection attempts. - **PoolSize** (int) - The size of the connection pool. - **TLSConfig** (*tls.Config) - TLS configuration for secure connections. ### Request Example ```go package main import ( "fmt" "log" "github.com/FalkorDB/falkordb-go/v2" ) func main() { db, err := falkordb.FalkorDBNew(&falkordb.ConnectionOption{ Addr: "localhost:6379", Password: "mysecret", }) if err != nil { log.Fatal(err) } defer db.Conn.Close() graphs, err := db.ListGraphs() if err != nil { log.Fatal(err) } fmt.Println("Graphs:", graphs) } ``` ### Response #### Success Response (200) - **FalkorDB** (*falkordb.FalkorDB) - A client instance connected to FalkorDB. - **error** (error) - An error if the connection fails. ``` -------------------------------- ### Working with Graph Path Results Source: https://context7.com/falkordb/falkordb-go/llms.txt Demonstrates how to retrieve and process path results from graph queries using the `Path` type. ```APIDOC ## Path — Work with graph path results `Path` is returned when a query uses a path pattern (`MATCH p = ...`). It contains ordered slices of `*Node` and `*Edge` that form the traversal. ```go result, _ := graph.Query( "MATCH p = (:Person {name: 'Alice'})-[:KNOWS*1..3]->(:Person) RETURN p LIMIT 1", nil, nil, ) result.Next() r := result.Record() pIface, _ := r.GetByIndex(0) path := pIface.(falkordb.Path) fmt.Println("Nodes in path:", path.NodesCount()) fmt.Println("Edges in path:", path.EdgeCount()) fmt.Println("First node:", path.FirstNode().GetProperty("name")) fmt.Println("Last node:", path.LastNode().GetProperty("name")) fmt.Println("Path string:", path.String()) // <(0)-[0]->(1)-[1]->(2)> for i, node := range path.GetNodes() { fmt.Printf(" Node[%d]: %v\n", i, node.GetProperty("name")) } for i, edge := range path.GetEdges() { fmt.Printf(" Edge[%d]: %s\n", i, edge.Relation) } ``` ``` -------------------------------- ### Iterate and Access Query Results in Go Source: https://context7.com/falkordb/falkordb-go/llms.txt Iterate through query results using `Next()` and access individual records with `Record()`. Query metadata like relationships created, properties set, and execution time can also be retrieved. ```go graph := db.SelectGraph("social") result, err := graph.Query( "MATCH (p:Person)-[k:KNOWS]->(f:Person) RETURN p, k, f", nil, nil, ) if err != nil { log.Fatal(err) } for result.Next() { r := result.Record() // Access by column name pIface, ok := r.Get("p") if ok { person := pIface.(*falkordb.Node) fmt.Printf("Person: %s (ID=%d, labels=%v)\n", person.GetProperty("name"), person.ID, person.Labels) } // Access edge by index eIface, _ := r.GetByIndex(1) edge := eIface.(*falkordb.Edge) fmt.Printf(" -[%s {since: %v}]->\n", edge.Relation, edge.GetProperty("since")) // Access by index fIface, _ := r.GetByIndex(2) friend := fIface.(*falkordb.Node) fmt.Printf(" Friend: %s\n", friend.GetProperty("name")) } // Query statistics fmt.Printf("Relationships created: %d\n", result.RelationshipsCreated()) fmt.Printf("Properties set: %d\n", result.PropertiesSet()) fmt.Printf("Cached execution: %d\n", result.CachedExecution()) fmt.Printf("Internal execution time: %.3fms\n", result.InternalExecutionTime()) ``` -------------------------------- ### Work with Node Data in Go Source: https://context7.com/falkordb/falkordb-go/llms.txt Access properties, ID, and labels of a `Node` object. `GetProperty()` retrieves a specific property, while `String()` and `Encode()` provide string representations. ```go result, _ := graph.Query( "CREATE (p:Person:Employee {name: 'Carol', dept: 'Engineering'}) RETURN p", nil, nil, ) result.Next() r := result.Record() nIface, _ := r.GetByIndex(0) node := nIface.(*falkordb.Node) fmt.Println("Node ID:", node.ID) fmt.Println("Labels:", node.Labels) // [Person Employee] fmt.Println("Name:", node.GetProperty("name")) // Carol fmt.Println("Dept:", node.GetProperty("dept")) // Engineering fmt.Println("String:", node.String()) // {name:"Carol",dept:"Engineering"} fmt.Println("Encoded:", node.Encode()) // (p:Person:Employee{name:"Carol",dept:"Engineering"}) ``` -------------------------------- ### Execute Read/Write Cypher Query with Parameters Source: https://context7.com/falkordb/falkordb-go/llms.txt Use `Graph.Query` to execute Cypher queries that modify the graph. Named parameters can be passed using a map. Results can be iterated to retrieve records and metadata like nodes created and execution time. ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "localhost:6379"}) graph := db.SelectGraph("social") // Write query — create nodes _, err := graph.Query( "CREATE (:Person {name: $name, age: $age})-[:LIVES_IN]->(:City {name: $city})", map[string]interface{}{ "name": "Alice", "age": 30, "city": "Wonderland", }, nil, ) if err != nil { log.Fatal(err) } // Read query — return structured results result, err := graph.Query( "MATCH (p:Person)-[:LIVES_IN]->(c:City) RETURN p.name, p.age, c.name", nil, nil, ) if err != nil { log.Fatal(err) } for result.Next() { r := result.Record() name, _ := r.Get("p.name") age, _ := r.Get("p.age") city, _ := r.Get("c.name") fmt.Printf("%s (age %v) lives in %s\n", name, age, city) } // Output: Alice (age 30) lives in Wonderland fmt.Printf("Nodes created: %d\n", result.NodesCreated()) fmt.Printf("Execution time: %.2fms\n", result.InternalExecutionTime()) ``` -------------------------------- ### Execute Query with Timeout Option Source: https://context7.com/falkordb/falkordb-go/llms.txt Set a query timeout using `NewQueryOptions` and `SetTimeout`. This option is passed to the server via the `timeout` flag on `GRAPH.QUERY`. Handle potential timeout errors. ```go graph := db.SelectGraph("social") // Set a 50ms query timeout opts := falkordb.NewQueryOptions().SetTimeout(50) result, err := graph.Query( "MATCH (src:Person)-[*]->(dest:Person) RETURN src.name, dest.name", nil, opts, ) if err != nil { // May return a timeout error if the traversal exceeds 50ms log.Printf("Query error (possibly timed out): %v", err) return } for result.Next() { r := result.Record() src, _ := r.GetByIndex(0) dst, _ := r.GetByIndex(1) fmt.Printf("%v -> %v\n", src, dst) } ``` -------------------------------- ### ListGraphs Source: https://context7.com/falkordb/falkordb-go/llms.txt Lists all graph names currently stored in the FalkorDB instance. ```APIDOC ## ListGraphs ### Description Returns a `[]string` of all graph names currently stored in the FalkorDB instance. ### Method `db.ListGraphs() ([]string, error)` ### Request Example ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "localhost:6379"}) graphs, err := db.ListGraphs() if err != nil { log.Fatal(err) } for _, name := range graphs { fmt.Println("- ", name) } ``` ### Response #### Success Response (200) - **graphs** ([]string) - A slice of strings, where each string is the name of a graph. - **error** (error) - An error if listing graphs fails. ``` -------------------------------- ### FalkorDBNewCluster Source: https://context7.com/falkordb/falkordb-go/llms.txt Creates a FalkorDB client backed by a Redis Cluster connection. Supports cluster-specific connection options. ```APIDOC ## FalkorDBNewCluster ### Description Creates a `FalkorDB` client backed by a Redis Cluster connection. `ConnectionClusterOption` is an alias for `redis.ClusterOptions`. ### Method `falkordb.FalkorDBNewCluster(option *falkordb.ConnectionClusterOption) (*falkordb.FalkorDB, error)` ### Parameters #### Request Body - **option** (*falkordb.ConnectionClusterOption) - Required - Connection options for the FalkorDB cluster client. - **Addrs** ([]string) - A list of addresses for the Redis cluster nodes. - **Password** (string) - The password for authentication. - **MaxRedirects** (int) - The maximum number of redirects for cluster commands. - **PoolSize** (int) - The size of the connection pool. - **TLSConfig** (*tls.Config) - TLS configuration for secure connections. ### Request Example ```go db, err := falkordb.FalkorDBNewCluster(&falkordb.ConnectionClusterOption{ Addrs: []string{ "node1:6379", "node2:6379", "node3:6379", }, Password: "clusterpass", }) if err != nil { log.Fatal(err) } defer db.Conn.Close() graph := db.SelectGraph("social") _, err = graph.Query("CREATE (:Person {name: 'Alice'})", nil, nil) if err != nil { log.Fatal(err) } ``` ### Response #### Success Response (200) - **FalkorDB** (*falkordb.FalkorDB) - A client instance connected to the FalkorDB cluster. - **error** (error) - An error if the connection fails. ``` -------------------------------- ### Invoke Built-in Graph Procedure Source: https://context7.com/falkordb/falkordb-go/llms.txt Use `Graph.CallProcedure` to execute FalkorDB built-in procedures like `db.labels` or `db.relationshipTypes`. Specify the procedure name and optionally the columns to yield. Results are returned as a `*QueryResult`. ```go graph := db.SelectGraph("social") // List all node labels result, err := graph.CallProcedure("db.labels", []string{"label"}) if err != nil { log.Fatal(err) } fmt.Println("Labels:") for result.Next() { r := result.Record() label, _ := r.GetByIndex(0) fmt.Println(" -", label) } // List all relationship types result, err = graph.CallProcedure("db.relationshipTypes", []string{"relationshipType"}) if err != nil { log.Fatal(err) } fmt.Println("Relationship types:") for result.Next() { r := result.Record() rel, _ := r.GetByIndex(0) fmt.Println(" -", rel) } ``` -------------------------------- ### QueryResult.PrettyPrint Source: https://context7.com/falkordb/falkordb-go/llms.txt Renders the entire result set as a formatted ASCII table to standard output, followed by query statistics. ```APIDOC ## QueryResult.PrettyPrint() ### Description Prints the query results as a formatted table to stdout, including query statistics. ### Method `PrettyPrint()` ``` -------------------------------- ### NewQueryOptions / SetTimeout Source: https://context7.com/falkordb/falkordb-go/llms.txt Creates a `QueryOptions` struct and sets a millisecond-level timeout for query execution, which is passed to the server via the `timeout` flag on `GRAPH.QUERY`. ```APIDOC ## NewQueryOptions / SetTimeout — Execute a query with a timeout `NewQueryOptions` creates a `QueryOptions` struct. `SetTimeout` sets a millisecond-level timeout that is passed to the server via the `timeout` flag on `GRAPH.QUERY`. ### Request Example ```go graph := db.SelectGraph("social") // Set a 50ms query timeout opts := falkordb.NewQueryOptions().SetTimeout(50) result, err := graph.Query( "MATCH (src:Person)-[*]->(dest:Person) RETURN src.name, dest.name", nil, opts, ) if err != nil { // May return a timeout error if the traversal exceeds 50ms log.Printf("Query error (possibly timed out): %v", err) return } for result.Next() { r := result.Record() src, _ := r.GetByIndex(0) dst, _ := r.GetByIndex(1) fmt.Printf("%v -> %v\n", src, dst) } ``` ``` -------------------------------- ### Work with Edge Data in Go Source: https://context7.com/falkordb/falkordb-go/llms.txt Access properties, ID, relation type, and source/destination node IDs of an `Edge` object. `GetProperty()` retrieves a specific property, and `String()` provides a string representation. ```go result, _ := graph.Query( "MATCH (a:Person)-[r:KNOWS]->(b:Person) RETURN r LIMIT 1", nil, nil, ) result.Next() r := result.Record() eIface, _ := r.GetByIndex(0) edge := eIface.(*falkordb.Edge) fmt.Println("Edge ID:", edge.ID) fmt.Println("Relation:", edge.Relation) // KNOWS fmt.Println("Since:", edge.GetProperty("since")) // 2022 fmt.Println("Src Node ID:", edge.SourceNodeID()) fmt.Println("Dst Node ID:", edge.DestNodeID()) fmt.Println("String:", edge.String()) // {since:2022} ``` -------------------------------- ### SelectGraph Source: https://context7.com/falkordb/falkordb-go/llms.txt Selects a named graph for querying. The graph is created implicitly on the first write query if it does not exist. ```APIDOC ## SelectGraph ### Description Returns a `*Graph` handle for the named graph. The graph is created implicitly on the first write query if it does not exist. No network call is made at selection time. ### Method `db.SelectGraph(graphID string) *falkordb.Graph` ### Parameters #### Path Parameters - **graphID** (string) - Required - The name of the graph to select. ### Request Example ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "localhost:6379"}) graph := db.SelectGraph("social") fmt.Println("Working with graph:", graph.Id) ``` ### Response #### Success Response (200) - **Graph** (*falkordb.Graph) - A handle to the selected graph. ``` -------------------------------- ### Execute Read-Only Cypher Query Source: https://context7.com/falkordb/falkordb-go/llms.txt Utilize `Graph.ROQuery` for queries that should not modify the graph. This enforces read-only semantics at the server level, making it safer for untrusted queries. Results can be pretty-printed. ```go graph := db.SelectGraph("social") result, err := graph.ROQuery( "MATCH (p:Person) WHERE p.age > $minAge RETURN p.name, p.age ORDER BY p.age DESC", map[string]interface{}{"minAge": 25}, nil, ) if err != nil { log.Fatal(err) } result.PrettyPrint() // +-------+-------+ // | p.name | p.age | // +-------+-------+ // | Bob | 45 | // | Alice | 30 | // +-------+-------+ ``` -------------------------------- ### UDFLoad / UDFList / UDFDelete / UDFFlush — Manage User Defined Functions Source: https://context7.com/falkordb/falkordb-go/llms.txt Provides functionality to manage JavaScript-based User Defined Functions (UDFs), including loading, listing, deleting, and flushing all UDF libraries. ```APIDOC ## UDFLoad / UDFList / UDFDelete / UDFFlush — Manage User Defined Functions FalkorDB supports JavaScript-based User Defined Functions. `UDFLoad` registers a named library, `UDFList` enumerates all loaded libraries and their functions, `UDFDelete` removes a specific library, and `UDFFlush` removes all libraries. ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "localhost:6379"}) defer db.Conn.Close() library := "MathUtils" source := ` function square(x) { return x * x; } function cube(x) { return x * x * x; } falkor.register('square', square); falkor.register('cube', cube); ` // Load the UDF library if err := db.UDFLoad(library, source); err != nil { log.Fatal("UDFLoad:", err) } // List loaded libraries udfs, err := db.UDFList() if err != nil { log.Fatal("UDFList:", err) } fmt.Printf("Loaded UDFs: %v\n", udfs) // Loaded UDFs: [[MathUtils [square cube]]] // Use a UDF in a Cypher query graph := db.SelectGraph("demo") result, err := graph.Query("RETURN MathUtils.square(7)", nil, nil) if err != nil { log.Fatal(err) } result.Next() val, _ := result.Record().GetByIndex(0) fmt.Println("7² =", val) // 7² = 49 // Remove a specific UDF library if err := db.UDFDelete(library); err != nil { log.Fatal("UDFDelete:", err) } // Or remove all UDF libraries if err := db.UDFFlush(); err != nil { log.Fatal("UDFFlush:", err) } ``` ``` -------------------------------- ### Graph.CallProcedure Source: https://context7.com/falkordb/falkordb-go/llms.txt Invokes a FalkorDB built-in procedure (e.g., `db.labels`, `db.relationshipTypes`, `db.propertyKeys`, `db.indexes`) and returns a `*QueryResult`. An optional `yield` slice can specify which columns to return. ```APIDOC ## Graph.CallProcedure — Invoke a built-in graph procedure Calls a FalkorDB built-in procedure (e.g., `db.labels`, `db.relationshipTypes`, `db.propertyKeys`, `db.indexes`) and returns a `*QueryResult`. The optional `yield` slice specifies which columns to return. ### Request Example ```go graph := db.SelectGraph("social") // List all node labels result, err := graph.CallProcedure("db.labels", []string{"label"}) if err != nil { log.Fatal(err) } fmt.Println("Labels:") for result.Next() { r := result.Record() label, _ := r.GetByIndex(0) fmt.Println(" -", label) } // List all relationship types result, err = graph.CallProcedure("db.relationshipTypes", []string{"relationshipType"}) if err != nil { log.Fatal(err) } fmt.Println("Relationship types:") for result.Next() { r := result.Record() rel, _ := r.GetByIndex(0) fmt.Println(" -", rel) } ``` ``` -------------------------------- ### Graph.Query Source: https://context7.com/falkordb/falkordb-go/llms.txt Executes a read/write Cypher query against a selected graph. It accepts optional named parameters and query options for timeout control. ```APIDOC ## Graph.Query — Execute a read/write Cypher query Runs a Cypher query against the selected graph and returns a `*QueryResult`. Accepts an optional `map[string]interface{}` of named parameters (prepended as a `CYPHER` header) and an optional `*QueryOptions` for timeout control. ### Request Example ```go db, _ := falkordb.FalkorDBNew(&falkordb.ConnectionOption{Addr: "localhost:6379"}) graph := db.SelectGraph("social") // Write query — create nodes _, err := graph.Query( "CREATE (:Person {name: $name, age: $age})-[:LIVES_IN]->(:City {name: $city})", map[string]interface{}{ "name": "Alice", "age": 30, "city": "Wonderland", }, nil, ) if err != nil { log.Fatal(err) } // Read query — return structured results result, err := graph.Query( "MATCH (p:Person)-[:LIVES_IN]->(c:City) RETURN p.name, p.age, c.name", nil, nil, ) if err != nil { log.Fatal(err) } for result.Next() { r := result.Record() name, _ := r.Get("p.name") age, _ := r.Get("p.age") city, _ := r.Get("c.name") fmt.Printf("%s (age %v) lives in %s\n", name, age, city) } // Output: Alice (age 30) lives in Wonderland fmt.Printf("Nodes created: %d\n", result.NodesCreated()) fmt.Printf("Execution time: %.2fms\n", result.InternalExecutionTime()) ``` ``` -------------------------------- ### Graph.ROQuery Source: https://context7.com/falkordb/falkordb-go/llms.txt Executes a read-only Cypher query using the `GRAPH.RO_QUERY` command, enforcing read-only semantics at the server level. This is useful for safely running untrusted or user-supplied queries. ```APIDOC ## Graph.ROQuery — Execute a read-only Cypher query Executes a query using the `GRAPH.RO_QUERY` command, which enforces read-only semantics at the server level. Useful for safely running untrusted or user-supplied queries. ### Request Example ```go graph := db.SelectGraph("social") result, err := graph.ROQuery( "MATCH (p:Person) WHERE p.age > $minAge RETURN p.name, p.age ORDER BY p.age DESC", map[string]interface{}{"minAge": 25}, nil, ) if err != nil { log.Fatal(err) } result.PrettyPrint() // +-------+-------+ // | p.name | p.age | // +-------+-------+--- // | Bob | 45 | // | Alice | 30 | // +-------+-------+ ``` ```