neo4jcypher

apoc.path.expand filtering nodes/links


I've got the following query which follows all relations into and out of a given node out to a particular distance (in this case 3 hops):

MATCH (r:Record {record_id: $id})
CALL apoc.path.expand(r, null, null, 0, 3) YIELD path
RETURN path, length(path) AS hops
ORDER BY hops

Now, I need to restrict this to show incoming relations only, and to filter on the type of relationship. This documentation would appear to offer the answer to that:

https://neo4j.com/labs/apoc/4.0/overview/apoc.path/apoc.path.expand/

The difficulty here is the fields:

relationshipFilter :: STRING?, labelFilter :: STRING?

Relations between each Record are handled by a RecordAssociation with a label, though this function requires strings. Is apoc.path.expand therefore not able to handle paths where an intermediate relation is used, and, if so, what would I need instead?


Solution

  • To only traverse inbound relationships with type RecordAssociation you would write:

    MATCH (r:Record {record_id: $id})
    CALL apoc.path.expand(r, '<RecordAssociation', null, 0, 3)
    YIELD path 
    RETURN path, length(path) AS hops ORDER BY hops
    

    There are more configuration options documented here.

    If you are on 5.9+, you are probably better off using quantified path patterns, which would allow you to write the following:

    MATCH path = (r:Record {record_id: $id})<-[:RecordAssociation]-{0,3}()
    RETURN path, length(path) AS hops ORDER BY hops
    

    One particular advantage of quantified path patterns is that you can also filter on the properties of relationships and nodes. This query is filtering on a property label on relationships with type RecordAssociation:

    MATCH path = (r:Record {record_id: $id})<-[:RecordAssociation {label: "value"}]-{0,3} ()
    RETURN path, length(path) AS hops ORDER BY hops