neo4j:类型按距离计数

neo4j: type counts by distance

我想根据与根的距离按类型进行计数统计。例如,

(A型:'private')-[值:20]->(B型:'private')-[值:40]->(C型:'private' )

(A型:'private')-[值:0]->(D型:'public')-[值:20]->(E型:'private' )

CREATE (:firm {name:'A', type:'private'}), (:firm {name:'B', type:'private'}), (:firm {name:'C', type:'private'}), (:firm {name:'D', type:'public'}), (:firm {name:'E', type:'private'});
MATCH (a:firm {name:'A'}), (b:firm {name:'B'}), (c:firm {name:'C'}), (d:firm {name:'D'}), (e:firm {name:'E'})
CREATE (a)-[:REL {value: 20}]->(b)->[:REL {value: 40}]->(c),
(a)-[:REL {value: 0}]->(d)->[:REL {value: 20}]->(e);

我想得到A的每类直接邻居和第二层邻居的数量,即

+-----------------------------+
| distance |   type   | count |
+-----------------------------+
| 0        |  private |   1   |
| 0        |  public  |   0   |
| 1        |  private |   1   |
| 1        |  public  |   1   |
| 2        |  private |   2   |
| 2        |  public  |   0   |
+-----------------------------+

是一个关于按距离聚合统计的相关问题。 谢谢!

为此,apoc library 派上了用场:

MATCH path=(:firm {name:'A'})-[:REL*]->(leaf:firm)
WHERE NOT (leaf)-[:REL]->(:firm)
WITH COLLECT(path) AS paths, max(length(path)) AS longest
UNWIND RANGE(0,longest) AS depth
WITH depth,
     apoc.coll.frequencies([node IN apoc.coll.toSet(REDUCE(arr=[], path IN [p IN paths WHERE length(p) >= depth] |
                                   arr
                                   + nodes(path)[depth]
                            ) 
     ) | node.type
     ]) as typesAtDepth

UNWIND typesAtDepth AS typeAtDepth
RETURN depth, typeAtDepth.item AS type, typeAtDepth.count AS count

对于此数据集

CREATE (_174:`firm` { `name`: 'A', `type`: 'type2' }) CREATE (_200:`firm` { `name`: 'D', `type`: 'type2' }) CREATE (_202:`firm` { `name`: 'E', `type`: 'type2' }) CREATE (_203:`firm` { `name`: 'F', `type`: 'type1' }) CREATE (_191:`firm` { `name`: 'B', `type`: 'type1' }) CREATE (_193:`firm` { `name`: 'C', `type`: 'type2' }) CREATE (_174)-[:`REL` { `value`: '0' }]->(_200) CREATE (_200)-[:`REL` { `value`: '20' }]->(_202) CREATE (_202)-[:`REL` { `value`: '99' }]->(_203) CREATE (_174)-[:`REL` { `value`: '20' }]->(_191) CREATE (_191)-[:`REL` { `value`: '40' }]->(_193) 

它returns这个结果:

╒═══════╤═══════╤═══════╕
│"depth"│"type" │"count"│
╞═══════╪═══════╪═══════╡
│0      │"type2"│1      │
├───────┼───────┼───────┤
│1      │"type2"│1      │
├───────┼───────┼───────┤
│1      │"type1"│1      │
├───────┼───────┼───────┤
│2      │"type2"│2      │
├───────┼───────┼───────┤
│3      │"type1"│1      │
└───────┴───────┴───────┘