0
votes

I'm new to neo4j and would really appreciate your help for this.

I have following graph created in neo4j.

n1----n2----n3----n4---n5

n1,n2,n3,n4,n5 all are nodes --- : relationship_type_1 (REL)

Now given any set of nodes (in any order), I want to check whether these nodes are connected or not. E.g. Given n1, n2, n3 ==> Connected. Given n1, n3, n2, n4, n5 ==> Connected.

How should I formulate my cypher query to check connectivity?

Following query is working even if I change the order,

MATCH p=_1--_2--_3 
WHERE _1.name?="Node1" and ALL (n in nodes(p) 
  WHERE n.name IN ["Node1", "Node2", "Node4"]) 
RETURN nodes(p);

on http://console.neo4j.org/?id=xl8pnl

but if I provide start nodes instead of using _1,_2 and change the order then it's not returning me the path. :(

http://console.neo4j.org/?id=xl8pnl for following query,

START p1=node(6),p2=node(5),p3=node(4) MATCH p=p1--p2--p3 
WHERE p1.name?="Node1" AND ALL (n IN nodes(p) WHERE n.name IN ['Node1' ,'Node3', 'Node2' , 'Node4']) 
RETURN nodes(p)

it doesn't return the path as nodes are connected in node(6)-node(5)-node(4) order.

2
Do the nodes have to be connected directly or are nodes in between allowed (the found path can be bigger than the nodes set, e.g. n1, n3, n5 -> n1----n2----n3----n4---n5 = connected) ?Peter Neubauer
HI, Nodes should be connected directly. E.g. given, n1,n3,n5 should result in ==> Not connected.sbhatt

2 Answers

2
votes

Case 1:

2 paths found

MATCH p=_1--_2--_3--_4 
WHERE _1.name?="Node1" and 
  ALL (n in nodes(p) 
    WHERE n.name IN ["Node1", "Node2", "Node3", "Node4"]) 
RETURN nodes(p);

Check it out here:

http://console.neo4j.org/?id=nn9yl6 in this case order dosen't matter


Case 2

(no path found)

Use node 1,2,4

MATCH p=_1--_2--_3 
WHERE _1.name?="Node1" and ALL (n in nodes(p) 
  WHERE n.name IN ["Node1", "Node2", "Node4"]) 
RETURN nodes(p);

Check it out here:

http://console.neo4j.org/?id=xl8pnl

2
votes

You need to list the different patterns that constitute the "connectedness" to you for instant by listing them explicitly like console.neo4j.org/r/2w3poz

START p1=node(0),p2=node(4),p3=node(5) 
RETURN 
  CASE 
    WHEN p1--p2--p3 OR p2--p1--p3 OR p1--p3--p2 OR p3--p2--p1 OR p3--p1--p2  
    THEN 'Connected'  
    ELSE 'Not connected' 
  END