How to use apoc.path.subgraphAll procedure in Neo4j

64 Views Asked by At

I am doing a project in which I am required to return the path or nodes in a path from a particular start node. I pass the start node to the query, and need to continue down the path until the value of the relationship property Action between two consecutive nodes is "ODC". Or, if the Action value is "ODSN", I have to break from the particular path and return the next node alone separately. I am required to process all the paths from a particular start node in this manner.

I tried using the apoc.path.subgraphAll procedure but did not get the desired result:

MATCH (c:Customer {customer_id: 4})
CALL apoc.path.subgraphAll(c, {
relationshipFilter: ">",
minLevel: 1
})
YIELD nodes, relationships
UNWIND relationships as rel
WITH nodes, rel
WHERE rel.Action = 'ODC'
RETURN DISTINCT nodes

Is there another method to approach this or should I be using another APOC procedure?

1

There are 1 best solutions below

1
cybersam On

If I understand your requirements correctly, you want to find paths containing just outgoing relationships in which only the last relationship has the Action value of either 'ODC' or 'ODSN'. If the value is 'ODC', then you want all the nodes in the path returned, else you only want the last node.

That use case does not need to use APOC. For example:

MATCH (c:Customer {customer_id: 4})-[rels1 *0..8]->()-[rel2:Action]->(n)
WHERE rel2.Action IN ['ODC', 'ODSN'] AND NONE(r1 IN rels1 WHERE r1.Action IN ['ODC', 'ODSN'])
WITH rel2.Action AS action, c, rels1, n
RETURN action, CASE action WHEN 'ODC' THEN [c] + [r2 IN rels1 | ENDNODE(r2)] + n ELSE [n] END AS nodes

Since it is best practice to put a reasonable upper bound on variable length relationship patterns (to avoid taking too long or running out of memory), this query searches paths up to 9 (i.e., 8 + 1) relationships deep (adjust as necessary to suit your actual data).

If action is 'ODC', then all the nodes in the path are returned in the nodes list, else the list contains only the last node.