Neo4j / Cypher:如果满足某些条件,则建立关系

时间:2014-10-24 07:47:48

标签: neo4j cypher

我正在我的图表数据库中进行求和操作:我比较几个节点,计算一个数字来表示图表的某些区域有多相似,如果这个数字足够大,我想创建一个关系节点。

我有一个查询可以做到这一切,除了检查数字是否足够大;它目前还创建了相似性得分为0的相似关系 - 我不想要那样。

我的完整密码查询有点长,所以我已经为这篇文章简化了它。因此,我担心我无法在neo4j控制台中提供示例图db。我的图包含Center个节点,它们周围有Affinity个节点和Searched个节点。如果2个中心节点具有相似的Affinity或Searched节点,则中心节点将获得关系。

这里是带注释的简化语句:

MATCH (a:Center), (x:Center)
WHERE id(a) <> id(x)
OPTIONAL MATCH a-->(aff1:Affinity), x-->(aff2:Affinity)
WHERE aff1.affinityReference=aff2.affinityReference     // if the Affinity nodes have the same reference, then their Center nodes are similar
OPTIONAL MATCH a-->(search1:Search), x-->(search2:Search)
WHERE search1.searchTerm = search2.searchTerm   // if the Search nodes have the same searchTerm, then their Center nodes are similar
WITH a, x, 
SUM (CASE WHEN aff2.relative_weight IS NULL THEN 0 ELSE (aff2.relative_weight * 5) END) AS AffinityScore, // Affinity nodes have a relative weight, which shall be used in the similarity calculation.
(count(search2) * 5) AS SearchScore   // matching Search nodes shall just be counted and multiplied with 5.

OPTIONAL MATCH x-[r1:IS_SIMILAR_TO]->()  // Delete all similarity relationships for x
WITH a,x,r1,AffinityScore, SearchScore, (AffinityScore+SearchScore) AS TotalScore

DELETE r1   // delete relationship if it exists...
MERGE      // ... and create it anew.
  x-[:IS_SIMILAR_TO {
  SimilarityScore:Total,
  AffinityScore:AffinityScore,
 SearchScore:SearchScore
 }]->a

RETURN a, x, AffintyScore, SearchScore, TotalScore 
ORDER BY TotalScore DESC

我尝试在不同的地方引入CASE声明,但显然从来没有在正确的地方。它应该去哪里?

感谢您的帮助!

1 个答案:

答案 0 :(得分:11)

进行条件变异操作有一个技巧:当条件为真时,使用CASE语句返回长度为1的列表,否则为空列表。然后使用FORACH迭代该数组以执行CREATEMERGE

...
WITH a, x, AffintyScore, SearchScore, TotalScore, Total, 
  CASE AffinityScore WHEN 0 THEN [] ELSE [1] END as array
FOREACH (x in array | 
   MERGE
   x-[:IS_SIMILAR_TO {
   SimilarityScore:Total,
   AffinityScore:AffinityScore,
   SearchScore:SearchScore
   }]->a 
)
RETURN a, x, AffintyScore, SearchScore, TotalScore 
ORDER BY TotalScore DESC