How can I combine results of two Cypher queries?

43 Views Asked by At

I have to visualize routes of two salesman. First one covers city from East to the West, second one from North to the South.

I used this code to create stores:

CREATE (a:Store {name: 'StoreA', location: 'East', route: 'EW'}),
       (b:Store {name: 'StoreB', location: 'Central East', route: 'EW'}),
       (c:Store {name: 'StoreC', location: 'Central', route: 'EW'}),
       (d:Store {name: 'StoreD', location: 'Central West', route: 'EW'}),
       (e:Store {name: 'StoreE', location: 'West', route: 'EW'}),
       (f:Store {name: 'StoreF', location: 'North', route: 'NS'}),
       (g:Store {name: 'StoreG', location: 'Central North', route: 'NS'}),
       (h:Store {name: 'StoreH', location: 'Central', route: 'NS'}),
       (i:Store {name: 'StoreI', location: 'Central South', route: 'NS'}),
       (j:Store {name: 'StoreJ', location: 'South', route: 'NS'});

I've used this to create relations between them:

MATCH (a:Store {name: 'StoreA'}),
      (b:Store {name: 'StoreB'}),
      (c:Store {name: 'StoreC'}),
      (d:Store {name: 'StoreD'}),
      (e:Store {name: 'StoreE'}),
      (f:Store {name: 'StoreF'}),
      (g:Store {name: 'StoreG'}),
      (h:Store {name: 'StoreH'}),
      (i:Store {name: 'StoreI'}),
      (j:Store {name: 'StoreJ'})
CREATE (a)-[:CONNECTED_TO]->(b),
       (b)-[:CONNECTED_TO]->(c),
       (c)-[:CONNECTED_TO]->(d),
       (d)-[:CONNECTED_TO]->(e),
       (f)-[:CONNECTED_TO]->(g),
       (g)-[:CONNECTED_TO]->(h),
       (h)-[:CONNECTED_TO]->(i),
       (i)-[:CONNECTED_TO]->(j);

I've used this to get rout for first salesman:

MATCH path = (s1:Store)-[:CONNECTED_TO*]->(s2:Store)
WHERE s1.route = 'EW' AND s2.route = 'EW'
RETURN path;

This is my second salesman:

MATCH path = (s1:Store)-[:CONNECTED_TO*]->(s2:Store)
WHERE s1.route = 'NS' AND s2.route = 'NS'
RETURN path;

I've tried to combine two queris into one using AND operator but it doesn't work:

MATCH path = (s1:Store)-[:CONNECTED_TO*]->(s2:Store)
WHERE s1.route = 'EW' AND s2.route = 'EW'
AND
MATCH path = (s1:Store)-[:CONNECTED_TO*]->(s2:Store)
WHERE s1.route = 'NS' AND s2.route = 'NS'
RETURN path;

I get the error message Query failed: line 4:7 mismatched input 'path' expecting {<EOF>, ';'}

1

There are 1 best solutions below

0
On

Try to use the UNION clause.

See: https://neo4j.com/docs/cypher-manual/current/clauses/union/

You could also additionally run this in a CALL { } subquery if you want to do additional processing on top of it.

See: https://neo4j.com/docs/cypher-manual/current/subqueries/

I am pointing out solutions for Neo4j 5.8 and higher. Be aware.