1
votes

I am trying to create a graph using Neo4j which makes relationships between cities and streets. There can be several streets with the same name, belonging to different cities, but the only restriction is that one city can't have 2 streets with the same name. Imagine I have the next scenario:

Here I create two Street nodes using Cypher with the same street name:

(st1: Street { streetName: 'streetName1'}),
(st2: Street { streetName: 'streetName1'}),

Here I create a City node:

(city1: City { cityName: 'cityName1'}),

I know st1 belongs to city1, so I create the relationship between them:

(st1)-[:BELONGS_TO]->(city1)

My question is: given that I have that relationship already in the graph, is there any way to prevent creating a new relationship between city1 and any other Street node which streetName attribute is 'streetName1', like the following

(st2)-[:BELONGS_TO]->(city1)
1
Unfortunately there no way to prevent creating new relationships as you described.Rajendra Kadam
You may need to check before creating relationships and conditionally create relationships.Rajendra Kadam

1 Answers

0
votes

Here is an example of how you can create a street and link it to a city if-and-only-if the city does not already have a street with the same name:

MATCH (city1:City {name: 'Foo'})
OPTIONAL MATCH (st:Street {streetName: 'streetName1'})-[:BELONGS_TO]->(city1)
FOREACH(x IN CASE WHEN st IS NULL THEN [1] END |
  CREATE (st2:Street {streetName: 'streetName1'})-[:BELONGS_TO]->(city1))