gpt4 book ai didi

c# - 如何在 c# neo4jClient 中创建一个唯一节点(如果已经存在则不重复)?

转载 作者:太空宇宙 更新时间:2023-11-03 18:32:19 25 4
gpt4 key购买 nike

我正在尝试执行以下操作(这在 neo4J 密码上很容易。

merge (ee:Person { id: "id1234" })

c#Neo4Jclient如何保证下次create不创建另外一个节点????

急需这个

client.Cypher.Merge("(user:User {Id: {Id} })")
.onCreate()
.set("user= {newUser}")
.withParams(new { ... } )
.executeWithoutResults();

似乎合并没有被拾取。知道为什么吗?因为即使对象完全相同,它仍然会创建一个新节点。

谢谢,R

最佳答案

您的语法可能不正确。请使用以下语法来防止创建重复节点。

GraphClient client = GetNeo4jGraphClient();
client.Connect();

client.Cypher
.Merge("(user:User {Id: {newUser}.Id })")
.OnCreate()
.Set("user = {newUser}")
.WithParams(
new {
newUser =
new {
Id = 1,
Name = "Michael",
Title = "Developer Advocate",
FavoriteDatabase = "Neo4j",
Occupation = "Software Developer"
}
})
.ExecuteWithoutResults();

请注意,我已将上面的 Id 属性更改为 {newUser}.Id

这解决了重复问题,但如果您将其用作 GET/CREATE 用户的方法,则不会反射(reflect)更新。例如,如果我将 newUser.Name 属性更改为 "Kenny",并且 Id 属性保持不变,则原始 ON CREATE 将优先并将节点恢复到其原始状态。

要解决此问题,您需要执行以下两项操作之一。

  1. 创建更新方法
  2. 将您的 MERGE 字符串作为不带参数的 Cypher 发送

选项 1 - 创建更新方法

创建一个看起来像这样的附加方法,将我的动态替换为您的用户类:

GraphClient client = GetNeo4jGraphClient();
client.Connect();

client.Cypher.Match("(user:User {Id: {newUser}.Id })")
.Set("user = {newUser}")
.WithParams(
new
{
newUser =
new
{
Id = 1,
Name = "Kenny",
Title = "Developer Advocate",
FavoriteDatabase = "Neo4j",
Occupation = "Software Developer"
}
})
.ExecuteWithoutResults();

选项 2 - 将您的 MERGE 字符串作为不带参数的 Cypher 发送

我建议将 Cypher 直接发送到 Neo4j 服务器并暂时绕过 Neo4jClient 中的 LINQ 扩展。

请查看这个修改后的基于 Neo4jClient 的 CypherQueryCreator.cs 文件:

https://github.com/kbastani/predictive-autocomplete/blob/master/predictive-autocomplete/PredictiveAutocomplete/CypherQueryCreator.cs

public static List<IGraphNode> MergeUser(User user)
{
var sb = new StringBuilder();
sb.AppendLine("MERGE user:User { Id: '{0}' }");
sb.AppendLine("RETURN user");

string commandQuery = sb.ToString();

commandQuery = string.Format(commandQuery, user.UserId);

GraphClient graphClient = GetNeo4jGraphClient();

var cypher = new CypherFluentQueryCreator(graphClient, new CypherQueryCreator(commandQuery), new Uri(Configuration.GetDatabaseUri()));

var resulttask = cypher.ExecuteGetCypherResults<GraphNode>();
var graphNodeResults = resulttask.Result.ToList().Select(gn => (IGraphNode)gn).ToList();
return graphNodeResults;
}

您可以在此处的同一个 GitHub 项目中找到类似的实现:

https://github.com/kbastani/predictive-autocomplete/blob/master/predictive-autocomplete/PredictiveAutocomplete/Processor.cs

转到方法“GetRankedNodesForQuery”。

注意:此实现未利用通过 REST API 推荐使用的参数。请查看文档以了解这一点:

http://docs.neo4j.org/chunked/milestone/rest-api-cypher.html#rest-api-use-parameters

干杯,

肯尼

关于c# - 如何在 c# neo4jClient 中创建一个唯一节点(如果已经存在则不重复)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20501806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com