neo4j - Cypher Neo4j - 根据相同的关系对相似的实体进行排名
问题描述
在图像中,您会看到相同类型的节点 P,它们都与类型 C 的节点有关系。这只是一个没有太多细节的通用视图,但所有实体都有参数 ID。假设我有 P1 具有不同的关系模式,即 C1-C5...然后我如何获取具有相同关系的 P 类型的相似实体并根据相似关系的数量进行排名...
我想要的结果是基于我有已知 HasProperty 到 C1 的 P1 排名结果为:
P2,有 4 个相似关系,也有 C1
P3,有 3 个相似关系,也有 C1
P4,有 2 个相似关系,也有 C1
谢谢!
解决方案
给定下图:
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 *
╒═════════╤═════════════════╤═════════════════════╕
│"otherId"│"sameHasProperty"│"sameType" │
╞═════════╪═════════════════╪═════════════════════╡
│"p3" │[] │[true,false,true] │
├─────────┼─────────────────┼─────────────────────┤
│"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
╒═════════╤═══════╕
│"otherId"│"score"│
╞═════════╪═══════╡
│"p2" │6.0 │
├─────────┼───────┤
│"p3" │2.0 │
└─────────┴───────┘
推荐阅读
- android - 我们如何在android中的图像上添加文本?
- knockout.js - 侧面可观察数组中可观察数组的变化不更新淘汰赛js中的UI
- python - 在 Django 中使用子查询并用平均值注释结果 - 删除 GROUP BY
- typescript - Typescript:使用声明合并扩展外部 javascript 库的接口
- apache-spark - Spark2 读取 ORC 文件比 Spark1 慢得多
- cassandra - Cassandra 触发器 jar 正在加载但未执行该类
- angular - 物料表中如何默认展开所有行?
- linux - 为什么ELF文件有这么多空格?
- sql-server - QT 连接错误 [Microsoft][ODBC SQL Server Driver][SQL Server] 用户 '' 登录失败。QODBC3: 无法连接
- iframe - 无法在超级集中显示 matomo iframe