.NET C# 操作Neo4j图数据库
目录
- .NET C# 操作Neo4j图数据库
- 环境
- Code
环境
VisualStudio2022 + .NET 6 + Neo4j.Driver 5.21
Code
// 连接设置
var uri = "bolt://localhost:7687";
var user = "neo4j";
var password = "password"; // 请替换为你的实际密码
var driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
var session = driver.AsyncSession();
try
{
// 创建节点
var createResult = await session.RunAsync("CREATE (n:Person {name: $name, age: $age}) RETURN n",
new { name = "Alice", age = 30 });
var createdNode = await createResult.SingleAsync();
Console.WriteLine($"Created Node: {createdNode["n"].As<INode>().Properties["name"]}");
// 查询节点
var readResult = await session.RunAsync("MATCH (n:Person) WHERE n.name = $name RETURN n",
new { name = "Alice" });
var readNode = await readResult.SingleAsync();
Console.WriteLine($"Read Node: {readNode["n"].As<INode>().Properties["name"]}");
// 更新节点
var updateResult = await session.RunAsync("MATCH (n:Person) WHERE n.name = $name SET n.age = $age RETURN n",
new { name = "Alice", age = 35 });
var updatedNode = await updateResult.SingleAsync();
Console.WriteLine($"Updated Node Age: {updatedNode["n"].As<INode>().Properties["age"]}");
// 删除节点
var deleteResult = await session.RunAsync("MATCH (n:Person) WHERE n.name = $name DELETE n",
new { name = "Alice" });
Console.WriteLine("Deleted Node: Alice");
// 创建节点 Alice
var createAlice = await session.RunAsync("CREATE (a:Person {name: $name, age: $age}) RETURN a",
new { name = "Alice", age = 30 });
var aliceNode = await createAlice.SingleAsync();
Console.WriteLine($"Created Node: {aliceNode["a"].As<INode>().Properties["name"]}");
// 创建节点 Bob
var createBob = await session.RunAsync("CREATE (b:Person {name: $name, age: $age}) RETURN b",
new { name = "Bob", age = 25 });
var bobNode = await createBob.SingleAsync();
Console.WriteLine($"Created Node: {bobNode["b"].As<INode>().Properties["name"]}");
// 创建关系 KNOWS
var createRelationship = await session.RunAsync(@"
MATCH (a:Person {name: $nameA}), (b:Person {name: $nameB})
CREATE (a)-[r:KNOWS]->(b)
RETURN r",
new { nameA = "Alice", nameB = "Bob" });
var relationship = await createRelationship.SingleAsync();
Console.WriteLine($"Created Relationship: {relationship["r"].As<IRelationship>().Type}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
await session.CloseAsync();
await driver.CloseAsync();
}