You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Rust连接Docker中默认配置的Memgraph并执行查询?

Rust连接本地Docker版Memgraph数据库

1. 添加依赖

在你的Cargo.toml中添加兼容Memgraph的Bolt协议驱动,这里使用neo4rs(Memgraph兼容Neo4j的Bolt协议,该驱动成熟且易用):

[dependencies]
neo4rs = "0.22.0"
tokio = { version = "1.0", features = ["full"] }

2. 编写连接与查询代码

以下是异步风格的示例代码,包含连接数据库、创建节点和查询数据的操作:

use neo4rs::{Client, Config};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 连接默认配置的本地Memgraph(Docker映射端口7687,无认证)
    let config = Config::new("bolt://localhost:7687");
    let client = Client::connect(config).await?;

    // 执行创建节点的Cypher查询
    let create_query = "CREATE (n:User {name: 'Alice', age: 30}) RETURN n";
    let create_result = client.execute(create_query, None).await?;
    
    // 打印创建结果
    for row in create_result {
        let node = row.get("n")?;
        println!("Created node: {:?}", node);
    }

    // 执行查询节点的Cypher语句
    let query = "MATCH (n:User) RETURN n.name, n.age";
    let query_result = client.execute(query, None).await?;
    
    // 遍历并打印查询结果
    for row in query_result {
        let name: String = row.get("n.name")?;
        let age: i32 = row.get("n.age")?;
        println!("User: {} (age {})", name, age);
    }

    Ok(())
}

注意事项

  • 确保Docker中的Memgraph Platform实例已启动,且本地端口7687已正确映射(默认启动命令:docker run -p 7687:7687 -p 3000:3000 memgraph/memgraph-platform)
  • 若Memgraph配置了用户名和密码,需在连接时添加认证信息:Config::new("bolt://localhost:7687").with_auth("your_username", "your_password")
  • 也可使用Memgraph官方Rust驱动memgraph-driver,依赖写法为memgraph-driver = "0.1.0",API风格与上述示例类似

内容的提问来源于stack exchange,提问作者KWriter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:25:20