【问题标题】:Neo4j / Cypher: create relationship if certain condition is metNeo4j / Cypher:如果满足特定条件,则创建关系
【发布时间】:2014-10-24 07:47:48
【问题描述】:

我在我的图数据库中进行求和运算:我比较了几个节点,计算一个数字来表示图中某些区域的相似程度,如果这个数字足够大,我想在节点。

我有一个查询可以完成所有这些,除了检查数字是否足够大;它目前还创建相似度得分为 0 的相似度关系——我不希望这样。

我的完整密码查询有点长,所以我在这篇文章中对其进行了简化。因此,恐怕我无法在 neo4j 控制台中提供示例图形数据库。我的图表包含Center 节点,它们周围有Affinity 节点和Searched 节点。如果 2 个 Center 节点有相似的 Affinity 或 Searched 节点,则 Center 节点应建立关系。

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

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 语句,但显然从来没有在正确的地方引入。应该去哪里?

感谢您的帮助!

【问题讨论】:

    标签: neo4j cypher


    【解决方案1】:

    进行条件变异操作有一个技巧:当条件为真时,使用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
    

    【讨论】:

    • 正是我需要的
    • 为什么 Cypher 没有更好的方法来做到这一点?
    • 因为简单的东西是为懦夫准备的 ;-) 更严重的是:在github.com/neo4j/neo4j/issues提出问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 2020-06-27
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多