Vaasha
Vaasha

Reputation: 971

Good way to set relation to an edge in Neo4j

For my project I need to create a relation to an edge in Neo4j graph database.

Let's illustrate on example of a flight provider who operates flights from Rome to London (and back) and also from Oslo to Lisbon.

CREATE (l:City{name:"London"})
       (r:City{name:"Rome"}),
       (li:City{name:"Lisbon"})
       (o:City{name:"Oslo"}),
       (op:Operator{name:"One"}),
       (l)<-[f:FlightRoute{distance:900}]->(r)

How would you link Operator One to London, Rome, Lisbon and Oslo to suggest that this operator connects these cities (l<-->r & li<-->o) but not e.g. r<-->o. Other operators would be doing other cities. So basically I would like to link op to 2 edges.

Queries to perform would be to find all operators doing various lines. Calculating overall distances of operations (assuming <--> has distance parameter) etc.

I can imagine only to create a node between (l) and (r). Is there some other way?

Upvotes: 0

Views: 26

Answers (1)

cybersam
cybersam

Reputation: 67044

As you suspected, "reification" (i.e., turning a relationship into a node) is probably the best way to handle your situation.

Here is an example of a query that adds the fact that an operator operates a flight from London to Rome:

MATCH  (l:City {name:"London"}),
       (r:City {name:"Rome"}),
       (op:Operator {name:"One"})
CREATE (l)<-[:FROM]-(f:FlightRoute{distance:900})-[:TO]->(r),
       (op)-[:OPERATES]->(f);

And a similar query for a flight from Lisbon to Oslo:

MATCH  (li:City {name:"Lisbon"}),
       (o:City {name:"Oslo"}),
       (op:Operator {name:"One"})
CREATE (li)<-[:FROM]-(f:FlightRoute{distance:21})-[:TO]->(o),
       (op)-[:OPERATES]->(f);

To find all operators between London and Rome:

MATCH (l:City {name:"London"})<-[:FROM|TO]-(f)-[:FROM|TO]->(r:City {name:"Rome"}),
      (op:Operator)-[:OPERATES]->(f)
RETURN DISTINCT op;

To find overall distance for all flights of an operator:

MATCH (op:Operator {name:"One"})-[:OPERATES]->(f)
RETURN SUM(f.distance);

Indexes (or uniqueness constraint) for :City(name) and Operator(name) would help to speed up the above queries.

Upvotes: 1

Related Questions