Reputation: 1941
New to Neo4J/Cypher and here is my query:
MATCH (origin:BusStop)-[bus*]->(destination:BusStop)
WITH bus
WHERE origin.name =~ '(?i).*Origin.*'
AND destination.name =~ '(?i).*Destination.*'
AND all(rel in bus where rel.day in ['Sat'])
RETURN bus
I'm trying to get all the possible buses between the Origin and Destination. I also want the total fare (as a sum function) in the above query.
Note: The relationship has a property called fare SUM(bus.fare)).
Upvotes: 1
Views: 633
Reputation: 2656
Here's a way to do it without APOC:
Testdata :
CREATE (o:BusStop {id: 1})
CREATE (i1:BusStop {id: 2})
CREATE (d:BusStop {id: 3})
CREATE (i2:BusStop {id: 4})
MERGE (o)-[:Bus {day: "Sat", fare: 10}]->(i1)-[:Bus {day: "Sat", fare: 15}]->(d)
MERGE (o)-[:Bus {day: "Sun", fare: 5}]->(i1)-[:Bus {day: "Sun", fare: 15}]->(d)
MERGE (o)-[:Bus {day: "Mon", fare: 20}]->(i1)
MERGE (i1)-[:Bus {day: "Sat", fare: 5}]->(i2)-[:Bus {day: "Sat", fare: 9}]->(d);
Query:
MATCH p=(o:BusStop)-[*]->(d:BusStop)
WHERE o.id = 1
AND d.id = 3
AND ALL (rs in relationships(p)
WHERE rs.day in ['Sat'])
WITH p, relationships(p) AS rels
UNWIND rels AS rel
RETURN DISTINCT p, sum(rel.fare) AS price;
Hope this helps.
Regards, Tom
Upvotes: 0
Reputation: 30397
With APOC Procedures you can sum elements of a collection, though you'll need to extract the fare value from each relationship in the bus collection:
RETURN bus, apoc.coll.sum([rel in bus | rel.fare]) as totalFare
Without APOC Procedures, you'll need to use REDUCE():
RETURN bus, reduce(total = 0, rel in bus | total + rel.fare) as totalFare
Upvotes: 1