Search code examples
neo4jcypher

How to set number of relations between nodes?


I have created a transport route of station nodes connected by a :CONNECTION type session, if it is a transfer, I have a :EXCHANGE session type. I'm looking for a route using a query

MATCH path = (from:Station {id: 61})-[:IN]->(sec_from:Section),
              (to:Station {id: 131})<-[:OUT]-(sec_to:Section),
              route=(sec_from)-[:CONNECTION|EXCHANGE*]->(sec_to)
RETURN route;

If I want to search for direct connections only, I use: route=(sec_from)-[:CONNECTION*]->(sec_to) , it works. If I want to limit the number of connections to 5-10, I use: route=(sec_from)-[:CONNECTION*5..10]->(sec_to) also works. But if I want to have a connection of type :CONNECTION 1-100 and at the same time type :EXCHANGE 0-3, the query doesn't work:

MATCH path = (from:Station {id: 61})-[:IN]->(sec_from:Section),
              (to:Station {id: 131})<-[:OUT]-(sec_to:Section),
              route=(sec_from)-[:CONNECTION*1..100|EXCHANGE*0..3]->(sec_to)
RETURN route;

What is the correct syntax?

Thanks


Solution

  • Based on what you've written in the question, the straightforward way would be to add constraints on the number of each relationship type in a WHERE clause:

    MATCH path = (from:Station {id: 61})-[:IN]->(sec_from:Section), 
          (to:Station {id: 131})<-[:OUT]-(sec_to:Section), 
          route = (sec_from)-[r:CONNECTION|EXCHANGE*1..103]->(sec_to) 
    WHERE 1 <= size([rel IN r WHERE rel:CONNECTION]) <= 100 
          AND size([rel IN r WHERE rel:EXCHANGE]) <= 3
    RETURN route;
    

    Depending on your data, a post-filter like this could be inefficient, as it might fetch many paths with > 3 relationships of type EXCHANGE before discarding them at the WHERE clause stage.