'Neo4j CYPHER: trim a variable length path based on property match

I have a pretty complex query that includes variable length paths.

The purpose of the variable path is to recurse down a hierarchy until I find a match to a property in another part of the path.

It works fine, but as I output the nodes and edges to render a graph, I would like to trim down the searched path of the hierarchy to a meaningful length (i.e. down to where I found a match, but no further)

It goes something like this:

        MATCH p1 = (g:Group{filter_group})-[gr:CAN {{manage: 1}}]->(r1:Resource)-[r1r:IS_PART_OF]->(rt1:ResourceType)-[:INCLUDES*0..3]->(rt2:ResourceType)-[rt2r:INCLUDES]->(i:Instance),
        p2 = (r1)-[:IS_IN|IS_PARENT_OF*]->(c1:Compartment)
        WHERE (i.compartment_id IS NULL AND i.id IS NULL) or ANY(n IN nodes(p2)[1..] WHERE n.id = i.compartment_id)
        OPTIONAL MATCH p3 = (i)-[ir:IS_IN]->(c2:Compartment)
        UNWIND([
            nodes(p1), relationships(p1),
            nodes(p2), relationships(p2)
        ]) AS nested
        WITH ir, c2, nested UNWIND(nested) as n
        RETURN DISTINCT n, ir, c2

The WHERE clause is what determines a match for i.compartment_id in the id of Compartment nodes in the path p2

So I want to trim down the path p2 to the length where I found that match, so that the UNWIND clause would be something like:

UNWIND([
            nodes(p1), relationships(p1),
            nodes(p2)[0..X], relationships(p2)[0..X-1]
        ]) AS nested

Where X is the index value I need to find and populate dynamically.

How would I do that?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source