Search code examples
memgraphdb

Can I connect to Memgraph Cloud using Rust?


I'm wondering if I can connect from Rust to Memgraph Cloud. If it is important, I'm using a free version of the Memgraph Cloud at the moment.


Solution

  • To connect to a running Memgraph Cloud instance with Rust, you can use the provided code at the Cloud website. Also, the instructions are provided at the Memgraph Cloud documentation.

    Here are the steps:

    1. Install mgclient - a C library interface for the Memgraph database (installation instructions)
    2. Add dependency to the Cargo.toml file:
    rsmgclient = "0.1.1"
    
    1. Copy the following code and add the host address, username and password, which can be found at Memgraph Cloud website:
    use rsmgclient::{ConnectParams, Connection, SSLMode};
    
    fn main(){
        // Parameters for connecting to database.
        let connect_params = ConnectParams {
            host: Some(String::from("MEMGRAPH_HOST_ADDRESS")),
            port: 7687,
            username: Some(String::from("YOUR_MEMGRAPH_USERNAME")),
            password: Some(String::from("YOUR_MEMGRAPH_PASSWORD")),
            sslmode: SSLMode::Require,
            ..Default::default()
        };
    
        // Make a connection to the database.
        let mut connection = match Connection::connect(&connect_params) {
            Ok(c) => c,
            Err(err) => panic!("Connect failed: {}", err)
        };
    
        // Execute a query.
        let query = "CREATE (n:FirstNode {message: 'Hello Memgraph from Rust!'}) RETURN id(n) AS nodeId, n.message AS message";
        match connection.execute(query, None) {
            Ok(c) => c,
            Err(err) => panic!("Query failed: {}", err)
        };
    
        match connection.fetchall() {
            Ok(records) => {
                println!("Created node: {}", &records[0].values[1])
            },
            Err(err) => panic!("{}", err)
        };
    }