我有一个方法可以传递现有节点的标题和两个列表。一个包含新节点的标题,另一个包含应作为属性添加到新关系的计数。两个列表都包含相同数量的项目。
我展开新文章列表,并可以使用以下代码成功添加新节点:
public async Task AddArticlesWithRelationshipsAsync(List<string> newArticleTitles, string linkedFromArticle, List<int> count)
{
await client
.Cypher
.Unwind(newArticleTitles, "newArticleTitle")
.Match("(linkedFromArticle:Article)")
.Where("linkedFromArticle.title = { linkedFromArticle}")
.WithParam("linkedFromArticle", linkedFromArticle)
.Merge("(newArticle: Article { title: newArticleTitle } )")
.Merge("(newArticle)< -[:REFERENCES { count: 500 }]-(linkedFromArticle)")
.ExecuteWithoutResultsAsync();
}
但是,硬编码为500.我正在努力利用<int>
的计数。到目前为止,我最好的尝试是展开count
列表:
public async Task AddArticlesWithRelationshipsAsync(List<string> newArticleTitles, string linkedFromArticle, List<int> count)
{
await client
.Cypher
.Unwind(newArticleTitles, "newArticleTitle")
.Unwind(count, "count")
.Match("(linkedFromArticle:Article)")
.Where("linkedFromArticle.title = { linkedFromArticle}")
.WithParam("linkedFromArticle", linkedFromArticle)
.Merge("(newArticle: Article { title: newArticleTitle } )")
.Merge("(newArticle)< -[:REFERENCES { count: count }]-(linkedFromArticle)")
.ExecuteWithoutResultsAsync();
}
不幸的是,这会增加所有新节点与所有关系计数之间的关系。如何将两个列表与具有相同索引的项配对?
答案 0 :(得分:2)
我写了一个Cypher查询,使用range()函数和FOREACH来解决问题。
首先,我创建了一个:Article
节点:
CREATE (:Article {title : 'Article A'})
之后,我将Neo4j浏览器参数配置为:
:params { linkedFromArticle : 'Article A', newArticleTitles : ['Article B', 'Article C', 'Article D'], count : [10, 20, 30] }
然后,Cypher查询:
MATCH (linkedFromArticle:Article)
WHERE linkedFromArticle.title = {linkedFromArticle}
WITH linkedFromArticle, RANGE(0, SIZE({count}) - 1) AS indexes
FOREACH(index IN indexes |
MERGE (newArticle:Article { title: {newArticleTitles}[index] } )
MERGE (newArticle)-[:REFERENCES {count : {count}[index]}]->(linkedFromArticle)
)
结果图:
修改强>
使用Neo4jClient的等效C#函数:
public async Task AddArticlesWithRelationshipsAsync(List<string> newArticleTitles, string linkedFromArticle, List<int> count) {
await client
.Cypher
.WithParam("newArticleTitles", newArticleTitles)
.WithParam("linkedFromArticle", linkedFromArticle)
.WithParam("count", count)
.Match("(linkedFromArticle:Article)")
.Where("linkedFromArticle.title = {linkedFromArticle}")
.With("linkedFromArticle, RANGE(0, SIZE({count}) - 1) AS indexes")
.ForEach("(index IN indexes | " +
"MERGE (newArticle:Article { title: {newArticleTitles}[index] } )" +
"MERGE (newArticle)-[:REFERENCES {count : {count}[index]}]->(linkedFromArticle)" +
")")
.ExecuteWithoutResultsAsync();
}