### TCP/Redis Connection Examples Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Examples of TCP/Redis connection URLs, demonstrating host and port specification. ```text falkor://127.0.0.1:6379 falkor://db.example.com:6379 ``` -------------------------------- ### Explain and Profile Queries Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/INDEX.md Use `.explain()` to get the query plan or `.profile()` to get execution statistics for a query. Both require subsequent execution. ```rust graph.explain(...).execute()? graph.profile(...).execute()? ``` -------------------------------- ### Install Prometheus Metrics Exporter Source: https://github.com/falkordb/falkordb-rs/blob/main/README.md Install a metrics recorder, such as Prometheus, to start exporting metrics. Metrics are exported on the configured endpoint after installation. ```rust let builder = metrics_exporter_prometheus::PrometheusBuilder::new(); builder.install().expect("failed to install Prometheus recorder"); // ... use the client; metrics are now exported on the configured endpoint. ``` -------------------------------- ### Reproduce CI Job: Build Examples Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `check-examples` CI job using the `just build-examples` recipe. ```bash just build-examples ``` -------------------------------- ### Start FalkorDB Server Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Start a FalkorDB Docker container and wait until it is ready. This is a prerequisite for server-backed tests, coverage, and benchmarks if not using `*-local` recipes. ```bash just db-up ``` -------------------------------- ### Install and Regenerate README.md Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Install the `cargo-rdme` tool and use the `just readme` command to regenerate the `README.md` file from the crate-level documentation. Use `just check-readme` to verify the README is up-to-date. ```bash cargo install cargo-rdme --version 2.0.0 # one-time; pinned to match CI (scripts/install-cargo-rdme.sh) just readme # regenerate README.md from the crate docs just check-readme # drift gate: fails if the committed README.md is stale ``` -------------------------------- ### Redis Sentinel Connection Examples Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Examples of Redis Sentinel connection URLs, including multiple sentinels and optional password. ```text sentinel://sentinel1:26379,sentinel2:26379/mymaster sentinel://sentinel1:26379/mymaster?password=secret ``` -------------------------------- ### Unix Domain Socket Connection Example Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Example of a Unix domain socket connection URL. ```text unix:///var/run/redis.sock ``` -------------------------------- ### Pre-built Query Batch Example Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/batch-and-procedures.md Shows how to prepare a list of queries, potentially including read and write operations, and then execute them as a single batch. ```APIDOC ## Pre-built Query Batch This example demonstrates preparing a list of queries and executing them as a batch. ### Code Example ```rust let queries = vec![ BatchQuery::write("CREATE (:Event {date: $d})"), BatchQuery::write("CREATE (:Event {date: $d})"), BatchQuery::read("MATCH (e:Event) RETURN e"), ]; let mut batch = graph.batch(); batch.push(queries[0].clone()).with_param("d", "2024-06-30"); batch.push(queries[1].clone()).with_param("d", "2024-07-01"); batch.push(queries[2].clone()); let results = batch.execute()?; ``` ``` -------------------------------- ### Embedded FalkorDB Client Configuration Example Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Demonstrates how to configure and build a FalkorDB client using an embedded server. Shows both auto-download and offline configurations. ```rust use falkordb::{FalkorClientBuilder, FalkorConnectionInfo, EmbeddedConfig}; // Auto-download and cache let embedded = EmbeddedConfig::default(); // Or fully offline with pre-installed binary let offline = EmbeddedConfig { auto_download: false, falkordb_module_path: Some("/path/to/falkordb.so".into()), ..Default::default() }; let client = FalkorClientBuilder::new() .with_connection_info(FalkorConnectionInfo::Embedded(offline)) .build()?; ``` -------------------------------- ### Install tracing feature for FalkorDB Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Install the tracing feature for the falkordb crate to enable OpenTelemetry-aligned observability with structured tracing spans. ```bash cargo add falkordb --features tracing ``` -------------------------------- ### Install metrics feature for FalkorDB Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Install the metrics feature for the falkordb crate to enable Prometheus/OpenTelemetry metrics emission via the `metrics` facade. ```bash cargo add falkordb --features metrics ``` -------------------------------- ### Add FalkorDB Client for High-Availability Setup Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Use this command to add the FalkorDB crate for a high-availability setup. This configuration includes an async client, Sentinel routing, and observability features, along with metrics for monitoring. A connection to a Sentinel endpoint is also required. ```bash cargo add falkordb --features tokio,metrics,tracing # Plus connection to Sentinel endpoint ``` -------------------------------- ### Run FalkorDB Benchmarks Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Commands to start a FalkorDB server for benchmarking, run the full benchmark suite, execute a single benchmark case, and clean up the server. ```bash # Start a server (configure with FALKORDB_HOST / FALKORDB_PORT; defaults to 127.0.0.1:6379) docker run -d --name falkordb-bench -p 6379:6379 falkordb/falkordb:latest # Run the full benchmark suite cargo bench --features tokio --bench async_strategies # Run a single case (criterion accepts a filter on the benchmark id) cargo bench --features tokio --bench async_strategies -- 'async_read_throughput/multiplexed_8/8' # Clean up docker stop falkordb-bench && docker rm falkordb-bench ``` -------------------------------- ### Install tokio feature for FalkorDB Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Install the tokio feature for the falkordb crate to enable asynchronous client and APIs. This requires a multi-threaded tokio runtime. ```bash cargo add falkordb --features tokio ``` -------------------------------- ### Embedded FalkorDB Usage Example Source: https://github.com/falkordb/falkordb-rs/blob/main/blog/content/posts/05-embedded-server.md This example demonstrates how to use the embedded FalkorDB server. The usage remains identical regardless of how the module is sourced, with differences only in the `EmbeddedConfig`. ```rust use falkordb::falkordb_rs::FalkorDB; #[tokio::main] async fn main() { // Use the default configuration to embed FalkorDB. // This will auto-download the module if not found, and use redis-server from PATH. let db = FalkorDB::new().await.unwrap(); // You can also configure the embedded server: // let config = EmbeddedConfig { // // Specify a path to a local FalkorDB module file. // module_path: Some("/path/to/falkordb.so"), // // Disable auto-downloading the module. // auto_download: false, // // Specify a custom redis-server path. // redis_server_path: Some("/usr/local/bin/redis-server"), // // Set a custom port for the embedded server. // port: Some(12345), // }; // let db = FalkorDB::with_config(config).await.unwrap(); // Now you can use the `db` client as usual. let res = db.execute("PING").await.unwrap(); println!("PING response: {}", res); // The embedded server will be shut down automatically when `db` is dropped. // Explicitly dropping `db` here to show the shutdown. drop(db); println!("Embedded server shut down."); } ``` -------------------------------- ### Bulk Insert Example Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/batch-and-procedures.md Demonstrates how to perform a bulk insert of multiple items into the database using a batch. Each item is inserted as a separate query within the batch. ```APIDOC ## Bulk Insert This example shows how to create multiple records in a single batch operation. ### Code Example ```rust let items = vec!["Alice", "Bob", "Charlie"]; let mut batch = graph.batch(); for (i, name) in items.iter().enumerate() { batch.query("CREATE (:Person {name: $n})") .with_param("n", name); } let results = batch.execute()?; for (i, result) in results.iter().enumerate() { if let Err(e) = result { eprintln!("Insert {}: {}", i, e); } } ``` ``` -------------------------------- ### Batch Query Execution Example Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-graph.md Shows how to queue multiple mutable and read-only queries using BatchBuilder, add parameters, and then execute the batch. It iterates through the results, printing statistics or errors for each query. ```rust let mut batch = graph.batch(); batch.query("CREATE (:Person {name: $n})").with_param("n", "Alice"); batch.query("CREATE (:Person {name: $n})").with_param("n", "Bob"); batch.ro_query("MATCH (p:Person) RETURN count(p) AS count"); let results = batch.execute()?; for (i, result) in results.into_iter().enumerate() { match result { Ok(res) => println!("Query {}: {:?}", i, res.stats), Err(e) => eprintln!("Query {} failed: {}", i, e), } } ``` -------------------------------- ### Configure tracing for FalkorDB client Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Example of initializing the tracing subscriber and building a FalkorDB client with query logging disabled for privacy. Queries will emit INFO-level spans. ```rust use tracing_subscriber; tracing_subscriber::fmt() .with_max_level(tracing::Level::INFO) .init(); let client = falkordb::FalkorClientBuilder::new() .with_query_logging(false) // Privacy-safe by default .build()?; // Queries now emit INFO-level spans with structured fields ``` -------------------------------- ### Install serde feature for FalkorDB Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Install the serde feature for the falkordb crate to enable deserialization of query results into custom Rust types. ```bash cargo add falkordb --features serde ``` -------------------------------- ### Run Resource Usage Benchmarks Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Commands to start a FalkorDB server, run the resource usage benchmark suite, and clean up the server. This benchmark measures peak memory and CPU time. ```bash docker run -d --name falkordb-bench -p 6379:6379 falkordb/falkordb:latest cargo bench --features tokio --bench resource_usage docker stop falkordb-bench && docker rm falkordb-bench ``` -------------------------------- ### Create a new BatchBuilder Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/batch-and-procedures.md Instantiate a new, empty batch builder for accumulating queries. This is the starting point for building a batch of operations. ```rust let mut batch = graph.batch(); ``` -------------------------------- ### Get Query Execution Plan Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-graph.md Use `explain` to retrieve the execution plan of a Cypher query without actually running it. Parameters can be set before execution. ```rust pub fn explain(&self, cypher: &str) -> QueryBuilder ``` ```rust let mut plan = graph.explain("MATCH (n) WHERE n.id > 100 RETURN n") .execute()?; println!("{:?}", plan.data.next()?); ``` -------------------------------- ### End-to-End Local Testing with Managed Server Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Run tests, coverage, or benchmarks with a FalkorDB server managed automatically. This recipe handles starting the DB, populating it, running the task, and tearing down the server. ```bash # Or let a single recipe manage the container lifecycle end-to-end. just test-local # start DB, populate, run the full suite, tear down just coverage-local # same, but produce Codecov JSON just bench-local # start DB, run all benchmarks, tear down ``` -------------------------------- ### Explain Query Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/INDEX.md Get an explanation of a query's execution plan. ```APIDOC ## Explain Query ### Description Get an explanation of a query's execution plan. ### Method ```rust graph.explain(...).execute()? ``` ``` -------------------------------- ### Install FalkorDB with Tokio Native TLS Async Feature Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Add 'tokio' and 'tokio-native-tls' features for asynchronous TLS support using the system's native TLS library. Requires the 'tokio' runtime. ```bash cargo add falkordb --features tokio,tokio-native-tls ``` -------------------------------- ### Duration Arithmetic Example Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/types.md Shows how to perform addition of durations with overflow checking and access the total seconds component. ```rust pub fn seconds(&self) -> Seconds pub fn add(rhs: Self) -> FalkorResult pub fn checked_add, checked_sub, checked_neg() ``` -------------------------------- ### Collecting Whole Result Set (Before 0.7) Source: https://github.com/falkordb/falkordb-rs/blob/main/docs/migrating-to-0.7.md Example of collecting all query results into a Vec> before version 0.7. ```rust let rows: Vec> = result.data.collect(); ``` -------------------------------- ### DateTime Arithmetic Example Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/types.md Demonstrates performing arithmetic operations on DateTime objects, such as subtraction to yield a Duration, and adding or subtracting durations. ```rust let dt1: DateTime = ...; let dt2: DateTime = ...; // Subtraction yields Duration let duration: Duration = dt1 - dt2; // Add/subtract duration let later = dt1.checked_add(duration)?; let earlier = dt1.checked_sub(duration)?; ``` -------------------------------- ### Basic FalkorDB Client Usage in Rust Source: https://github.com/falkordb/falkordb-rs/blob/main/blog/content/posts/01-why-rust.md Demonstrates connecting to FalkorDB, executing a query, and iterating over typed results. This example showcases the absence of manual string escaping and type-unsafe data handling. ```rust use falkordb::{Client, Query}; #[tokio::main] async fn main() -> Result<(), Box> { let mut client = Client::connect("localhost:20003", "password") .await?; // Example query let query = Query::Cypher("RETURN 1 as single_value"); let mut stream = client.execute(query).await?; // Iterate over results while let Some(row) = stream.next().await? { let value: i32 = row.get("single_value")?; println!("Query result: {}", value); } Ok(()) } ``` -------------------------------- ### Install FalkorDB with Tokio Rustls Async TLS Feature Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Add 'tokio' and 'tokio-rustls' features for asynchronous TLS support with Rustls. Requires the 'tokio' runtime. ```bash cargo add falkordb --features tokio,tokio-rustls ``` -------------------------------- ### Run FalkorDB Server with Docker Source: https://github.com/falkordb/falkordb-rs/blob/main/README.md Start a FalkorDB server instance using Docker. This command maps the default FalkorDB port (6379) to your host machine. ```bash docker run --rm -p 6379:6379 falkordb/falkordb ``` -------------------------------- ### Async FalkorDB client usage with tokio Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Example of building and using an asynchronous FalkorDB client with the tokio runtime. Ensure a multi-threaded tokio runtime is active. ```rust #[tokio::main(flavor = "multi_thread")] async fn main() -> falkordb::FalkorResult<()> { let client = falkordb::FalkorClientBuilder::new_async() .with_connection_info("falkor://localhost:6379".try_into()?) .build() .await?; // Use async client Ok(()) } ``` -------------------------------- ### Add FalkorDB with Tokio and Serde Features Source: https://github.com/falkordb/falkordb-rs/blob/main/README.md Install the FalkorDB crate with specific Cargo features enabled. 'tokio' enables the async client for the Tokio runtime, and 'serde' allows mapping query results to custom types. ```bash cargo add falkordb --features tokio,serde ``` -------------------------------- ### FalkorClientBuilder::new() Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Creates a new builder for a synchronous (blocking) FalkorDB client with default settings. This is the starting point for configuring a sync client. ```APIDOC ## FalkorClientBuilder::new() ### Description Creates a new builder for a synchronous (blocking) client with default configuration. ### Method `new()` ### Returns `FalkorClientBuilder` - A new `FalkorClientBuilder` configured for sync operations. ### Example ```rust use falkordb::FalkorClientBuilder; let builder = FalkorClientBuilder::new(); ``` ``` -------------------------------- ### Get Mitigation Hint for Errors Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/errors.md Provides a short, actionable hint for common errors. Use this to guide remediation efforts when an error occurs. ```rust pub fn mitigation_hint(&self) -> Option<&'static str> ``` ```rust if let Some(hint) = error.mitigation_hint() { eprintln!("Tip: {}", hint); } ``` -------------------------------- ### FalkorSyncClient::connection_strategy Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Returns the effective connection strategy being used by the client. This might differ from the initially requested strategy if, for example, a Sentinel setup influences the connection method. ```APIDOC ## FalkorSyncClient::connection_strategy ### Description Returns the effective connection strategy (may differ from requested if Sentinel). ### Method `connection_strategy` ### Signature `pub fn connection_strategy(&self) -> ConnectionStrategy` ### Returns - **ConnectionStrategy** - The active connection strategy. ### Example ```rust let strategy = client.connection_strategy(); ``` ``` -------------------------------- ### Run Integration Tests Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Execute integration tests that require a running FalkorDB instance. Tests can be run using the provided script, or manually by starting FalkorDB with Docker and then running cargo tests. The `--features tokio` flag enables async support. Remember to clean up the Docker container afterwards. ```bash ./run_integration_tests.sh ``` ```bash docker run -d --name falkordb-test -p 6379:6379 falkordb/falkordb:latest cargo test --test integration_tests ``` ```bash cargo test --test integration_tests --features tokio ``` ```bash docker stop falkordb-test && docker rm falkordb-test ``` -------------------------------- ### Default EmbeddedConfig (Runtime Download) Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Creates a default configuration that automatically downloads and caches the FalkorDB module on first start. Reuses cached modules on subsequent runs. ```rust let config = EmbeddedConfig::default(); // Downloads and caches module on first start // Reuses cached module on subsequent runs ``` -------------------------------- ### Reproduce CI Job: Documentation Build Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `check-doc` CI job using the `just doc` recipe. ```bash just doc ``` -------------------------------- ### Fast Development Loop: Format, Lint, Build Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Run a quick check of your code's formatting, linting, and build status without needing a running FalkorDB server. ```bash # Fast inner loop (no server needed): format, lint and build. just check ``` -------------------------------- ### Reproduce CI Job: Build Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `check-build` CI job using the `just build` recipe. ```bash just build ``` -------------------------------- ### Create Index and Wait for Completion Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/README.md Shows how to initiate an index creation operation and explicitly wait for its completion, with a specified timeout. ```rust use std::time::Duration; graph.create_index_op(IndexType::Range, EntityType::Node, "User", &["email"], None) .wait_with(WaitOptions::with_timeout(Duration::from_secs(60)))?; ``` -------------------------------- ### Get Actionable Error Hints Source: https://github.com/falkordb/falkordb-rs/blob/main/README.md Use the mitigation_hint() method on FalkorDBError to get a short, actionable remediation tip for common failures. Unrecognized errors return None. ```rust use falkordb::FalkorDBError; let err = FalkorDBError::ConnectionDown; if let Some(hint) = err.mitigation_hint() { println!("hint: {hint}"); } ``` -------------------------------- ### Profile Query Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/INDEX.md Get profiling information for a query's execution. ```APIDOC ## Profile Query ### Description Get profiling information for a query's execution. ### Method ```rust graph.profile(...).execute()? ``` ``` -------------------------------- ### List Available Just Recipes Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Use this command to see all available development tasks managed by the `just` runner. ```bash just # or: just --list ``` -------------------------------- ### Batch Multiple Queries for Execution Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/README.md Illustrates how to queue multiple queries within a batch and execute them together, then process the results for each query. ```rust let mut batch = graph.batch(); for movie in &movie_titles { batch.query("CREATE (:Movie {title: $t})").with_param("t", movie); } let results = batch.execute()?; for (i, result) in results.into_iter().enumerate() { println!("Query {}: {:?}", i, result?); } ``` -------------------------------- ### SyncGraph.ro_query Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-graph.md Starts building a read-only Cypher query using GRAPH.RO_QUERY. The server refuses to execute writes with this method. ```APIDOC ## SyncGraph.ro_query ### Description Starts building a read-only Cypher query using GRAPH.RO_QUERY. The server refuses to execute writes with this method. ### Method ```rust pub fn ro_query(&self, cypher: &str) -> QueryBuilder ``` ### Parameters #### Path Parameters - **cypher** (string) - Required - Read-only Cypher query ### Response #### Success Response - **QueryBuilder** - Chainable builder ### Request Example ```rust let mut result = graph.ro_query("MATCH (n) RETURN count(n)") .execute()?; ``` ``` -------------------------------- ### Reproduce CI Job: README Check Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `check-readme` CI job using the `just check-readme` recipe. ```bash just check-readme ``` -------------------------------- ### SyncGraph.batch Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-graph.md Starts building a batch of queries to execute in a single Redis pipeline. This allows for multiple operations in one round-trip. ```APIDOC ## SyncGraph.batch ### Description Starts building a batch of queries to execute in a single Redis pipeline. This allows for multiple operations in one round-trip. ### Method ```rust pub fn batch(&self) -> BatchBuilder ``` ### Response #### Success Response - **BatchBuilder** - Accumulates queries before execution ### Request Example ```rust let mut batch = graph.batch(); batch.query("CREATE (:Movie {title: $t})").with_param("t", "Inception"); batch.query("CREATE (:Movie {title: $t})").with_param("t", "Interstellar"); let results = batch.execute()?; // Both in one round-trip ``` ``` -------------------------------- ### Connect and Query FalkorDB Source: https://github.com/falkordb/falkordb-rs/blob/main/README.md Connect to a FalkorDB server, select a graph, create nodes, and retrieve them using a query. Demonstrates basic client interaction and query execution. ```rust use falkordb::{FalkorClientBuilder, FalkorConnectionInfo}; // Connect to FalkorDB let connection_info: FalkorConnectionInfo = "falkor://127.0.0.1:6379".try_into() .expect("Invalid connection info"); let client = FalkorClientBuilder::new() .with_connection_info(connection_info) .build() .expect("Failed to build client"); // Select the social graph let mut graph = client.select_graph("social"); // Create 100 nodes and return a handful let mut nodes = graph.query("UNWIND range(1, 100) AS i CREATE (n { v:1 }) RETURN n LIMIT 10") .with_timeout(5000) .execute() .expect("Failed executing query"); // Each item is a `FalkorResult`; read columns by index or name. while let Some(row) = nodes.data.next() { let row = row.expect("row failed to parse"); println!("{:?}", row.get_at(0)); } ``` -------------------------------- ### SyncGraph.query Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-graph.md Starts building a mutable Cypher query that may read or write. This method is used for general query execution. ```APIDOC ## SyncGraph.query ### Description Starts building a mutable Cypher query that may read or write. This method is used for general query execution. ### Method ```rust pub fn query(&self, cypher: &str) -> QueryBuilder ``` ### Parameters #### Path Parameters - **cypher** (string) - Required - Cypher query string with optional $param placeholders ### Response #### Success Response - **QueryBuilder** - Chainable query builder for setting parameters, timeout, and executing ### Request Example ```rust let mut result = graph.query("CREATE (:Person {name: $name})") .with_param("name", "Alice") .execute()?; ``` ``` -------------------------------- ### Reproduce CI Job: Tokio Integration Tests Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `integration-tests-tokio` CI job using `just integration --features tokio`. ```bash just integration --features tokio ``` -------------------------------- ### RowStream Async Iteration Example Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/types.md Demonstrates how to asynchronously iterate over rows using the RowStream with the `tokio` feature. Requires the `futures` crate. ```rust use futures::StreamExt; while let Some(row) = stream.next().await { let row = row?; } ``` -------------------------------- ### Run Full Validation (Server-Backed) Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Execute all CI gates, including the server-backed test suite. Requires a FalkorDB instance, which can be managed by `just db-up` or `*-local` wrappers. ```bash just verify ``` -------------------------------- ### Mitigation Hint on Error Source: https://github.com/falkordb/falkordb-rs/blob/main/docs/llms.template.md Access a mitigation hint from a `FalkorDBError` to get actionable remediation advice. The raw error is always preserved. ```rust if let Err(err) = result { if let Some(hint) = err.mitigation_hint() { println!("Mitigation: {}", hint); } } ``` -------------------------------- ### Build FalkorDB Client Source: https://github.com/falkordb/falkordb-rs/blob/main/docs/llms.template.md Instantiate a FalkorDB client and select a graph handle. This is the initial step for interacting with the database. ```rust let client = FalkorClientBuilder::new().build()?; let mut graph = client.select_graph("g"); ``` -------------------------------- ### Read Preference Configuration Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Configure which node serves read-only queries in a Sentinel setup. Options include Primary (default) and PreferReplica. ```APIDOC ## Read Preference Controls which node serves read-only queries in a Sentinel setup. ```rust pub enum ReadPreference { /// All reads go to the primary (default, strongest consistency) Primary, /// Try replicas first, fall back to primary if unavailable PreferReplica, } ``` **Default:** `ReadPreference::Primary` (no replication lag) **Usage:** ```rust // Per-client default let client = FalkorClientBuilder::new() .with_read_preference(ReadPreference::PreferReplica) .build()?; // Per-query override let mut result = graph .ro_query("MATCH (n) RETURN n") .prefer_replica() .execute()?; let mut fresh = graph .ro_query("MATCH (n) RETURN n") .primary_only() // Force primary despite client default .execute()?; ``` ``` -------------------------------- ### Create Index Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/INDEX.md Create an index on the graph. `create_index()` returns immediately, while `create_index_op().wait()` blocks until the index is ready. ```rust graph.create_index(...)? graph.create_index_op(...).wait()? ``` -------------------------------- ### Install FalkorDB with Embedded Feature Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Add the 'embedded' feature to your FalkorDB dependency to enable in-process server execution with runtime module download. ```bash cargo add falkordb --features embedded ``` -------------------------------- ### Build and Use Embedded FalkorDB Client Source: https://github.com/falkordb/falkordb-rs/blob/main/README.md Demonstrates building a FalkorDB client with an embedded configuration and executing a sample query. The embedded server shuts down automatically when the client is dropped. ```rust use falkordb::{EmbeddedConfig, FalkorClientBuilder, FalkorConnectionInfo}; use std::path::PathBuf; // Create an embedded configuration with defaults let embedded_config = EmbeddedConfig::default(); // Or customize the configuration: // let embedded_config = EmbeddedConfig { // redis_server_path: Some(PathBuf::from("/path/to/redis-server")), // falkordb_module_path: Some(PathBuf::from("/path/to/falkordb.so")), // db_dir: Some(PathBuf::from("/tmp/my_falkordb")), // falkordb_version: None, // pin a different release, e.g. Some("v4.18.10".into()) // cache_dir: None, // override the download cache location // ..Default::default() // }; // Build a client with embedded FalkorDB let client = FalkorClientBuilder::new() .with_connection_info(FalkorConnectionInfo::Embedded(embedded_config)) .build() .expect("Failed to build client"); // Use the client normally let mut graph = client.select_graph("social"); graph.query("CREATE (:Person {name: 'Alice', age: 30})").execute().expect("Failed to execute query"); // The embedded server will be automatically shut down when the client is dropped ``` -------------------------------- ### build (sync) Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Builds and returns a synchronous FalkorDB client with the currently configured settings. Handles potential connection errors. ```APIDOC ## build() -> FalkorResult ### Description Builds the synchronous client with the configured settings. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Not applicable (Rust method) ### Endpoint Not applicable (Rust method) ### Returns `FalkorResult` - The connected client or an error ### Throws - `FalkorDBError::InvalidConnectionInfo` - Connection info is malformed - `FalkorDBError::NoConnection` - Cannot connect to server - `FalkorDBError::UnavailableProvider` - Required TLS feature not enabled ### Example ```rust use falkordb::FalkorClientBuilder; let client = FalkorClientBuilder::new() .with_connection_info("falkor://localhost:6379".try_into().unwrap()) .build()?; ``` ``` -------------------------------- ### Get Read Preference using FalkorSyncClient Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Retrieves the default read preference configured for the FalkorDB client. This dictates where read operations are directed. ```rust pub fn read_preference(&self) -> ReadPreference ``` -------------------------------- ### Get Connection Pool Size using FalkorSyncClient Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Returns the current number of active connections maintained by the client's connection pool. ```rust pub fn connection_pool_size(&self) -> usize ``` -------------------------------- ### ReadPreference Enum Definition Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Defines the available read preferences for directing read-only queries in a Sentinel setup. Defaults to `Primary` for strongest consistency. ```rust pub enum ReadPreference { /// All reads go to the primary (default, strongest consistency) Primary, /// Try replicas first, fall back to primary if unavailable PreferReplica, } ``` -------------------------------- ### Reproduce CI Job: Coverage Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `coverage` CI job using the `just coverage` recipe. ```bash just coverage ``` -------------------------------- ### RedisError Variant with Examples Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/errors.md Wraps errors originating from the underlying Redis communication. The message string contains details about the specific Redis error encountered. ```rust #[error("An error occurred while sending the request to Redis: {0}")] RedisError(String), ``` ```text "ERR Code: 1, db.idx.fulltext.createNodeIndex: errmsg: syntax error at offset 3 line: 1 column: 4" "[NOCONTENT] Unique constraint FAILED" "[READONLY] You can't write against a replica" "Graph 'social' is empty or not created, key doesn't contain a graph" ``` -------------------------------- ### Reproduce CI Job: Format Check Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `check-fmt` CI job using the `just fmt-check` recipe. ```bash just fmt-check ``` -------------------------------- ### Call Read-Only FalkorDB Procedure Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/batch-and-procedures.md Execute a read-only FalkorDB procedure, ensuring no modifications are made to the database. This example shows querying a full-text index. ```rust let mut result = graph.call_procedure_ro("db.idx.fulltext.queryNodes($index, $query)") .with_param("index", "article_idx") .with_param("query", "machine learning") .execute()?; ``` -------------------------------- ### Batch Execution with Procedures Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/batch-and-procedures.md This snippet shows how to include both regular queries and procedure calls within a single batch for atomic execution. It creates a document and then creates a full-text index. ```rust let mut batch = graph.batch(); batch.query("CREATE (:Document {title: $t})") .with_param("t", "New Article"); batch.call_procedure("db.idx.fulltext.createNodeIndex($l, $p)") .with_param("l", "Document") .with_param("p", vec!["title"]); let results = batch.execute()?; ``` -------------------------------- ### Reproduce CI Job: Property-Based Testing Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `check-proptest` CI job using the `just proptest` recipe. ```bash just proptest ``` -------------------------------- ### Export FalkorDB metrics with Prometheus Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Example of setting up the Prometheus exporter and building a FalkorDB client. Metrics will be exported on the default Prometheus endpoint (:9090/metrics). ```rust use metrics_exporter_prometheus; let builder = metrics_exporter_prometheus::PrometheusBuilder::new(); builder .install() .expect("failed to install Prometheus exporter"); let client = falkordb::FalkorClientBuilder::new().build()?; // Metrics now exported on default Prometheus endpoint (:9090/metrics) ``` -------------------------------- ### Configure Direct Redis Connection Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Set up a direct connection to a Redis instance using connection info and pool size. ```rust let client = FalkorClientBuilder::new() .with_connection_info("falkor://localhost:6379".try_into()?) .with_num_connections(NonZeroU8::new(4).unwrap()) .build()?; ``` -------------------------------- ### Create Index with Operation Builder Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-graph.md Provides an IndexOpBuilder to create indexes, allowing for explicit control over waiting for the index to become operational. Use `.execute()` for fire-and-forget behavior or `.wait()` to block until the index is ready. ```rust pub fn create_index_op( &self, index_type: IndexType, entity_type: EntityType, label_or_type: &str, properties: &[&str], options: Option> ) -> IndexOpBuilder ``` ```rust // Fire-and-forget (same as create_index) graph.create_index_op(IndexType::Range, EntityType::Node, "Person", &["age"], None) .execute()?; ``` ```rust // Wait for index to become operational (30s timeout by default) graph.create_index_op(IndexType::Range, EntityType::Node, "Person", &["name"], None) .wait()?; ``` ```rust // Custom timeout graph.create_index_op(IndexType::Fulltext, EntityType::Node, "Article", &["body"], None) .wait_with(WaitOptions::with_timeout(Duration::from_secs(60)))?; ``` -------------------------------- ### FalkorSyncClient::replica_reads_available Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Checks if the FalkorDB setup includes readable replicas that can be used for read operations. This is particularly relevant in high-availability configurations using Sentinel. ```APIDOC ## FalkorSyncClient::replica_reads_available ### Description Checks if readable replicas are available (requires Sentinel setup). ### Method `replica_reads_available` ### Signature `pub fn replica_reads_available(&self) -> bool` ### Returns - **bool** - `true` if readable replicas are available, `false` otherwise. ### Example ```rust if client.replica_reads_available() { println!("Readable replicas are available."); } ``` ``` -------------------------------- ### Check Replica Reads Availability using FalkorSyncClient Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Determines if the FalkorDB server has readable replicas available, which is typically configured via a Sentinel setup. ```rust pub fn replica_reads_available(&self) -> bool ``` -------------------------------- ### Install FalkorDB with Embedded Bundle Feature Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Add the 'embedded-bundle' feature to your FalkorDB dependency to bundle the FalkorDB module directly into your binary for fully offline runtime. ```bash cargo add falkordb --features embedded-bundle ``` -------------------------------- ### UnavailableProvider Error Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/errors.md Indicates that the requested database provider is unavailable because the necessary feature is not enabled. Enable the required Cargo feature, for example, `tokio`, `rustls`, or `embedded`. ```rust #[error("The provided URL scheme points at a database provider that is currently unavailable, make sure the correct feature is enabled")] UnavailableProvider, ``` ```bash cargo add falkordb --features tokio,rustls,embedded ``` -------------------------------- ### build (async) Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Asynchronously builds and returns a FalkorDB client. This method must be awaited and handles potential connection errors. ```APIDOC ## build() -> Future> ### Description Asynchronously builds the client. Must be awaited. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Not applicable (Rust method) ### Endpoint Not applicable (Rust method) ### Returns `Future>` - The connected client or an error ### Example ```rust use falkordb::FalkorClientBuilder; let client = FalkorClientBuilder::new_async() .with_connection_info("falkor://localhost:6379".try_into().unwrap()) .build() .await?; ``` ``` -------------------------------- ### Batch Query with Conditions Example Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/batch-and-procedures.md Illustrates executing multiple read-only queries within a single batch, including queries with conditional clauses and aggregate functions. ```APIDOC ## Batch Query with Conditions This example demonstrates executing multiple read queries in a batch, including conditional logic and counting results. ### Code Example ```rust let mut batch = graph.batch(); batch.ro_query("MATCH (p:Person) WHERE p.age > $min RETURN count(p)") .with_param("min", 18); batch.ro_query("MATCH (p:Person) WHERE p.age <= $min RETURN count(p)") .with_param("min", 18); batch.ro_query("MATCH (p:Person) RETURN count(p)"); let results = batch.execute()?; let [adults, minors, total] = [ results[0].as_ref()?.data[0].try_get_at::(0)?, results[1].as_ref()?.data[0].try_get_at::(0)?, results[2].as_ref()?.data[0].try_get_at::(0)?, ]; println!("Adults: {}, Minors: {}, Total: {}", adults, minors, total); ``` ``` -------------------------------- ### Reproduce CI Job: Doctest Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `check-doctest` CI job using the `just doctest` recipe. ```bash just doctest ``` -------------------------------- ### Full Validation with Server-Backed Test Suite Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Perform a complete validation that includes running the test suite against a managed FalkorDB Docker instance. This recipe handles spinning up the server, populating data, running tests, and tearing down. ```bash # Full validation including the server-backed test suite (manages Docker for you): # spins up FalkorDB, populates the fixture, runs the suite, tears it down. just verify ``` -------------------------------- ### Reproduce CI Job: Integration Tests Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `integration-tests` CI job using `just integration` or `just integration --all-features`. ```bash just integration and just integration --all-features ``` -------------------------------- ### Mapping and Collecting Async Results (0.8 and later) Source: https://github.com/falkordb/falkordb-rs/blob/main/docs/migrating-to-0.8.md Illustrates mapping over async query results and then collecting them using `.try_collect().await`. ```rust result.data.map(..).try_collect().await ``` -------------------------------- ### Install FalkorDB with Rustls Sync TLS Feature Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Add the 'rustls' feature to your FalkorDB dependency for synchronous TLS support using the pure Rust Rustls implementation. ```bash cargo add falkordb --features rustls ``` -------------------------------- ### Reproduce CI Job: Dependency Audit Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Locally run the `check-deny` CI job using the `just deny` recipe. ```bash just deny ``` -------------------------------- ### Call FalkorDB Procedure with Parameters Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/batch-and-procedures.md Invoke a FalkorDB procedure that may read or write data, passing parameters as needed. This example demonstrates creating a full-text index. ```rust let mut result = graph.call_procedure("db.idx.fulltext.createNodeIndex($label, $fields)") .with_param("label", "Article") .with_param("fields", vec!["title", "body"]) .execute()?; ``` -------------------------------- ### Execute Index Creation (Fire-and-Forget) Source: https://github.com/falkordb/falkordb-rs/blob/main/README.md This snippet demonstrates the fire-and-forget behavior of `create_index_op().execute()`, which returns as soon as the server accepts the request without waiting for the index to become operational. ```rust use falkordb::{EntityType, FalkorClientBuilder, FalkorConnectionInfo, IndexType, WaitOptions}; use std::time::Duration; let connection_info: FalkorConnectionInfo = "falkor://127.0.0.1:6379".try_into() .expect("Invalid connection info"); let client = FalkorClientBuilder::new() .with_connection_info(connection_info) .build() .expect("Failed to build client"); let mut graph = client.select_graph("social"); // Fire-and-forget, exactly like `create_index` (returns as soon as the server accepts it): graph.create_index_op(IndexType::Range, EntityType::Node, "Person", &["age"], None) .execute() .expect("Failed to request index creation"); ``` -------------------------------- ### Execute Query and Get Lazy Results Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-graph.md Executes the configured query and returns results as a lazy iterator. Handles potential errors during execution, parameter binding, or connection. ```rust pub fn execute(self) -> FalkorResult> ``` ```rust let mut result = graph.query("MATCH (n) RETURN n LIMIT 10").execute()?; while let Some(row) = result.data.next() { let row = row?; println!("{:?}", row.get_at(0)); } println!("Nodes created: {:?}", result.get_nodes_created()); ``` -------------------------------- ### Run Property-Based Tests Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Execute property-based tests using proptest. These tests verify query-parameter encoding and serde mapping without a running server. The `just proptest` command uses the default case count, while `just proptest 4096` increases it. The raw cargo command is also provided. ```bash just proptest ``` ```bash just proptest 4096 ``` ```bash cargo nextest run --lib --features serde proptest ``` -------------------------------- ### Configure Embedded FalkorDB Client Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/configuration.md Use `EmbeddedConfig` to set up an embedded FalkorDB server. The module is downloaded and cached on first start. Requires Redis server v8.0+. ```rust use falkordb::{FalkorClientBuilder, FalkorConnectionInfo, EmbeddedConfig}; let embedded = EmbeddedConfig::default(); let client = FalkorClientBuilder::new() .with_connection_info(FalkorConnectionInfo::Embedded(embedded)) .build()?; ``` -------------------------------- ### ParamEncoding Error Examples Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/errors.md Illustrates common scenarios that trigger the ParamEncoding error, such as invalid parameter names, non-finite float values, or attempting to encode graph entities directly. ```text "invalid query parameter 'x': parameter name contains invalid character '-' "invalid query parameter 'coords': cannot encode non-finite float 'NaN'" "invalid query parameter: cannot encode graph entity 'Node'; use Cypher constructors instead" "invalid query parameter 'count': integer 9223372036854775808 overflows i64" ``` -------------------------------- ### Configuration Options Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/MANIFEST.txt Details on configuring the FalkorDB Rust client, including Cargo feature flags, builder configuration methods, environment variables, embedded server options, and connection URL formats. ```APIDOC ## Configuration Options ### Description This section outlines the various ways to configure the FalkorDB Rust client. It covers Cargo feature flags, all available builder methods, environment variable settings, and details on connection information formats including URL parsing for different connection types (TCP, Unix socket, Sentinel, embedded). ### Configuration Aspects - **Cargo Feature Flags**: 10+ features with descriptions. - **Builder Methods**: All configuration methods available via `FalkorClientBuilder`. - **Environment Variables**: Runtime and build-time configuration. - **EmbeddedConfig**: Options for running an embedded FalkorDB server. - **Connection Information**: Formats and URL parsing (TCP, Unix socket, Sentinel, embedded). - **TLS Configuration**: Settings for secure connections. ``` -------------------------------- ### Manage FalkorDB Container Lifecycle Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Manually control the lifecycle of a FalkorDB Docker container. Use `db-up` to start, `db-populate` to load test data, and `db-down` to stop and remove. ```bash # Manage a FalkorDB container yourself. just db-up # start a server (and wait until it is ready) just db-populate # load the IMDB fixture graph the lib tests use just db-down # stop and remove the container ``` -------------------------------- ### Run All CI Gates Locally (No Server) Source: https://github.com/falkordb/falkordb-rs/blob/main/CONTRIBUTING.md Execute all required CI checks locally that do not depend on a running FalkorDB instance. This includes formatting, linting, building, and documentation tests. ```bash # Run every required CI gate locally (no server needed): # fmt-check, clippy, build, doc, doctest, build-examples, deny, check-llms, check-readme. just ci ``` -------------------------------- ### Get Connection Strategy using FalkorSyncClient Source: https://github.com/falkordb/falkordb-rs/blob/main/_autodocs/api-reference-client-builder.md Returns the effective connection strategy being used by the client. This may differ from the initially requested strategy, especially when using Sentinel for high availability. ```rust pub fn connection_strategy(&self) -> ConnectionStrategy ```