I present a graph in Postgres 9.1 (sometimes bi-directional and cyclic):
CREATE TABLE nodes ( id SERIAL PRIMARY KEY, name text ); CREATE TABLE edges ( id SERIAL PRIMARY KEY, node1_id int REFERENCES nodes(id), node2_id int REFERENCES nodes(id) );
Given a specific node identifier, you want to get all the other nodes in this cluster. I started with the "Path from a single node" example here , and it was there that I got:
WITH RECURSIVE search_graph(id, path) AS ( SELECT id, ARRAY[id] FROM nodes UNION SELECT e.node2_id, sg.path || e.node2_id FROM search_graph sg JOIN edges e ON e.node1_id = sg.id )
I cannot understand, a) if there is an easier way to write this, since I do not care about collecting the full path and b) how to make it go in both directions ( node1 β node2 and node2 β node1 for each edge). It would be helpful to evaluate any light on a good approach. Thanks!
Aidan feldman
source share