neo4j 在Cypher中为每个结果节点添加具有邻居计数的虚拟属性的简洁方法

fdx2calv  于 2023-10-18  发布在  其他
关注(0)|答案(2)|浏览(170)

我正在使用NeoDash,我想生成一个图形报告,其中每个节点的大小都由邻居的数量加权。
因此,这个计数必须成为NeoDash正确分析的节点的属性。
现在,4个小时后,我终于成功地完成了下面的查询,但我很确定应该有一种更优雅和简洁的方式来完成同样的任务,对吗?

MATCH path=(n)-[r]->(c) //n is already from a subset, and here we exclude _events
    WHERE NOT c:_event

WITH collect(distinct n) as listN, collect(distinct c) as listC
  UNWIND listN as n
    MATCH (n)-[r]->(c) WHERE c in listC

WITH listN, listC, n, count(c) as countC
  SET n.counter=countC

WITH collect(n) as listN, listC
  UNWIND listC as c
    MATCH (n)-[r]->(c) WHERE n in listN

WITH c, count(n) as countN, listN
  SET c.counter=countN

WITH collect(c) as listC, listN
  MATCH (n)-[r]->(c)
    WHERE n in listN 
      and c in listC

RETURN n,r,c

还是有什么apoc捷径

kyvafyod

kyvafyod1#

您可以使用COUNT子查询(从Neo4j 5.3开始可用)来内联SET子句的邻居计数。
此示例等效于初始查询,减去返回原始图:

MATCH (n)-[r]->(c:!_event)
WITH collect(DISTINCT n) + collect(DISTINCT c) AS ncs, collect(r) AS rs
UNWIND ncs AS nc
SET nc.counter = COUNT { (nc)-[r WHERE r IN rs]-() }

COUNT子查询表示数据库命中。作为替代方案,您可以通过仅计算第一个MATCH中的关系来避免后续的DB命中:

MATCH (n:A)-->(c:!_event)
WITH collect(n) + collect(c) AS ncs
UNWIND ncs AS nc
WITH nc, count(*) AS counter
SET nc.counter = counter
q3aa0525

q3aa05252#

下面的查询只需要一个MATCH,不需要APOC。CALL subqueries不返回任何内容,因此保留单个外部行。

.
.
.
MATCH (n)-[rel]->(:!_event) //n was defined earlier, and here we exclude _events
WITH COLLECT(rel) as rels
CALL {
  WITH rels
  UNWIND rels AS r
  WITH STARTNODE(r) AS n, COUNT(*) AS countC
  SET n.counter = countC
}
CALL {
  WITH rels
  UNWIND rels AS r
  WITH ENDNODE(r) AS c, COUNT(*) AS countN
  SET c.counter = countN
}
UNWIND rels AS r
RETURN STARTNODE(r) AS n, r, ENDNODE(r) AS c

相关问题