如何使用 neo4jclient 展开两个列表?

How to unwind two lists with neo4jclient?

我有一个方法可以传递现有节点的标题和两个列表。一个包含新节点的标题,一个包含应该作为 属性 添加到新关系中的计数。两个列表包含相同数量的项目。

我展开了新文章列表,并且可以使用此代码成功添加新节点:

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();
}

不幸的是,这会添加所有新节点之间的关系以及所有关系计数。如何将两个列表与具有相同索引的项目配对?

我写了一个 Cypher 查询,使用 range() function and 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();
}