4

I have a graph in that contains two types of nodes (objects and pieces) and two types of links (similarTo and contains). Some pieces are made of the pieces.

I would like to extract the path to each piece starting from a set of objects.

MATCH (o:Object)
WITH o
OPTIONAL MATCH path = (p:Piece) <-[:contains*]- (o) -[:similarTo]- (:Object)
RETURN path

The above query only returns part of the pieces. In the returned graph, some objects do not directly connect to any pieces, the latter are not returned, although they actually do!

I can change the query to:

MATCH (o:Object) -[:contains*]-> (p:Piece) 
OPTIONAL MATCH (o) –[:similarTo]- (:Object) 

However, I did not manage to return the whole path for that query, which I need to return collection of nodes and links with:

WITH rels(path) as relations , nodes(path) as nodes 
UNWIND relations as r unwind nodes as n 
RETURN {nodes: collect(distinct n), links: collect(distinct {source: id(startNode(r)), target: id(endNode(r))})}

I'd be grateful to any recommendation.

Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
Pierre
  • 885
  • 2
  • 10
  • 25

1 Answers1

4

Would something like this do the trick ?

I created a small graph representing objects and pieces here : http://console.neo4j.org/r/abztz4

Execute distinct queries with UNION ALL

Here you'll combine the two use cases in one set of paths :

MATCH (o:Object)
WITH o
OPTIONAL MATCH p=(o)-[:CONTAINS]->(piece)
RETURN p
UNION ALL 
MATCH (o:Object)
WITH o
OPTIONAL MATCH p=(o)-[:SIMILAR_TO]-()-[:CONTAINS]->(piece)
RETURN p
Christophe Willemsen
  • 19,399
  • 2
  • 29
  • 36