首页 > 解决方案 > Cypher Neo4j - 根据相同的关系对相似的实体进行排名

问题描述

在图像中,您会看到相同类型的节点 P,它们都与类型 C 的节点有关系。这只是一个没有太多细节的通用视图,但所有实体都有参数 ID。假设我有 P1 具有不同的关系模式,即 C1-C5...然后我如何获取具有相同关系的 P 类型的相似实体并根据相似关系的数量进行排名...

我想要的结果是基于我有已知 HasProperty 到 C1 的 P1 排名结果为:

P2,有 4 个相似关系,也有 C1
P3,有 3 个相似关系,也有 C1
P4,有 2 个相似关系,也有 C1

Neo4j

谢谢!

标签: neo4jcypher

解决方案


给定下图:

CREATE (p1:P {id: 'p1'})
CREATE (p2:P {id: 'p2'})
CREATE (p3:P {id: 'p3'})
CREATE (c1:C {id: 'c1'})
CREATE (c2:C {id: 'c2'})
CREATE (c3:C {id: 'c3'})
CREATE (c4:C {id: 'c4'})
CREATE (p1)-[:RELA {hasProperty: 1}]->(c1)
CREATE (p1)-[:RELA]->(c2)
CREATE (p1)-[:RELA]->(c3)
CREATE (p1)-[:RELA]->(c4)
CREATE (p2)-[:RELA {hasProperty: 1}]->(c1)
CREATE (p2)-[:RELA]->(c2)
CREATE (p2)-[:RELA]->(c3)
CREATE (p2)-[:RELA]->(c4)
CREATE (p3)-[:RELA]->(c2)
CREATE (p3)-[:RELB]->(c3)
CREATE (p3)-[:RELA]->(c4)

在此处输入图像描述

给定 p1,您可以为 p2、p3 中的每一个返回两个布尔值列表,一个用于相同的关系类型,一个用于相同的 hasProperty 值:

MATCH (n:P)-[r1]->(c)<-[r2]-(other)
WHERE n.id = 'p1'
WITH other.id AS otherId, 
collect(r1.hasProperty = r2.hasProperty) AS sameHasProperty, 
collect(type(r1) = type(r2)) AS sameType
RETURN *

╒═════════╤═════════════════╤═════════════════════╕
│&quot;otherId"│&quot;sameHasProperty"│&quot;sameType"           │
╞═════════╪═════════════════╪═════════════════════╡
│&quot;p3"     │[]               │[true,false,true]    │
├─────────┼─────────────────┼─────────────────────┤
│&quot;p2"     │[true]           │[true,true,true,true]│
└─────────┴─────────────────┴─────────────────────┘

然后,您可以为每个集合中的真假打分。

假设相似的 hasProperty 得分 2.0 和相似的关系类型得分 1.0 :

MATCH (n:P)-[r1]->(c)<-[r2]-(other)
WHERE n.id = 'p1'
WITH other.id AS otherId, 
collect(r1.hasProperty = r2.hasProperty) AS sameHasProperty, 
collect(type(r1) = type(r2)) AS sameType
RETURN otherId, (size([x IN sameHasProperty WHERE x = true])*2.0 + size([x IN sameType WHERE x = true])*1.0) AS score
ORDER BY score DESC

╒═════════╤═══════╕
│&quot;otherId"│&quot;score"│
╞═════════╪═══════╡
│&quot;p2"     │6.0    │
├─────────┼───────┤
│&quot;p3"     │2.0    │
└─────────┴───────┘

推荐阅读