2017-09-22 46 views
1

我有一個方法,我傳遞一個現有節點的標題和兩個列表。一個包含新節點的標題,另一個包含應作爲屬性添加到新關係的計數。兩個列表都包含相同數量的項目。如何使用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(); 
} 

不幸的是這將所有與所有的關係計數的新節點之間的關係。如何將兩個列表與具有相同索引的項目配對?

回答

2

我寫了一個Cypher查詢,使用range()函數和FOREACH來解決問題。

首先,我創建與:Article節點:

: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) 
) 

CREATE (:Article {title : 'Article A'}) 

之後,我使用配置的Neo4j的瀏覽器參數

結果圖:

Resultant graph

編輯:

等效使用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(); 
}