### Clone and Install FalkorDB Examples Source: https://github.com/falkordb/falkordb-ts/blob/main/examples/README.md Instructions for setting up the examples folder to run or develop your own examples. This involves cloning the repository, installing dependencies, and building the project. ```bash $ git clone https://github.com/falkordb/falkordb-ts.git $ cd falkordb-ts $ npm install -ws && npm run build-all $ cd examples $ npm install ``` -------------------------------- ### FalkorDB Example Template Source: https://github.com/falkordb/falkordb-ts/blob/main/examples/README.md A starter template for creating new FalkorDB examples. It includes basic setup for connecting to the database and a placeholder for your example code. ```javascript // This comment should describe what the example does // and can extend to multiple lines. import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect() // Add your example code here... await db.quit(); ``` -------------------------------- ### Install release-it Source: https://github.com/falkordb/falkordb-ts/blob/main/RELEASE.md Install the release-it tool globally if it is not already installed. This tool helps automate the release process. ```bash npm install -g release-it ``` -------------------------------- ### Install FalkorDB and Node.js Client Source: https://context7.com/falkordb/falkordb-ts/llms.txt Instructions for setting up FalkorDB via Docker and installing the Node.js client library using npm. ```bash # Start FalkorDB via Docker docker run -p 6379:6379 -it falkordb/falkordb:latest # Install the client npm install falkordb ``` -------------------------------- ### Run FalkorDB via Docker Source: https://github.com/falkordb/falkordb-ts/blob/main/README.md Use this command to start a FalkorDB instance using Docker. Ensure Docker is installed and running on your system. ```bash docker run -p 6379:6379 -it falkordb/falkordb:latest ``` -------------------------------- ### Connect and Query FalkorDB Source: https://github.com/falkordb/falkordb-ts/blob/main/README.md Basic example demonstrating how to connect to FalkorDB, select a graph, create nodes and relationships, and perform a query. Ensure you have a FalkorDB instance running and replace placeholder credentials. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ username: 'myUsername', password: 'myPassword', socket: { host: 'localhost', port: 6379 } }) console.log('Connected to FalkorDB') const graph = db.selectGraph('myGraph') await graph.query(`CREATE (:Rider {name:'Valentino Rossi'})-[:rides]->(:Team {name:'Yamaha'}), (:Rider {name:'Dani Pedrosa'})-[:rides]->(:Team {name:'Honda'}), (:Rider {name:'Andrea Dovizioso'})-[:rides]->(:Team {name:'Ducati'})`) const result = await graph.query(`MATCH (r:Rider)-[:rides]->(t:Team) WHERE t.name = $name RETURN r.name`, {params: {name: 'Yamaha'}}) console.log(result) // Valentino Rossi console.log(await db.list()) console.log(await db.info()) db.close() ``` -------------------------------- ### Install FalkorDB Node.js Client Source: https://github.com/falkordb/falkordb-ts/blob/main/README.md Install the falkordb npm package to use the FalkorDB client in your Node.js project. ```bash npm install falkordb ``` -------------------------------- ### Manage FalkorDB Server Configuration Source: https://context7.com/falkordb/falkordb-ts/llms.txt Read and write FalkorDB server configuration parameters at runtime using `configGet` and `configSet`. The example shows how to retrieve the current value of the 'TIMEOUT' configuration key and then update it to a new value, followed by verifying the update. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); // Read current configuration for a key const config = await db.configGet('TIMEOUT'); console.log('TIMEOUT config:', config); // Update configuration await db.configSet('TIMEOUT', 1000); const updated = await db.configGet('TIMEOUT'); console.log('Updated TIMEOUT:', updated); await db.close(); ``` -------------------------------- ### Get Query Execution Plan with graph.explain Source: https://context7.com/falkordb/falkordb-ts/llms.txt Retrieve the execution plan for a Cypher query without executing it using `explain`. This is useful for query optimization and debugging. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('riders'); await graph.query(` CREATE (:Rider {name:'Valentino Rossi'})-[:rides]->(:Team {name:'Yamaha'}) `); const plan = await graph.explain( 'MATCH (r:Rider)-[:rides]->(t:Team) WHERE t.name = $name RETURN r.name, t.name' ); console.log(plan); // [ // 'Results', // ' Project', // ' Conditional Traverse | (t)->(r:Rider)', // ' Filter', // ' Node By Label Scan | (t:Team)' // ] await graph.delete(); await db.close(); ``` -------------------------------- ### Load and Use JavaScript UDFs in FalkorDB Source: https://context7.com/falkordb/falkordb-ts/llms.txt Register JavaScript User-Defined Functions (UDFs) by providing a raw script string or a named function. UDFs can be loaded with or without replacement of existing libraries. Examples demonstrate loading math and string manipulation UDFs, executing them within Cypher queries, and cleaning up by deleting the loaded libraries. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); // Load a library using raw script string const mathScript = ` function add(a, b) { return a + b; } function multiply(a, b) { return a * b; } falkor.register("add", add); falkor.register("multiply", multiply); `; await db.udfLoad('mathlib', mathScript); // Load a library by passing a named function directly (register() added automatically) const doubleValue = function doubleValue(n: number) { return n * 2; }; await db.udfLoad('jslib', doubleValue); // Use UDFs in Cypher queries const graph = db.selectGraph('udf_graph'); const addResult: any = await graph.query('RETURN mathlib.add(5, 3) AS sum'); console.log(addResult.data[0].sum); // 8 const doubleResult: any = await graph.query('RETURN jslib.doubleValue(21) AS doubled'); console.log(doubleResult.data[0].doubled); // 42 // Use a UDF to transform node properties await graph.query("CREATE (:City {name: 'london'})"); const greetScript = `function greet(name) { return "Hello, " + name + "!"; } falkor.register("greet", greet); `; await db.udfLoad('strlib', greetScript); const greetResult: any = await graph.query("MATCH (c:City) RETURN strlib.greet(c.name) AS msg"); console.log(greetResult.data[0].msg); // "Hello, london!" await graph.delete(); await db.udfDelete('mathlib'); await db.udfDelete('jslib'); await db.udfDelete('strlib'); await db.close(); ``` -------------------------------- ### List All FalkorDB Graphs Source: https://context7.com/falkordb/falkordb-ts/llms.txt Retrieve a list of all graph names currently stored on the FalkorDB server. This function is useful for understanding the current state of your graph databases. The example demonstrates creating two graphs, listing them, and then cleaning up by deleting both graphs. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const g1 = db.selectGraph('graphA'); const g2 = db.selectGraph('graphB'); await g1.query("CREATE (:Node)"); await g2.query("CREATE (:Node)"); const graphs = await db.list(); console.log(graphs); // ['graphA', 'graphB'] (order may vary) await g1.delete(); await g2.delete(); await db.close(); ``` -------------------------------- ### Get Graph Memory Usage with graph.memoryUsage Source: https://context7.com/falkordb/falkordb-ts/llms.txt Obtain detailed memory usage statistics for a graph using `memoryUsage`. An optional `SAMPLES` option can control the sampling depth. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('mem_test'); await graph.query("UNWIND range(1, 1000) AS i CREATE (:Node {val: i})"); const usage = await graph.memoryUsage({ SAMPLES: 5 }); console.log('Memory usage report:', usage); // Returns nested array of [key, value] memory statistics await graph.delete(); await db.close(); ``` -------------------------------- ### Remove FalkorDB UDF Libraries Source: https://context7.com/falkordb/falkordb-ts/llms.txt Manage User-Defined Function (UDF) libraries by deleting specific ones or flushing all registered libraries. `udfDelete` removes a single library by name, while `udfFlush` clears all UDFs from the server. The examples show how to load two libraries, verify their count, delete one, and then flush the remaining one, confirming the count returns to zero. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const s1 = `function f1() { return 1; }\nfalkor.register("f1", f1); `; const s2 = `function f2() { return 2; }\nfalkor.register("f2", f2); `; await db.udfLoad('lib1', s1); await db.udfLoad('lib2', s2); console.log((await db.udfList()).length); // 2 // Delete a specific library await db.udfDelete('lib1'); console.log((await db.udfList()).length); // 1 // Flush all remaining libraries await db.udfFlush(); console.log((await db.udfList()).length); // 0 await db.close(); ``` -------------------------------- ### FalkorDB.connect(options?) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Establishes a connection to a FalkorDB instance and returns a connected client. It supports various connection options and automatically detects the deployment topology. ```APIDOC ## FalkorDB.connect(options?) ### Description Creates and returns a connected `FalkorDB` client. Accepts a `FalkorDBOptions` object with URL, socket, credentials, TLS, ping interval, and other settings. The client auto-detects whether the server is a standalone instance, Sentinel-managed, or a cluster and returns the appropriate internal client type. ### Method `FalkorDB.connect(options?)` ### Parameters - **options** (`FalkorDBOptions`) - **url** (`string`) - Optional - URL to connect to (e.g., `falkor://user:pass@host:port`) - **username** (`string`) - Optional - Username for authentication - **password** (`string`) - Optional - Password for authentication - **socket** (`object`) - Optional - Socket connection options - **host** (`string`) - Required - Hostname of the FalkorDB server - **port** (`number`) - Required - Port of the FalkorDB server - **tls** (`boolean`) - Optional - Whether to use TLS/SSL - **connectTimeout** (`number`) - Optional - Connection timeout in milliseconds - **pingInterval** (`number`) - Optional - Interval for sending pings in milliseconds ### Request Example ```typescript import { FalkorDB } from 'falkordb'; // Connect using explicit host/port with authentication const db = await FalkorDB.connect({ username: 'myUsername', password: 'myPassword', socket: { host: 'localhost', port: 6379, tls: false, connectTimeout: 5000, } }); // Alternatively, connect using a URL (falkor:// or falkordb://) const db2 = await FalkorDB.connect({ url: 'falkor://user:pass@localhost:6379' }); // Forward connection errors db.on('error', (err) => console.error('FalkorDB error:', err)); console.log('Connected to FalkorDB'); await db.close(); ``` ### Response - **FalkorDB Client** - A connected FalkorDB client instance. ``` -------------------------------- ### Run release-it Source: https://github.com/falkordb/falkordb-ts/blob/main/RELEASE.md Execute the release-it command to automate version bumping, git commits, tag creation, and pushing to GitHub. This is an alternative to manual release steps. ```bash release-it ``` -------------------------------- ### db.configGet(key) and db.configSet(key, value) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Manage FalkorDB server configuration parameters at runtime. `configGet` reads a configuration value, and `configSet` writes a new value. ```APIDOC ## `db.configGet(key)` and `db.configSet(key, value)` — Manage server configuration Reads or writes FalkorDB server configuration parameters at runtime. ### Parameters #### Path Parameters - **key** (string) - Required - The configuration parameter key. - **value** (string) - Required (for `configSet`) - The new value for the configuration parameter. ### Request Example ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); // Read current configuration for a key const config = await db.configGet('TIMEOUT'); console.log('TIMEOUT config:', config); // Update configuration await db.configSet('TIMEOUT', 1000); const updated = await db.configGet('TIMEOUT'); console.log('Updated TIMEOUT:', updated); ``` ### Response #### Success Response (200) - **configGet**: (string) - The current value of the configuration parameter. - **configSet**: (void) - Operation successful. ``` -------------------------------- ### Profile Query Execution with graph.profile Source: https://context7.com/falkordb/falkordb-ts/llms.txt Execute a query and obtain detailed runtime profiling information using `profile`. This shows record counts and time spent at each execution step. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('profile_test'); await graph.query("UNWIND range(1, 100) AS i CREATE (:Node {val: i})"); const profile = await graph.profile('MATCH (n:Node) WHERE n.val > 50 RETURN n.val'); console.log(profile); // Returns an array of strings with per-step record counts and timing info await graph.delete(); await db.close(); ``` -------------------------------- ### db.udfList(lib?, withCode?) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Returns all registered UDF libraries, optionally filtered by library name and optionally including the source code. ```APIDOC ## `db.udfList(lib?, withCode?)` — List UDF libraries Returns all registered UDF libraries, optionally filtered by library name and optionally including the source code. ### Parameters #### Path Parameters - **lib** (string) - Optional - The name of the UDF library to filter by. - **withCode** (boolean) - Optional - If true, includes the source code of the UDF libraries. ### Request Example ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const script = `function hello() { return "world"; }\nfalkor.register("hello", hello); `; await db.udfLoad('mylib', script); // List all UDF libraries const all = await db.udfList(); console.log(all); // Filter by library name const filtered = await db.udfList('mylib'); console.log(filtered); // Include source code const withCode = await db.udfList(undefined, true); console.log(withCode); ``` ### Response #### Success Response (200) - (Array) - An array of UDF libraries. Each element can be an array containing the library name, a list of function names, and optionally the source code. ``` -------------------------------- ### Connect to FalkorDB Instance (TypeScript) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Connect to a FalkorDB instance using explicit host/port with authentication or a connection URL. Handles connection errors by emitting an 'error' event. ```typescript import { FalkorDB } from 'falkordb'; // Connect using explicit host/port with authentication const db = await FalkorDB.connect({ username: 'myUsername', password: 'myPassword', socket: { host: 'localhost', port: 6379, tls: false, connectTimeout: 5000, } }); // Alternatively, connect using a URL (falkor:// or falkordb://) const db2 = await FalkorDB.connect({ url: 'falkor://user:pass@localhost:6379' }); // Forward connection errors db.on('error', (err) => console.error('FalkorDB error:', err)); console.log('Connected to FalkorDB'); await db.close(); ``` -------------------------------- ### Copy a Graph with graph.copy Source: https://context7.com/falkordb/falkordb-ts/llms.txt Create a full copy of the current graph into a new graph using `copy`. This includes all nodes, edges, indices, and constraints. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const src = db.selectGraph('source_graph'); await src.query(`CREATE (:User {name: 'Alice'})-[:FRIEND]->(:User {name: 'Bob'})`); await src.query('CREATE INDEX ON :User(name)'); await src.copy('destination_graph'); const dest = db.selectGraph('destination_graph'); const result = await dest.roQuery('MATCH (n:User) RETURN n.name AS name ORDER BY name'); console.log(result.data); // [{ name: 'Alice' }, { name: 'Bob' }] await src.delete(); await dest.delete(); await db.close(); ``` -------------------------------- ### db.info(section?) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Retrieves server information from the underlying Redis/FalkorDB server. Information can be optionally filtered by a specific section such as 'server', 'memory', or 'replication'. ```APIDOC ## `db.info(section?)` — Retrieve server info ### Description Returns server information from the underlying Redis/FalkorDB server, optionally filtered by section (e.g., `'server'`, `'memory'`, `'replication'`). ### Parameters #### Query Parameters - **section** (string) - Optional - The section of server info to retrieve. ### Request Example ```typescript // Full server info const fullInfo = await db.info(); // Section-specific info const serverInfo = await db.info('server'); ``` ### Response #### Success Response (200) - **info** (object) - An object containing server information. ### Response Example ```json { "used_memory": "123456", "connected_clients": "5", "redis_version": "7.0.0" } ``` ``` -------------------------------- ### graph.explain(query) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Retrieves the execution plan for a Cypher query without actually executing it. This is valuable for query optimization and debugging purposes. ```APIDOC ## graph.explain(query) ### Description Returns the execution plan for a Cypher query as an array of strings without actually executing it. Useful for query optimization and debugging. ### Method `graph.explain(query)` ### Parameters #### Path Parameters - **query** (string) - Required - The Cypher query for which to get the execution plan. ### Request Example ```typescript const plan = await graph.explain( 'MATCH (r:Rider)-[:rides]->(t:Team) WHERE t.name = $name RETURN r.name, t.name' ); ``` ### Response #### Success Response (200) - **plan** (Array) - An array of strings representing the query execution plan. ### Response Example ```json [ "Results", " Project", " Conditional Traverse | (t)->(r:Rider)", " Filter", " Node By Label Scan | (t:Team)" ] ``` ``` -------------------------------- ### Select and Query a Graph (TypeScript) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Select a specific graph by its ID and execute a Cypher query to create nodes and relationships. Graphs are created lazily on the first write query. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('social'); // Create nodes and relationships await graph.query(` CREATE (:Person {name: 'Alice', age: 30})-[:KNOWS {since: 2020}]->(:Person {name: 'Bob', age: 25}) `); await db.close(); ``` -------------------------------- ### graph.memoryUsage(options?) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Fetches detailed memory usage statistics for a graph. An optional `SAMPLES` option can be provided to control the sampling depth. ```APIDOC ## graph.memoryUsage(options?) ### Description Returns detailed memory usage statistics for a graph. Accepts an optional `SAMPLES` option to control sampling depth. ### Method `graph.memoryUsage(options?)` ### Parameters #### Path Parameters - **options** (object) - Optional - Options for memory usage statistics. - **SAMPLES** (number) - Optional - Controls the sampling depth for memory usage statistics. ### Request Example ```typescript const usage = await graph.memoryUsage({ SAMPLES: 5 }); ``` ### Response #### Success Response (200) - **usage** (Array>) - A nested array containing key-value pairs of memory statistics. ### Response Example ```json [ ["graph_nodes", 1000], ["graph_edges", 1500], ["memory_allocated", 102400] ] ``` ``` -------------------------------- ### db.list() Source: https://context7.com/falkordb/falkordb-ts/llms.txt Returns an array of graph names currently stored on the server. ```APIDOC ## `db.list()` — List all graphs Returns an array of graph names currently stored on the server. ### Parameters None ### Request Example ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const g1 = db.selectGraph('graphA'); const g2 = db.selectGraph('graphB'); await g1.query("CREATE (:Node)"); await g2.query("CREATE (:Node)"); const graphs = await db.list(); console.log(graphs); // ['graphA', 'graphB'] (order may vary) ``` ### Response #### Success Response (200) - (Array) - An array of graph names. ``` -------------------------------- ### graph.copy(destGraph) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Creates a complete copy of the current graph into a new graph specified by `destGraph`. This includes all nodes, edges, indices, and constraints. ```APIDOC ## graph.copy(destGraph) ### Description Creates a full copy of the current graph into a new graph with the given name, including all nodes, edges, indices, and constraints. ### Method `graph.copy(destGraph)` ### Parameters #### Path Parameters - **destGraph** (string) - Required - The name of the destination graph to copy to. ### Request Example ```typescript await src.copy('destination_graph'); ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the graph was copied successfully. ### Response Example ```json { "message": "Graph copied successfully to destination_graph" } ``` ``` -------------------------------- ### graph.profile(query) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Executes a Cypher query and provides detailed runtime profiling information, including record counts and time spent at each step of the execution plan. ```APIDOC ## graph.profile(query) ### Description Executes the query and returns detailed runtime profiling information showing the number of records produced and time spent at each execution plan step. ### Method `graph.profile(query)` ### Parameters #### Path Parameters - **query** (string) - Required - The Cypher query to profile. ### Request Example ```typescript const profile = await graph.profile('MATCH (n:Node) WHERE n.val > 50 RETURN n.val'); ``` ### Response #### Success Response (200) - **profile** (Array) - An array of strings containing per-step record counts and timing information. ### Response Example ```json [ "Step 1: Records: 100, Time: 0.5ms", "Step 2: Records: 50, Time: 0.2ms" ] ``` ``` -------------------------------- ### Retrieve FalkorDB Server Info Source: https://context7.com/falkordb/falkordb-ts/llms.txt Fetches server information, optionally filtered by section. Can be accessed directly or via the raw connection. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); // Full server info const fullInfo = await db.info(); console.log(fullInfo); // Section-specific info const serverInfo = await db.info('server'); console.log(serverInfo); // Also accessible via the raw connection const rawInfo = await db.connection.then(conn => conn.info()); console.log(rawInfo); await db.close(); ``` -------------------------------- ### Manage indices using FalkorDB index methods Source: https://context7.com/falkordb/falkordb-ts/llms.txt Creates and drops RANGE, FULLTEXT, or VECTOR indices on node or edge properties. RANGE indices accelerate lookups, FULLTEXT enables text search, and VECTOR indices support similarity search. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('indexed_graph'); await graph.query(` CREATE (:Article {title: 'Graph databases explained', body: 'FalkorDB is fast...', embedding: [0.1, 0.2, 0.3, 0.4]}), (:Article {title: 'Vector search with FalkorDB', body: 'Using ANN search...', embedding: [0.5, 0.6, 0.7, 0.8]}) `); // RANGE index for equality/range queries await graph.createNodeRangeIndex('Article', 'title'); // FULLTEXT index for text search await graph.createNodeFulltextIndex('Article', 'body'); // VECTOR index for similarity search (128-dim, euclidean distance) await graph.createNodeVectorIndex('Article', 4, 'euclidean', 'embedding'); // RANGE index on edge property await graph.query("MATCH (a:Article), (b:Article) WHERE a <> b CREATE (a)-[:RELATED {score: 0.9}]->(b)"); await graph.createEdgeRangeIndex('RELATED', 'score'); // Verify all indices const indices: any = await graph.roQuery('CALL db.indexes() YIELD label, properties, types, entitytype RETURN *'); console.log(indices.data); // Drop indices await graph.dropNodeRangeIndex('Article', 'title'); await graph.dropNodeFulltextIndex('Article', 'body'); await graph.dropNodeVectorIndex('Article', 'embedding'); await graph.dropEdgeRangeIndex('RELATED', 'score'); await graph.delete(); await db.close(); ``` -------------------------------- ### graph.query(query, options?) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Executes a Cypher query against the selected graph. Supports parameterized queries and an optional timeout. ```APIDOC ## graph.query(query, options?) ### Description Executes a Cypher query against the selected graph and returns a `GraphReply` with typed `data` rows and a `metadata` array. Supports parameterized queries via `options.params` and an optional `TIMEOUT` (ms). ### Method `graph.query(query, options?)` ### Parameters - **query** (`string`) - The Cypher query to execute. - **options** (`object`) - Optional query execution options. - **params** (`object`) - Optional - Parameters to be used in the query. - **TIMEOUT** (`number`) - Optional - Query execution timeout in milliseconds. ### Request Example ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('riders'); // Create data await graph.query(` CREATE (:Rider {name:'Valentino Rossi'})-[:rides]->(:Team {name:'Yamaha'}), (:Rider {name:'Dani Pedrosa'})-[:rides]->(:Team {name:'Honda'}), (:Rider {name:'Andrea Dovizioso'})-[:rides]->(:Team {name:'Ducati'}) `); // Parameterized query const result = await graph.query<{ 'r.name': string }>( 'MATCH (r:Rider)-[:rides]->(t:Team) WHERE t.name = $teamName RETURN r.name', { params: { teamName: 'Yamaha' }, TIMEOUT: 3000 } ); console.log(result.data); // [{ 'r.name': 'Valentino Rossi' }] console.log(result.metadata); // ['Cached execution: 0', 'Query internal execution time: 0.123 milliseconds'] await graph.delete(); await db.close(); ``` ### Response - **GraphReply** - An object containing: - **data** (`Array`) - An array of result rows, typed according to the query. - **metadata** (`Array`) - An array of metadata strings about the query execution. ``` -------------------------------- ### db.udfLoad(name, script, replace?) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Registers a JavaScript User-Defined Function (UDF) library by name. The script can be a raw string or a named JavaScript function. The 'replace' option allows overwriting existing libraries. ```APIDOC ## `db.udfLoad(name, script, replace?)` — Load a User-Defined Function library Registers a JavaScript UDF library by name. The `script` can be a raw string with `falkor.register(...)` calls, or a named JavaScript function that the library will automatically wrap. Set `replace: true` to overwrite an existing library. ### Parameters #### Path Parameters - **name** (string) - Required - The name of the UDF library. - **script** (string) - Required - The JavaScript code for the UDF library. - **replace** (boolean) - Optional - If true, overwrites an existing library with the same name. ### Request Example ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const mathScript = ` function add(a, b) { return a + b; } function multiply(a, b) { return a * b; } falkor.register("add", add); falkor.register("multiply", multiply); `; await db.udfLoad('mathlib', mathScript); const doubleValue = function doubleValue(n: number) { return n * 2; }; await db.udfLoad('jslib', doubleValue); ``` ### Response #### Success Response (200) - (void) - Operation successful. ``` -------------------------------- ### Create constraints using graph.constraintCreate() Source: https://context7.com/falkordb/falkordb-ts/llms.txt Creates UNIQUE or MANDATORY constraints on node labels or relationship types for specified properties. A RANGE index must exist on properties before creating a UNIQUE constraint. ```typescript import { FalkorDB } from 'falkordb'; import { ConstraintType, EntityType } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('constrained_graph'); await graph.query("CREATE (:User {name: 'Alice', email: 'alice@example.com'})"); // Create index first (required for UNIQUE constraints) await graph.query('CREATE INDEX ON :User(email)'); // Create a UNIQUE constraint on User.email await graph.constraintCreate(ConstraintType.UNIQUE, EntityType.NODE, 'User', 'email'); // Create a MANDATORY constraint on User.name await graph.constraintCreate(ConstraintType.MANDATORY, EntityType.NODE, 'User', 'name'); // Create a MANDATORY constraint on a relationship property await graph.query("MATCH (a:User {name:'Alice'}) CREATE (a)-[:SUBSCRIBES {since: 2024}]->(:Plan {name:'Pro'})"); await graph.query('CREATE INDEX ON :SUBSCRIBES(since)'); await graph.constraintCreate(ConstraintType.MANDATORY, EntityType.RELATIONSHIP, 'SUBSCRIBES', 'since'); // Verify constraints const check = await graph.query('CALL db.constraints()'); console.log(check.data); // [{ type: 'UNIQUE', label: 'User', properties: ['email'], entitytype: 'NODE', status: 'OPERATIONAL' }, ...] await graph.delete(); await db.close(); ``` -------------------------------- ### db.udfDelete(lib) and db.udfFlush() Source: https://context7.com/falkordb/falkordb-ts/llms.txt Removes User-Defined Function (UDF) libraries. `udfDelete` removes a specific named library, while `udfFlush` removes all registered UDF libraries. ```APIDOC ## `db.udfDelete(lib)` and `db.udfFlush()` — Remove UDF libraries `udfDelete` removes a specific named library. `udfFlush` removes all registered UDF libraries at once. ### Parameters #### Path Parameters - **lib** (string) - Required - The name of the UDF library to delete. ### Request Example ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const s1 = `function f1() { return 1; }\nfalkor.register("f1", f1); `; const s2 = `function f2() { return 2; }\nfalkor.register("f2", f2); `; await db.udfLoad('lib1', s1); await db.udfLoad('lib2', s2); // Delete a specific library await db.udfDelete('lib1'); // Flush all remaining libraries await db.udfFlush(); ``` ### Response #### Success Response (200) - (void) - Operation successful. ``` -------------------------------- ### Execute Parameterized Cypher Query (TypeScript) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Execute a Cypher query with parameters and a timeout. The result includes typed data rows and metadata, such as execution time. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('riders'); // Create data await graph.query(` CREATE (:Rider {name:'Valentino Rossi'})-[:rides]->(:Team {name:'Yamaha'}), (:Rider {name:'Dani Pedrosa'})-[:rides]->(:Team {name:'Honda'}), (:Rider {name:'Andrea Dovizioso'})-[:rides]->(:Team {name:'Ducati'}) `); // Parameterized query const result = await graph.query<{ 'r.name': string }>( 'MATCH (r:Rider)-[:rides]->(t:Team) WHERE t.name = $teamName RETURN r.name', { params: { teamName: 'Yamaha' }, TIMEOUT: 3000 } ); console.log(result.data); // [{ 'r.name': 'Valentino Rossi' }] console.log(result.metadata); // ['Cached execution: 0', 'Query internal execution time: 0.123 milliseconds'] await graph.delete(); await db.close(); ``` -------------------------------- ### List FalkorDB UDF Libraries Source: https://context7.com/falkordb/falkordb-ts/llms.txt Retrieve a list of all registered User-Defined Function (UDF) libraries. You can optionally filter the list by a specific library name or include the source code of each UDF in the response. The output format is an array of arrays, where each inner array contains the library name, a list of function names within that library, and optionally the library's source code. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const script = `function hello() { return "world"; }\nfalkor.register("hello", hello); `; await db.udfLoad('mylib', script); // List all UDF libraries const all = await db.udfList(); console.log(all); // [['mylib', ['hello']]] // Filter by library name const filtered = await db.udfList('mylib'); console.log(filtered); // [['mylib', ['hello']]] // Include source code const withCode = await db.udfList(undefined, true); console.log(withCode); // [['mylib', ['hello'], 'function hello() { return "world"; }\nfalkor.register("hello", hello);']] await db.udfDelete('mylib'); await db.close(); ``` -------------------------------- ### Retrieve Slow Query Log with graph.slowLog Source: https://context7.com/falkordb/falkordb-ts/llms.txt Access the slow query log for a graph using `slowLog`. Each entry includes a timestamp, command, query string, and execution time in milliseconds. ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('slowlog_test'); // Run a slow query to generate log entries await graph.query('UNWIND range(0, 200000) AS x RETURN max(x)'); const logs = await graph.slowLog(); for (const entry of logs) { console.log({ timestamp: entry.timestamp, // Date object command: entry.command, // 'GRAPH.QUERY' query: entry.query, // 'UNWIND range(0, 200000) ...' took: entry.took // milliseconds (number) }); } await graph.delete(); await db.close(); ``` -------------------------------- ### Index Management Source: https://context7.com/falkordb/falkordb-ts/llms.txt Functions for creating and dropping various types of indices on nodes and edges. Supports RANGE, FULLTEXT, and VECTOR indices to optimize different query types. ```APIDOC ## Index Management ### Description Functions for creating and dropping indices on node or edge labels for one or more properties. Supports RANGE, FULLTEXT, and VECTOR indices. ### Methods #### Node Indices - **`createNodeRangeIndex(label, ...properties)`**: Creates a RANGE index on a node label. - **`createNodeFulltextIndex(label, ...properties)`**: Creates a FULLTEXT index on a node label. - **`createNodeVectorIndex(label, dimension, distance, ...properties)`**: Creates a VECTOR index on a node label. - **`dropNodeRangeIndex(label, ...properties)`**: Drops a RANGE index from a node label. - **`dropNodeFulltextIndex(label, ...properties)`**: Drops a FULLTEXT index from a node label. - **`dropNodeVectorIndex(label, ...properties)`**: Drops a VECTOR index from a node label. #### Edge Indices - **`createEdgeRangeIndex(label, ...properties)`**: Creates a RANGE index on an edge type. - **`createEdgeFulltextIndex(label, ...properties)`**: Creates a FULLTEXT index on an edge type. - **`createEdgeVectorIndex(label, dimension, distance, ...properties)`**: Creates a VECTOR index on an edge type. - **`dropEdgeRangeIndex(label, ...properties)`**: Drops a RANGE index from an edge type. - **`dropEdgeFulltextIndex(label, ...properties)`**: Drops a FULLTEXT index from an edge type. - **`dropEdgeVectorIndex(label, ...properties)`**: Drops a VECTOR index from an edge type. ### Parameters - **label** (string) - Required - The node label or relationship type. - **properties** (...string) - Required - One or more property names for the index. - **dimension** (number) - Required for VECTOR indices - The dimensionality of the vectors. - **distance** (string) - Required for VECTOR indices - The distance metric (e.g., 'euclidean', 'cosine'). ### Example ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('indexed_graph'); await graph.query(` CREATE (:Article {title: 'Graph databases explained', body: 'FalkorDB is fast...', embedding: [0.1, 0.2, 0.3, 0.4]}), (:Article {title: 'Vector search with FalkorDB', body: 'Using ANN search...', embedding: [0.5, 0.6, 0.7, 0.8]}) `); // RANGE index for equality/range queries await graph.createNodeRangeIndex('Article', 'title'); // FULLTEXT index for text search await graph.createNodeFulltextIndex('Article', 'body'); // VECTOR index for similarity search (4-dim, euclidean distance) await graph.createNodeVectorIndex('Article', 4, 'euclidean', 'embedding'); // RANGE index on edge property await graph.query("MATCH (a:Article), (b:Article) WHERE a <> b CREATE (a)-[:RELATED {score: 0.9}]->(b)"); await graph.createEdgeRangeIndex('RELATED', 'score'); // Verify all indices const indices: any = await graph.roQuery('CALL db.indexes() YIELD label, properties, types, entitytype RETURN *'); console.log(indices.data); // Drop indices await graph.dropNodeRangeIndex('Article', 'title'); await graph.dropNodeFulltextIndex('Article', 'body'); await graph.dropNodeVectorIndex('Article', 'embedding'); await graph.dropEdgeRangeIndex('RELATED', 'score'); await graph.delete(); await db.close(); ``` ``` -------------------------------- ### db.close() Source: https://context7.com/falkordb/falkordb-ts/llms.txt Gracefully disconnects from FalkorDB, ensuring all pending commands are flushed before closing the connection. ```APIDOC ## `db.close()` — Close the connection ### Description Gracefully disconnects from FalkorDB, flushing any pending commands. ### Method POST ### Endpoint `/close` ### Request Example ```typescript await db.close(); ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful disconnection. ### Response Example ```json { "message": "Connection closed successfully." } ``` ``` -------------------------------- ### graph.roQuery(query, options?) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Executes a read-only Cypher query. This is useful for routing read operations to replica nodes in cluster deployments and will throw an error if a write operation is attempted. ```APIDOC ## graph.roQuery(query, options?) ### Description Executes a read-only Cypher query. Throws if a write operation (CREATE, SET, DELETE, etc.) is attempted. Useful for routing reads to replica nodes in cluster deployments. ### Method `graph.roQuery(query, options?)` ### Parameters #### Path Parameters - **query** (string) - Required - The Cypher query to execute. - **options** (object) - Optional - Additional options for the query. ### Request Example ```typescript const result = await graph.roQuery<{ name: string; age: number }>( 'MATCH (n:Person) RETURN n.name AS name, n.age AS age ORDER BY n.age' ); ``` ### Response #### Success Response (200) - **data** (Array) - The results of the query. - **errors** (Array) - Any errors encountered during query execution. ### Response Example ```json { "data": [ { "name": "Bob", "age": 25 }, { "name": "Alice", "age": 30 } ], "errors": [] } ``` ``` -------------------------------- ### graph.slowLog() Source: https://context7.com/falkordb/falkordb-ts/llms.txt Retrieves the slow query log for the graph, providing details such as timestamp, command, query string, and execution time in milliseconds for each entry. ```APIDOC ## graph.slowLog() ### Description Returns the slow query log entries for the graph, each with a timestamp, command, query string, and execution time in milliseconds. ### Method `graph.slowLog()` ### Request Example ```typescript const logs = await graph.slowLog(); ``` ### Response #### Success Response (200) - **logs** (Array) - An array of objects, where each object represents a slow query log entry. - **timestamp** (Date) - The timestamp when the query was executed. - **command** (string) - The command that was executed (e.g., 'GRAPH.QUERY'). - **query** (string) - The slow query string. - **took** (number) - The execution time in milliseconds. ### Response Example ```json [ { "timestamp": "2023-10-27T10:00:00.000Z", "command": "GRAPH.QUERY", "query": "UNWIND range(0, 200000) AS x RETURN max(x)", "took": 1500 } ] ``` ``` -------------------------------- ### db.selectGraph(graphId) Source: https://context7.com/falkordb/falkordb-ts/llms.txt Returns a `Graph` instance bound to the specified graph name. This operation is lazy and does not make a network call until a write query is executed. ```APIDOC ## db.selectGraph(graphId) ### Description Returns a `Graph` instance bound to the specified graph name. No network call is made; graphs are created lazily on first write query. ### Method `db.selectGraph(graphId)` ### Parameters - **graphId** (`string`) - The unique identifier for the graph. ### Request Example ```typescript import { FalkorDB } from 'falkordb'; const db = await FalkorDB.connect({ socket: { host: 'localhost', port: 6379 } }); const graph = db.selectGraph('social'); // Create nodes and relationships await graph.query(` CREATE (:Person {name: 'Alice', age: 30})-[:KNOWS {since: 2020}]->(:Person {name: 'Bob', age: 25}) `); await db.close(); ``` ### Response - **Graph Instance** - A `Graph` object representing the selected graph. ```