1. 程式人生 > 程式設計 >PostgreSQL_圖的遞迴查詢

PostgreSQL_圖的遞迴查詢

背景

樹形遞迴查詢這篇文章,我記錄了使用CTE語法查詢樹形結構的辦法。在一個樹形結構中,每一個節點最多有一個上級,可以有任意個數的下級。

在實際場景中,我們還會遇到對圖(graph)的查詢,圖和樹的最大區別是,圖的節點可以有任意個數的上級和下級。如下圖所示

因為圖可能存在loop結構(上圖紅色箭頭),所以在使用CTE遞迴的過程中,必須要破環(break loop),否則演演算法就會進入無限遞迴,永不結束。

儲存和查詢圖結構,目前當紅資料庫是neo4j,但是當資料量只有十幾萬條的時候,PostgreSQL完全可以勝任。

構造樣本資料

-- 每一條有向關係邊都存在上游,下游兩個節點
drop
table if exists demo.t_rel; create table if not exists demo.t_rel(up int,down int); -- 唯一約束,避免插入相同的關係 alter table demo.t_rel add constraint udx_t_rel unique (up,down); insert into demo.t_rel values(6,5),(3,7),(5,1),(1,2),(7,(2,4),4); -- 構造一條環資料,7-2-4-7 delete from demo.t_rel where up=4 and down=7
; insert into demo.t_rel values(4,7); 複製程式碼

遞迴查詢

指定節點的下級

常見的一個場景是,給定一個節點,查詢這個節點的所有下級節點和路徑。使用破環的演演算法關鍵如下

  • 使用陣列儲存當前的路徑資訊。
  • 計算下一個節點之前,判斷該節點是否已經存在於路徑上。如果是,就說明該點是環的起點,必須排除這個節點來達到破環的效果。
  • 起始節點和最大深度,都是可選的。如果忽略這兩個條件,就會返回完整的圖資訊。
with recursive 
downstream as
(
	select 1 as lvl,r.up,r.down,-- 儲存當前路徑
			array[]::int
[] || r.up || r.down as trace from demo.t_rel r where r.up = 7 -- 指定起點 union all select ds.lvl +1,ds.trace || r.down from demo.t_rel r,downstream ds where r.up = ds.down -- 破環 and not r.down = any(ds.trace) and ds.lvl < 20 -- 最大深度 ) select * from downstream ds; 複製程式碼

上面以節點7為開始,返回下級的所有節點和路徑資訊,如下。

-- 可以看到並沒有包括7-2-4-7這條環。
 lvl | up | down |  trace
-----+----+------+---------
   1 |  7 |    2 | {7,2}
   1 |  7 |    4 | {7,4}
   2 |  2 |    4 | {7,2,4}
(3 rows)
複製程式碼

指定節點的所有關聯

在社交網路的場景中,我們根據一個特定的節點,查詢所有的關係網。在本文的樣本資料中,我們的需求就變成,同時查詢指定節點的所有上級和下級。

為了方便後面的測試,我們封裝一個函式

drop function if exists f_get_rel;

/*
取得某個節點的相關聯節點,和路徑資訊。
@start_node 起始節點。
@direct_flag 查詢方向,-1:查詢上級;1:查詢下級; 0:查詢上下級;
@max_depth 遞迴深度,即查詢最多幾級關係。
*/
create or replace function f_get_rel(start_node int,direct_flag int=1,max_depth int=20) 
	returns table (direct int,cur_depth int,up_node int,down_node int,trace int[])
as $$
begin

	return query 
		with recursive 
		downstream as
		(
			select 1 as lvl,array[]::int[] || r.up || r.down as trace 
				from demo.t_rel r 
			where r.up = start_node
				and direct_flag in (0,1)
			union all
			select ds.lvl +1,ds.trace || r.down
				from demo.t_rel r,downstream ds 
			where r.up = ds.down
				and not r.down = any(ds.trace)
				and ds.lvl < max_depth
		),upstream as
		(
			select 1 as lvl,array[]::int[] || r.up || r.down as trace 
				from demo.t_rel r 
			where r.down = start_node
				and direct_flag in (0,-1)
			union all
			select us.lvl +1,r.up || us.trace 
				from demo.t_rel r,upstream us 
			where r.down = us.up
				and not r.up = any(us.trace)
				and us.lvl < max_depth
		)
		select -1,us.* from upstream us 
			union all 
		select 1,ds.* from downstream ds
		order by 1 desc,lvl,up,down
	;

end;
$$ language plpgsql strict;
複製程式碼

測試一下,查詢節點7的所有3度關聯節點資訊,如下

dap=# select * from demo.f_get_rel(7,3);
 direct | cur_depth | up_node | down_node |   trace
--------+-----------+---------+-----------+-----------
      1 |         1 |       7 |         2 | {7,2}
      1 |         1 |       7 |         4 | {7,4}
      1 |         2 |       2 |         4 | {7,4}
     -1 |         1 |       3 |         7 | {3,7}
     -1 |         1 |       4 |         7 | {4,7}
     -1 |         1 |       5 |         7 | {5,7}
     -1 |         2 |       2 |         4 | {2,4,7}
     -1 |         2 |       6 |         5 | {6,5,7}
     -1 |         3 |       1 |         2 | {1,7}
     -1 |         3 |       5 |         2 | {5,7}
(10 rows)
複製程式碼

圖形顯示結果

ECharts模板

在沒有整合圖形介面之前,使用ECharts的示例程式碼(地址),可以直觀的檢視關係圖譜。對官方樣表進行微調之後,程式碼如下 注意 程式碼中的 data 和 links 部分需要進行替換

option = {
    title: {
        text: '資料圖譜'
    },tooltip: {},animationDurationUpdate: 1500,animationEasingUpdate: 'quinticInOut',series : [
        {
            type: 'graph',layout: 'force',force: {
                    repulsion: 1000
                },focusNodeAdjacency: true,symbolSize: 30,roam: true,label: {
                normal: {
                    show: true
                }
            },edgeSymbol: ['circle','arrow'],edgeSymbolSize: [4,10],edgeLabel: {
                normal: {
                    textStyle: {
                        fontSize: 20
                    }
                }
            },data: [
                { name:"2",draggable: true,symbolSize:20},],links: [
                { source:"2",target:"4"},}
    ]
};
複製程式碼

構造顯示用資料

構造 data 部分

-- 根據節點的關聯點數量,設定圖形大小
with rel as (select * from f_get_rel(7,0,2)),up_nodes as (select up_node,count(distinct down_node) as out_cnt from rel group by up_node),down_nodes as (select down_node,count(distinct up_node) as in_cnt from rel group by down_node),node_cnt as ( select up_node as node,out_cnt as cnt from up_nodes union all select * from down_nodes )
select '{ name:"' || n.node || '",draggable: true,symbolSize:' || sum(n.cnt) * 10 || '},'  as node
	from node_cnt n
group by n.node
order by 1;
複製程式碼

構造 links 部分

select distinct r.up_node,r.down_node,'{ source:"'|| r.up_node ||'",target:"'|| r.down_node ||'"},' as links 
	from f_get_rel(7,3) r
order by r.up_node	;
複製程式碼

圖形顯示

把構造的data和links替換到ECharts程式碼裡面

  • 查詢節點7的所有2度關聯節點資訊,結果顯示如下

  • 查詢節點7的所有關聯節點資訊(不限層級數),結果顯示如下