### Async Runtime Setup with Tokio Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/00-index.md This snippet demonstrates the basic setup required to run Neo4rs applications using the Tokio asynchronous runtime. Ensure Tokio is added as a dependency. ```rust #[tokio::main] async fn main() -> Result<()> { // Your code here Ok(()) } ``` -------------------------------- ### Example: Commit Transaction Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/03-transaction-api.md Demonstrates how to start a transaction, run a query, and then commit the transaction. Includes conditional logic for routed drivers to capture bookmarks. ```rust use neo4rs::{Graph, query}; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; let mut txn = graph.start_txn().await?; txn.run(query("CREATE (p:Person {name: 'Alice'})")).await?; // With routed driver: captures bookmark for causal consistency #[cfg(feature = "unstable-bolt-protocol-impl-v2")] { if let Some(bookmark) = txn.commit().await? { println!("Transaction bookmark: {}", bookmark); } } #[cfg(not(feature = "unstable-bolt-protocol-impl-v2"))] { txn.commit().await?; } Ok(()) } ``` -------------------------------- ### Complete Neo4rs Configuration Example Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/05-configuration.md A comprehensive example demonstrating various configuration options for Neo4rs, including connection details, database selection, pooling, timeouts, TLS, and user impersonation. ```rust use neo4rs::{ConfigBuilder, Graph}; use std::time::Duration; #[tokio::main] async fn main() -> Result<()> { let config = ConfigBuilder::new() // Connection .uri("bolt://neo4j.example.com:7687") .user("neo4j") .password("supersecret") // Database .db("neo4j") // Pool .fetch_size(1000) .max_connections(32) // Timeouts .connection_timeout(Duration::from_secs(15)) .tcp_keepalive(Duration::from_secs(60)) .idle_timeout(Duration::from_secs(300)) .max_lifetime(Duration::from_secs(3600)) // TLS .with_client_certificate("/etc/ssl/certs/ca.pem") // Impersonation .with_impersonate_user("alice") .build()?; let graph = Graph::connect(config)?; Ok(()) } ``` -------------------------------- ### Example: Get Last Bookmark Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/03-transaction-api.md Shows how to retrieve and print the last bookmark from a transaction handle, provided the necessary feature is enabled. ```rust #[cfg(feature = "unstable-bolt-protocol-impl-v2")] { if let Some(bookmark) = txn.last_bookmark() { println!("Last bookmark: {}", bookmark); } } ``` -------------------------------- ### Create New ConfigBuilder with Defaults Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/05-configuration.md Initializes a `ConfigBuilder` with default settings. Use this as a starting point for customizing connection parameters. ```rust use neo4rs::ConfigBuilder; let builder = ConfigBuilder::new() .uri("127.0.0.1:7687") .user("neo4j") .password("password"); ``` -------------------------------- ### Start Transaction on Specific Database Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md Initiate a transaction on a named database using `start_txn_on`. ```rust let mut txn = graph.start_txn_on("system").await?; txn.run(query("CREATE DATABASE testdb")).await?; txn.commit().await?; ``` -------------------------------- ### start_txn_as() Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Starts a new transaction with a specified operation type and optional bookmarks for causal consistency. Requires the 'unstable-bolt-protocol-impl-v2' feature. ```APIDOC ## start_txn_as() ### Description Starts a new transaction with operation type and bookmarks (requires `unstable-bolt-protocol-impl-v2` feature). ### Method `#[cfg(feature = "unstable-bolt-protocol-impl-v2")] pub async fn start_txn_as(&self, operation: Operation, bookmarks: Option>) -> Result` ### Parameters #### Path Parameters - **operation** (`Operation`) - Required - `Operation::Read` or `Operation::Write` - **bookmarks** (`Option>`) - Optional - Transaction bookmarks for causal consistency ### Response #### Success Response - **Txn** - A transaction handle ### Example ```rust let mut txn = graph.start_txn_as( Operation::Write, Some(vec![last_bookmark.clone()]) ).await?; txn.run(query("CREATE (p:Person {name: 'Charlie'})")).await?; let bookmark = txn.commit().await?; ``` ``` -------------------------------- ### Database Serialization Example Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md Shows how to use `Serialize` and `Deserialize` for the `Database` type within a struct, requiring the `unstable-bolt-protocol-impl-v2` feature. ```rust #[cfg(feature = "unstable-bolt-protocol-impl-v2")] { #[derive(Serialize, Deserialize)] struct Config { database: Database, } } ``` -------------------------------- ### start_txn_on() Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Starts a new transaction on a specified database. The transaction is managed via the returned Txn handle. ```APIDOC ## start_txn_on() ### Description Starts a new transaction on a specified database. The transaction is managed via the returned `Txn` handle. ### Method `pub async fn start_txn_on(&self, db: impl Into) -> Result` ### Parameters #### Path Parameters - **db** (`impl Into`) - Required - Target database name ### Response #### Success Response - **Txn** - A transaction handle ### Example ```rust let mut txn = graph.start_txn_on("system").await?; txn.run(query("DROP DATABASE testdb")).await?; txn.commit().await?; ``` ``` -------------------------------- ### Quick Start: Connect and Query Neo4j Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/00-index.md Demonstrates how to establish a connection to Neo4j, execute a Cypher query with parameters, and process the results using the neo4rs Rust driver. ```rust use neo4rs::{Graph, query}; #[tokio::main] async fn main() -> Result<()> { // Create a graph connection let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; // Execute a query let mut result = graph.execute( query("MATCH (p:Person {name: $name}) RETURN p") .param("name", "Alice") ).await?; // Consume results while let Some(row) = result.next().await? { let person: neo4rs::Node = row.get("p")?; println!("ID: {}", person.id()); } Ok(()) } ``` -------------------------------- ### Start a transaction with operation type and bookmarks Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Use `start_txn_as` to begin a transaction with a specified operation type (Read/Write) and optional bookmarks for causal consistency. This requires the `unstable-bolt-protocol-impl-v2` feature. ```rust let mut txn = graph.start_txn_as( Operation::Write, Some(vec![last_bookmark.clone()]) ).await?; txn.run(query("CREATE (p:Person {name: 'Charlie'})")).await?; let bookmark = txn.commit().await?; ``` -------------------------------- ### Start a transaction on a specific database Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Use `start_txn_on` to initiate a transaction on a specified database. This is useful for managing transactions across different databases within a Neo4j instance. ```rust let mut txn = graph.start_txn_on("system").await?; txn.run(query("DROP DATABASE testdb")).await?; txn.commit().await?; ``` -------------------------------- ### start_txn() Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Starts a new transaction on the configured database. A dedicated connection is reserved and released when the Txn is dropped. Transactions are not automatically retried on failure. ```APIDOC ## start_txn() ### Description Starts a new transaction on the configured database. A dedicated connection is reserved for the transaction and released when the `Txn` is dropped. Transactions are not automatically retried on failure. ### Method `pub async fn start_txn(&self) -> Result` ### Response #### Success Response - **Txn** - A transaction handle ### Throws - `Error::ConnectionError` - Failed to start transaction ### Example ```rust let mut txn = graph.start_txn().await?; txn.run(query("CREATE (p:Person {name: 'Alice'})")).await?; txn.run(query("CREATE (p:Person {name: 'Bob'})")).await?; txn.commit().await?; ``` ``` -------------------------------- ### Complete Row Handling Example Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Demonstrates how to execute a query and process the results, retrieving various data types including strings, integers, nodes, relations, paths, and deserializing into custom structs. ```APIDOC ## Complete Row Handling Example ```rust use neo4rs::{Graph, query, Node, Relation, Path}; use serde::Deserialize; #[derive(Deserialize)] struct PersonData { name: String, age: i64, } #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; let mut result = graph.execute( query( "MATCH (p:Person)-[r:KNOWS]->(friend:Person) \ RETURN p, r, friend, p.name AS name, p.age AS age" ) ).await?; while let Some(row) = result.next().await? { // Get typed values let name: String = row.get("name")?; let age: i64 = row.get("age")?; // Get structured types let person: Node = row.get("p")?; let relationship: Relation = row.get("r")?; let friend: Node = row.get("friend")?; // Deserialize to custom types let data: PersonData = row.get("p")?; println!( "{} (age {}) knows {} via {}", name, age, friend.get::("name")?, relationship.rel_type() ); } Ok(()) } ``` ``` -------------------------------- ### BoltPoint3D Conversion Example Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/08-types.md Shows how to convert a tuple into a BoltPoint3D, including SRID, x, y, and z coordinates. Useful for data that includes a Z-axis value. ```rust .param("location_3d", (4979i64, 48.8566, 2.3522, 35.0)) // Altitude ``` -------------------------------- ### Run a Query with Neo4rs Session Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Use `run()` to execute a single query and get a result summary. It automatically handles retries and updates session bookmarks. ```rust let mut session = graph.with_session(Some(config)); let result = session.run( query("MATCH (p:Person {name: $name}) RETURN count(p)") .param("name", "Alice") ).await?; ``` -------------------------------- ### Query::new() Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/02-query-api.md Creates a new Query instance from a Cypher query string. This is the starting point for building a query. ```APIDOC ## Query::new() ### Description Creates a new Query instance from a Cypher query string. ### Method Rust function ### Parameters #### Path Parameters - **query** (String) - Required - Cypher query string ### Response #### Success Response - **Query** (Self) - The newly created Query instance. ### Request Example ```rust use neo4rs::Query; let q = Query::new("MATCH (p:Person {name: $name}) RETURN p".to_string()); ``` ``` -------------------------------- ### Complete Row Handling Example Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Demonstrates iterating through query results, extracting various data types including strings, integers, structured Neo4j types (Node, Relation), and deserializing custom structs from rows. Requires a running Neo4j instance and appropriate data. ```rust use neo4rs::{Graph, query, Node, Relation, Path}; use serde::Deserialize; #[derive(Deserialize)] struct PersonData { name: String, age: i64, } #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; let mut result = graph.execute( query( "MATCH (p:Person)-[r:KNOWS]->(friend:Person) \ RETURN p, r, friend, p.name AS name, p.age AS age" ) ).await?; while let Some(row) = result.next().await? { // Get typed values let name: String = row.get("name")?; let age: i64 = row.get("age")?; // Get structured types let person: Node = row.get("p")?; let relationship: Relation = row.get("r")?; let friend: Node = row.get("friend")?; // Deserialize to custom types let data: PersonData = row.get("p")?; println!( "{} (age {}) knows {} viaજી {}", name, age, friend.get::("name")?, relationship.rel_type() ); } Ok(()) } ``` -------------------------------- ### Neo4rs Causal Consistency Example Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Demonstrates how to achieve causal consistency between two Neo4rs sessions using bookmarks. The first session writes data and retrieves a bookmark, which is then used to configure the second session to ensure it reads the latest committed data. ```rust use neo4rs::{Graph, query, SessionConfig}; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; // Session 1: Write data let mut session1 = graph.with_session(None); session1.run( query("CREATE (p:Person {name: 'Alice', age: 30})") ).await?; let bookmark1 = session1.last_bookmark().unwrap(); // Session 2: Read with guaranteed consistency let config = SessionConfig::builder() .with_bookmarks(vec![bookmark1.clone()]) .build(); let mut session2 = graph.with_session(Some(config)); let mut result = session2.execute_read( query("MATCH (p:Person {name: 'Alice'}) RETURN p.age") ).await?; if let Some(row) = result.next().await? { let age: i64 = row.get("p.age")?; assert_eq!(age, 30); } Ok(()) } ``` -------------------------------- ### Execute Transaction Operation Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md Demonstrates starting a read transaction and executing a query within it using `Operation::Read`. Requires the `unstable-bolt-protocol-impl-v2` feature. ```rust use neo4rs::{Graph, Operation}; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; // Start a read transaction #[cfg(feature = "unstable-bolt-protocol-impl-v2")] { let mut txn = graph.start_txn_as( Operation::Read, None ).await?; let stream = txn.execute(query("MATCH (n) RETURN n LIMIT 1")).await?; txn.commit().await?; } Ok(()) } ``` -------------------------------- ### Execute Graph Operation Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md Example of executing a read operation on the graph using `Operation::Read`. Requires the `unstable-bolt-protocol-impl-v2` feature. ```rust use neo4rs::{Graph, Operation}; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; // With routing enabled, this will be routed appropriately #[cfg(feature = "unstable-bolt-protocol-impl-v2")] { let result = graph.execute_on( Operation::Read, "neo4j", query("MATCH (p:Person) RETURN p LIMIT 100") ).await?; } Ok(()) } ``` -------------------------------- ### Example: Rollback Transaction Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/03-transaction-api.md Illustrates how to handle potential errors during transaction execution by rolling back the transaction if an error occurs. Otherwise, it commits the transaction. ```rust use neo4rs::{Graph, query, Error}; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; let mut txn = graph.start_txn().await?; match txn.run(query("CREATE (p:Person {name: 'Alice'})")).await { Ok(_) => txn.commit().await?, Err(e) => { eprintln!("Error: {}", e); txn.rollback().await?; } } Ok(()) } ``` -------------------------------- ### Create a new Query instance Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/02-query-api.md Use Query::new() to create a Query instance from a Cypher query string. This is the starting point for building a query. ```rust use neo4rs::Query; let q = Query::new("MATCH (p:Person {name: $name}) RETURN p".to_string()); ``` -------------------------------- ### Retrieve query parameters Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/02-query-api.md Use get_params() to get a reference to all query parameters as a BoltMap. This allows inspection of the parameters associated with the query. ```rust use neo4rs::query; let q = query("MATCH (p:Person {name: $name}) RETURN p").param("name", "Alice"); let params = q.get_params(); // assert!(params.contains_key("name")); ``` -------------------------------- ### Select Read or Write Operation Mode Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md Use `Operation::Read` for queries that do not modify data and `Operation::Write` for queries that create, update, or delete data. This example requires the `unstable-bolt-protocol-impl-v2` feature. ```rust use neo4rs::{Graph, Operation}; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; #[cfg(feature = "unstable-bolt-protocol-impl-v2")] { // Use Read for queries that don't modify data let result = graph.execute_on( Operation::Read, "neo4j", query("MATCH (p:Person) RETURN p") ).await?; // Use Write for queries that create/update/delete let result = graph.execute_on( Operation::Write, "neo4j", query("CREATE (p:Person {name: 'Alice'})") ).await?; } Ok(()) } ``` -------------------------------- ### BoltPoint2D Conversion Example Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/08-types.md Demonstrates converting a tuple into a BoltPoint2D, specifically for WGS84 coordinates (latitude/longitude). Use this when passing 2D point data to Neo4j. ```rust // WGS84 (SRID 4326): latitude/longitude .param("location", (4326i64, 48.8566, 2.3522)) // Paris ``` -------------------------------- ### Relation::rel_type() Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Retrieves the type of the relationship. Example: "KNOWS". ```rust pub fn rel_type(&self) -> &str ``` ```rust let rel: Relation = row.get("r")?; println!("Type: {}", rel.rel_type()); // e.g., "KNOWS" ``` -------------------------------- ### Create and Use a New Database with Neo4rs Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Demonstrates creating a new database and then executing queries against it using separate sessions configured for the system and the new database. ```rust use neo4rs::{Graph, query, SessionConfig}; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; // Session on system database let system_config = SessionConfig::builder() .with_db("system".into()) .build(); let mut system_session = graph.with_session(Some(system_config)); system_session.run( query("CREATE DATABASE mydb") ).await?; // Session on new database let db_config = SessionConfig::builder() .with_db("mydb".into()) .build(); let mut db_session = graph.with_session(Some(db_config)); db_session.run( query("CREATE (p:Person {name: 'Alice'})") ).await?; Ok(()) } ``` -------------------------------- ### Create a new Graph instance with minimal configuration Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Use `Graph::new` for basic connections using the Bolt protocol. Ensure URI, username, and password are provided. ```rust use neo4rs::Graph; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; Ok(()) } ``` -------------------------------- ### Get Node Labels Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Retrieves all labels associated with a node. Useful for filtering or categorizing nodes based on their types. ```rust let node: Node = row.get("p")?; for label in node.labels() { println!("Label: {}", label); } ``` -------------------------------- ### Build SessionConfig and Create Session Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Builds a fully configured `SessionConfig` and then uses it to create a new session with the graph database. ```rust let config = SessionConfig::builder() .with_db("neo4j".into()) .with_fetch_size(1000) .with_bookmarks(bookmarks) .build(); let session = graph.with_session(Some(config)); ``` -------------------------------- ### Get Node ID Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Retrieves the unique identifier of a node. Use this when you need to reference a specific node by its ID. ```rust let node: Node = row.get("p")?; println!("Node ID: {}", node.id()); ``` -------------------------------- ### Configure Neo4rs Connection with Custom Settings Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/00-index.md Shows how to build a custom `Config` object for connecting to Neo4j, specifying URI, credentials, database name, fetch size, max connections, and connection timeout. Requires importing `ConfigBuilder` and `Duration`. ```rust use std::time::Duration; let config = ConfigBuilder::default() .uri("bolt://neo4j.example.com:7687") .user("neo4j") .password("secret") .db("neo4j") .fetch_size(1000) .max_connections(32) .connection_timeout(Duration::from_secs(15)) .build()?; let graph = Graph::connect(config)?; ``` -------------------------------- ### Get Path Node Indices Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Retrieves the indices that define the path, where each index corresponds to a node or relationship ID in sequence. ```rust let indices = path.indices(); // indices[0] = start node ID // indices[1] = first rel ID // indices[2] = second node ID // etc. ``` -------------------------------- ### Set Initial Bookmarks in SessionConfigBuilder Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Sets the initial bookmarks for the session to ensure causal consistency with previous transactions. ```rust .with_bookmarks(vec![last_bookmark.clone()]) ``` -------------------------------- ### Get Specific Node Property Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Retrieves a specific property from a node by its key. The property is deserialized into the specified type T. ```rust let node: Node = row.get("p")?; let name: String = node.get("name")?; let age: i64 = node.get("age")?; ``` -------------------------------- ### Get Last Bookmark (Unstable) Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/03-transaction-api.md Retrieves the last bookmark received from the server. This function requires the `unstable-bolt-protocol-impl-v2` feature to be enabled. ```rust pub fn last_bookmark(&self) -> Option<&str> ``` -------------------------------- ### Manage Multi-Database Operations Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md This snippet demonstrates how to run queries on different databases, including creating a new database and explicitly using the `Database` type. ```rust use neo4rs::{Graph, Database}; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; // Work with system database graph.run_on("system", query("CREATE DATABASE newdb")).await?; // Work with new database graph.run_on( "newdb", query("CREATE (p:Person {name: 'Bob'})") ).await?; // Or use Database type explicitly let db: Database = "newdb".into(); graph.run_on(db, query("MATCH (p:Person) RETURN count(p)")).await?; Ok(()) } ``` -------------------------------- ### Get Node Property Keys Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Retrieves the names of all properties stored on a node. Use this to inspect the available data fields on a node. ```rust let node: Node = row.get("p")?; for key in node.keys() { println!("Property: {}", key); } ``` -------------------------------- ### Create a new Graph instance with custom configurations Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Use `Graph::connect` with a `Config` object built by `ConfigBuilder` for advanced settings like fetch size, max connections, and timeouts. ```rust use neo4rs::{ConfigBuilder, Graph}; use std::time::Duration; #[tokio::main] async fn main() -> Result<()> { let config = ConfigBuilder::default() .uri("127.0.0.1:7687") .user("neo4j") .password("password") .fetch_size(500) .max_connections(20) .connection_timeout(Duration::from_secs(10)) .build()?; let graph = Graph::connect(config)?; Ok(()) } ``` -------------------------------- ### Retrieve the Cypher query string Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/02-query-api.md Use the query() method to get the Cypher query string from a Query instance. This is useful for debugging or logging. ```rust let q = query("MATCH (p:Person) RETURN p"); assert_eq!(q.query(), "MATCH (p:Person) RETURN p"); ``` -------------------------------- ### Create Neo4rs Session with Configuration Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Use `with_session` to create a new database session with specific configurations like database name and fetch size. This requires the `unstable-bolt-protocol-impl-v2` feature to be enabled. ```rust #[cfg(feature = "unstable-bolt-protocol-impl-v2")] pub fn with_session(&self, config: Option) -> Session ``` ```rust let session = graph.with_session( SessionConfigBuilder::default() .with_db("mydb".into()) .with_fetch_size(1000) .build() ); ``` -------------------------------- ### Configure Neo4rs Connection with Database Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md Use ConfigBuilder to set connection details including the target database name. ```rust use neo4rs::{ConfigBuilder, Database}; let config = ConfigBuilder::default() .uri("127.0.0.1:7687") .user("neo4j") .password("password") .db("neo4j") // Database name .build()?; ``` -------------------------------- ### SessionConfigBuilder::with_bookmarks Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Sets the initial bookmarks for the session to ensure causal consistency with previous transactions. ```APIDOC ## SessionConfigBuilder::with_bookmarks ### Description Sets the initial bookmarks for causal consistency. ### Parameters #### Path Parameters - **bookmarks** (`Vec`) - Required - Bookmarks from previous transactions ### Example ```rust .with_bookmarks(vec![last_bookmark.clone()]) ``` ``` -------------------------------- ### Build Neo4rs Configuration Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/05-configuration.md Construct a `Config` object using `ConfigBuilder`. Ensure required fields like URI, user, and password are provided to avoid `InvalidConfig` errors. ```rust let config = ConfigBuilder::new() .uri("127.0.0.1:7687") .user("neo4j") .password("password") .fetch_size(500) .max_connections(20) .build()?; let graph = Graph::connect(config)?; ``` -------------------------------- ### Get SRID from Point2D Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Retrieves the spatial reference system ID from a Point2D object obtained from a row. Assumes the 'location' column contains a Point2D. ```rust let point: Point2D = row.get("location")?; println!("SRID: {}", point.sr_id()); // e.g., 4326 (WGS84) ``` -------------------------------- ### Get a specific value from a row Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Retrieves and deserializes a single value from a row using its field name. Ensure the field exists and the type `T` matches the data. ```Rust use neo4rs::{Graph, query}; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; let mut result = graph.execute( query("MATCH (p:Person {name: $name}) RETURN p.name, p.age") .param("name", "Alice") ).await?; if let Some(row) = result.next().await? { let name: String = row.get("p.name")?; let age: i64 = row.get("p.age")?; println!("{}: {}", name, age); } Ok(()) } ``` -------------------------------- ### Configure Neo4rs Connection with Impersonated User Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md Use ConfigBuilder with `with_impersonate_user` to set up a connection that impersonates a specific user. ```rust use neo4rs::{ConfigBuilder, ImpersonateUser}; let config = ConfigBuilder::default() .uri("127.0.0.1:7687") .user("admin") .password("admin_password") .with_impersonate_user("alice") // Impersonate alice .build()?; ``` -------------------------------- ### Execute Concurrent Queries with Neo4rs Source: https://github.com/neo4j-labs/neo4rs/blob/main/README.md Demonstrates how to establish a connection to Neo4j and execute queries concurrently using Tokio tasks. Ensure you have a Neo4j instance running and accessible at the specified URI. ```rust // concurrent queries let uri = "127.0.0.1:7687"; let user = "neo4j"; let pass = "neo"; let graph = Graph::new(&uri, user, pass).unwrap(); for _ in 1..=42 { let graph = graph.clone(); tokio::spawn(async move { let mut result = graph.execute( query("MATCH (p:Person {name: $name}) RETURN p").param("name", "Mark") ).await.unwrap(); while let Some(row) = result.next().await.unwrap() { let node: Node = row.get("p").unwrap(); let name: String = node.get("name").unwrap(); println!("{}", name); } }); } //Transactions let mut txn = graph.start_txn().await.unwrap(); txn.run_queries([ "CREATE (p:Person {name: 'mark'})", "CREATE (p:Person {name: 'jake'})", "CREATE (p:Person {name: 'luke'})", ]) .await .unwrap(); txn.commit().await.unwrap(); //or txn.rollback().await.unwrap(); ``` -------------------------------- ### Build and Execute a Parameterized Cypher Query Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/02-query-api.md Demonstrates building a Cypher query with multiple parameters using method chaining and executing it against the Neo4j graph database. Ensure you have a running Neo4j instance and the necessary connection details. ```rust use neo4rs::{Graph, query}; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; let result = graph.execute( query( "MATCH (p:Person) \ WHERE p.name = $name AND p.age > $min_age AND p.city = $city \ RETURN p, p.name AS fullName, p.age" ) .param("name", "Alice") .param("min_age", 18) .param("city", "New York") ).await?; Ok(()) } ``` -------------------------------- ### UnsupportedVersion Error Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/07-error-handling.md Triggered when the server reports a Bolt protocol version that the driver does not support. Example: Using a driver built for Bolt 4.x with a server running Bolt 5.x. ```rust #[error("Bolt Version {0}.{1} is not supported")] UnsupportedVersion(u8, u8) ``` -------------------------------- ### Create SessionConfig with Builder Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Uses the `SessionConfigBuilder` for fluent configuration of session settings like database and fetch size. ```rust let config = SessionConfig::builder() .with_db("mydb".into()) .with_fetch_size(1000) .build(); ``` -------------------------------- ### Enable Logging with log crate Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/00-index.md Enable logging for the Neo4rs driver by initializing the env_logger crate. Set the RUST_LOG environment variable to control log verbosity. ```rust use log::{debug, info}; #[tokio::main] async fn main() -> Result<()> { env_logger::init(); let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; // ... } ``` -------------------------------- ### DeserializationError Handling Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/07-error-handling.md Handles errors that occur during Serde deserialization, such as type mismatches or missing fields. The example shows how to catch and report a deserialization error when converting a row to a `Person` struct. ```rust #[error("conversion error")] ConversionError ``` ```rust #[error("{0}")] DeserializationError(#[from] DeError) ``` ```rust match row.to::() { Err(Error::DeserializationError(de_err)) => { eprintln!("Deserialization error: {}", de_err); } _ => {} } ``` -------------------------------- ### Node::new Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Creates a new Node instance. This is typically used internally by the driver. ```APIDOC ## Node::new ### Description Creates a new Node. ### Signature ```rust pub fn new(inner: BoltNode) -> Self ``` ``` -------------------------------- ### UnboundedRelation Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Represents a relationship without explicit start and end node information, typically used within a `Path`. It provides methods to access the relationship's ID, type, and properties. ```APIDOC ## UnboundedRelation ### new() Creates a new `UnboundedRelation`. ```rust pub fn new(inner: BoltUnboundedRelation) -> Self ``` ### id() Returns the relationship ID. ```rust pub fn id(&self) -> i64 ``` ### rel_type() Returns the relationship type. ```rust pub fn rel_type(&self) -> &str ``` ### keys(), get(), to() These methods function identically to their counterparts in the `Relation` struct, allowing access to relationship properties and deserialization. ``` -------------------------------- ### Get Last Bookmark from Neo4rs Session Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Retrieves the most recent bookmark from the current session. Bookmarks are updated after successful write operations and are used for maintaining causal consistency across sessions. ```rust pub fn last_bookmark(&self) -> Option ``` ```rust let mut session = graph.with_session(Some(config)); session.run(query("CREATE (p:Person {name: 'Alice'})")).await?; if let Some(bookmark) = session.last_bookmark() { // Create a new session with causal consistency let config2 = SessionConfig::builder() .with_bookmarks(vec![bookmark]) .build(); let session2 = graph.with_session(Some(config2)); } ``` -------------------------------- ### Graph::connect Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Creates a new Graph instance with custom configurations built using ConfigBuilder. Allows for fine-grained control over connection settings. ```APIDOC ## Graph::connect ### Description Creates a new Graph instance with custom configurations built using `ConfigBuilder`. ### Method `connect` ### Parameters #### Path Parameters - **config** (`Config`) - Required - Configuration object built with `ConfigBuilder` ### Returns `Result` ### Throws - `Error::InvalidConfig` - Invalid configuration parameters - `Error::ConnectionError` - Failed to establish pool connection ### Example ```rust use neo4rs::{ConfigBuilder, Graph}; use std::time::Duration; #[tokio::main] async fn main() -> Result<()> { let config = ConfigBuilder::default() .uri("127.0.0.1:7687") .user("neo4j") .password("password") .fetch_size(500) .max_connections(20) .connection_timeout(Duration::from_secs(10)) .build()?; let graph = Graph::connect(config)?; Ok(()) } ``` ``` -------------------------------- ### Database From String Constructor Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md Implements `From` for `Database`, allowing conversion from a `String` to a `Database` type. ```rust impl From for Database { fn from(s: String) -> Self { Database(s.into()) } } ``` -------------------------------- ### run() Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Executes a query and returns a result summary. This method is suitable for simple queries where only the execution statistics are needed. ```APIDOC ## run() ### Description Executes a query and returns a result summary. ### Method `run` ### Parameters #### Path Parameters - **query** (`impl Into`) - Required - Query to execute ### Returns - `crate::Result` - Result summary with execution statistics ### Throws - `Error::Neo4j(...)` - Query execution failed ### Behavior - Uses the session's configured database and user. - Updates session bookmarks after successful execution. - Applies automatic retry on transient errors. ### Example ```rust let mut session = graph.with_session(Some(config)); let result = session.run( query("MATCH (p:Person {name: $name}) RETURN count(p)") .param("name", "Alice") ).await?; ``` ``` -------------------------------- ### Causal Consistency with Sessions and Bookmarks Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/00-index.md Illustrates how to maintain causal consistency across read and write operations using sessions and bookmarks. This pattern requires the `unstable-bolt-protocol-impl-v2` feature flag to be enabled. ```rust #[cfg(feature = "unstable-bolt-protocol-impl-v2")] { let mut session = graph.with_session(None); session.run(query("CREATE (p:Person {name: 'Alice'})")).await?; let bookmark = session.last_bookmark().unwrap(); let config = SessionConfig::builder() .with_bookmarks(vec![bookmark]) .build(); let mut session2 = graph.with_session(Some(config)); let result = session2.execute_read( query("MATCH (p:Person {name: 'Alice'}) RETURN p") ).await?; } ``` -------------------------------- ### Relation Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/06-row-types.md Represents a relationship (edge) between two nodes in the Neo4j graph. It provides methods to access the relationship's ID, start and end node IDs, type, properties, and to deserialize the relationship into a custom type. ```APIDOC ## Relation ### new() Creates a new `Relation`. ```rust pub fn new(inner: BoltRelation) -> Self ``` ### id() Returns the relationship ID. ```rust pub fn id(&self) -> i64 ``` ### start_node_id() Returns the ID of the start node. ```rust pub fn start_node_id(&self) -> i64 ``` ### end_node_id() Returns the ID of the end node. ```rust pub fn end_node_id(&self) -> i64 ``` ### rel_type() Returns the relationship type. **Example**: ```rust let rel: Relation = row.get("r")?; println!("Type: {}", rel.rel_type()); // e.g., "KNOWS" ``` ```rust pub fn rel_type(&self) -> &str ``` ### keys() Returns property names on this relationship. ```rust pub fn keys(&self) -> Vec<&str> ``` ### get() Retrieves a property from the relationship. ```rust pub fn get<'this, T>(&'this self, key: &str) -> Result where T: Deserialize<'this>, ``` ### to() Deserializes the entire relationship to a custom type. ```rust pub fn to<'this, T>(&'this self) -> Result where T: Deserialize<'this>, ``` ``` -------------------------------- ### Run Integration Test with Existing Neo4j Instance Source: https://github.com/neo4j-labs/neo4rs/blob/main/README.md Set environment variables for connection details and version tag to run a specific integration test against an existing Neo4j instance. ```sh env NEO4J_TEST_URI=bolt://localhost:7687 NEO4J_TEST_USER=neo4j NEO4J_TEST_PASS=supersecret NEO4J_VERSION_TAG=5.8 cargo test --test ``` -------------------------------- ### Create Default SessionConfig Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Creates a default `SessionConfig` with no specific settings. This can be used directly or as a base for further customization. ```rust let config = SessionConfig::default(); let session = graph.with_session(Some(config)); ``` -------------------------------- ### Execute Simple Query and Iterate Results Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/00-index.md Demonstrates how to execute a basic Cypher query and iterate over the returned rows, extracting data by column name. Ensure the 'graph' object is initialized and connected. ```rust let mut result = graph.execute( query("MATCH (p:Person) RETURN p LIMIT 10") ).await?; while let Some(row) = result.next().await? { let person: Node = row.get("p")?; println!("{}", person.id()); } ``` -------------------------------- ### Set all query parameters at once Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/02-query-api.md Use with_params() to set all query parameters at once, replacing any existing parameters. This is useful when you have a pre-defined map of parameters. ```rust use neo4rs::query; use neo4rs::BoltMap; // Assuming BoltMap can be constructed or obtained elsewhere // let params: BoltMap = ...; // let q = query("MATCH (p:Person) RETURN p").with_params(params); ``` -------------------------------- ### Configure Session with Impersonated User Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md Use SessionConfig with `with_imp_user` to specify a user to impersonate for a session. ```rust #[cfg(feature = "unstable-bolt-protocol-impl-v2")] { use neo4rs::{SessionConfig, ImpersonateUser}; let session_config = SessionConfig::builder() .with_imp_user("bob".into()) // Impersonate bob .build(); let session = graph.with_session(Some(session_config)); } ``` -------------------------------- ### with_session() Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Creates a new Session context with optional configuration. This method requires the 'unstable-bolt-protocol-impl-v2' feature to be enabled. ```APIDOC ## with_session() ### Description Creates a new `Session` context with configuration (requires `unstable-bolt-protocol-impl-v2` feature). ### Method Signature ```rust #[cfg(feature = "unstable-bolt-protocol-impl-v2")] pub fn with_session(&self, config: Option) -> Session ``` ### Parameters #### Path Parameters - **config** (`Option`) - Optional - Session configuration. Defaults to the default configuration if not provided. ### Returns - **Session** - A session handle that maintains database, user, and bookmark context. ### Example ```rust let session = graph.with_session( SessionConfigBuilder::default() .with_db("mydb".into()) .with_fetch_size(1000) .build() ); ``` ``` -------------------------------- ### Type Ergonomics for Database and User Impersonation Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/10-operation-enum.md Demonstrates the efficient cloning of `Database` and `ImpersonateUser` types, which use `Arc` internally for cheap sharing and cloning. ```rust let db1: Database = "neo4j".into(); let db2 = db1.clone(); // Cheap clone; shares Arc let user1: ImpersonateUser = "alice".into(); let user2 = user1.clone(); // Cheap clone; shares Arc ``` -------------------------------- ### SessionConfigBuilder::with_db Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/09-session-api.md Sets the default database for the session configuration. ```APIDOC ## SessionConfigBuilder::with_db ### Description Sets the default database for the session. ### Parameters #### Path Parameters - **db** (`Database`) - Required - Target database name ### Example ```rust .with_db("system".into()) .with_db("neo4j".into()) ``` ``` -------------------------------- ### Graph::new Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/01-graph-api.md Creates a new Graph instance with minimal configuration using the Bolt protocol. This is the primary entry point for connecting to a Neo4j database. ```APIDOC ## Graph::new ### Description Creates a new Graph instance with minimal configuration using the Bolt protocol. ### Method `new` ### Parameters #### Path Parameters - **uri** (`impl Into`) - Required - Connection URI (e.g., "127.0.0.1:7687") - **user** (`impl Into`) - Required - Username for authentication - **password** (`impl Into`) - Required - Password for authentication ### Returns `Result` ### Throws - `Error::InvalidConfig` - Missing or invalid URI, user, or password - `Error::ConnectionError` - Failed to establish connection ### Example ```rust use neo4rs::Graph; #[tokio::main] async fn main() -> Result<()> { let graph = Graph::new("127.0.0.1:7687", "neo4j", "password")?; Ok(()) } ``` ``` -------------------------------- ### Using BoltString for Query Parameters Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/08-types.md Demonstrates how to use the query! macro with a string parameter, which is automatically converted to BoltString. ```rust use neo4rs::query; let q = query("MATCH (p:Person {name: $name}) RETURN p") .param("name", "Alice"); // Automatically converted to BoltString ``` -------------------------------- ### Using BoltFloat for Query Parameters Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/08-types.md Demonstrates passing floating-point values of different types as query parameters, which are converted to BoltFloat. ```rust .param("price", 19.99) .param("weight", 5.5f32) ``` -------------------------------- ### Execute Parameterized Query Source: https://github.com/neo4j-labs/neo4rs/blob/main/_autodocs/00-index.md Shows how to execute a Cypher query with parameters, binding values to placeholders like $name and $age. This is useful for preventing injection vulnerabilities and improving query performance. ```rust let result = graph.execute( query("MATCH (p:Person {name: $name, age: $age}) RETURN p") .param("name", "Alice") .param("age", 30) ).await?; ```