neo4j 计算多跳匹配中的不同节点配对

watbbzwu  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(131)

我希望在查询邻居的邻居时计算不同配对的数量。假设我有一个由以下节点和边组成的小图,

(id:A, type:1)->(id:B, type:2)
(id:A, type:1)->(id:C, type:2)
(id:B, type:2)->(id:D, type:3)
(id:C, type:2)->(id:D, type:3)
(id:C, type:2)->(id:E, type:3)

字符串
和匹配的模式,

MATCH (n0 {id: A})--(n1:2)--(n2)
WHERE n2.id IN ["D", "E"]


我正在寻找一个查询,将计数不同的配对沿着这2跳模式。换句话说,预期的答案将给予计数,

A to type2   : 2 connections
type2 to D   : 2 connections
type2 to E   : 1 connection

dced5bon

dced5bon1#

假设idtype是属性,这是有效的:

MATCH (n0 {id: "A"})--(n1 {type:2})--(n2)
WHERE n2.id IN ["D", "E"]
WITH collect(DISTINCT [n0, n1]) AS r1, collect(DISTINCT [n1, n2]) AS r2
WITH 
    COLLECT {
        WITH r1
        UNWIND r1 AS r
        WITH r[0].id AS lhs, 'type' + r[1].type AS rhs, count(*) AS num
        RETURN {lhs: lhs, rhs: rhs, num: num }
    } AS first, 
    COLLECT {
        WITH r2
        UNWIND r2 AS r
        WITH 'type' + r[0].type AS lhs, r[1].id AS rhs, count(*) AS num
        RETURN {lhs: lhs, rhs: rhs, num: num }
    } AS second
UNWIND first + second AS cn
RETURN 
    cn.lhs + ' to ' + cn.rhs + ': ' + cn.num + 
    CASE 
      WHEN cn.num = 1 THEN ' connection' 
      ELSE ' connections' 
    END AS result

字符串
不太好...

ffvjumwh

ffvjumwh2#

这个查询可能就足够了(它在每个结果行中重复相同的A_to_type2计数):

MATCH ({id: "A"})-[r1]-({type:2})-[r2]-(n2)
WHERE n2.id IN ["D", "E"]
WITH COUNT(DISTINCT r1) AS A_to_type2, COLLECT({n2Id: n2.id, r2: r2}) AS data
UNWIND data AS d
RETURN A_to_type2, d.n2Id AS n2Id, COUNT(DISTINCT d.r2) AS type2_to_n2Id

字符串
示例数据的输出:

╒══════════╤════╤═════════════╕
│A_to_type2│n2Id│type2_to_n2Id│
╞══════════╪════╪═════════════╡
│2         │"D" │2            │
├──────────┼────┼─────────────┤
│2         │"E" │1            │
└──────────┴────┴─────────────┘


或者,返回一个包含type2_to_n2Id计数集合的单行:

MATCH ({id: "A"})-[r1]-({type:2})-[r2]-(n2)
WHERE n2.id IN ["D", "E"]
WITH COUNT(DISTINCT r1) AS A_to_type2, COLLECT({n2Id: n2.id, r2: r2}) AS data
UNWIND data AS d
WITH A_to_type2, d.n2Id AS n2Id, COUNT(DISTINCT d.r2) AS cnt
RETURN A_to_type2, COLLECT({n2Id: n2Id, count: cnt}) AS type2_to_n2Id


样品结果:

╒══════════╤══════════════════════════════════════════════╕
│A_to_type2│type2_to_n2Id                                 │
╞══════════╪══════════════════════════════════════════════╡
│2         │[{count: 2, n2Id: "D"}, {count: 1, n2Id: "E"}]│
└──────────┴──────────────────────────────────────────────┘

相关问题