cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Create Node A and relationships with Node B If B exists

Hi everybody!

I'm trying to create a Node A, and if there are b's related to a's, it should create those connections that already exist among other a's

This is what i got so far

CREATE (a:A)
WITH a
MATCH (b:B)-[:AVAILABLE]->(:A)
CREATE (a)<-[:AVAILABLE]-(b)
RETURN a

The problem with this is that it's not returning a, probably because of the create(a)

How can i do this?

1 ACCEPTED SOLUTION

Try this: Modified PeteM code

CREATE (a:A)

OPTIONAL MATCH  (b:B)-[:AVAILABLE]->(:A)
WITH COALESCE(b) as b1, a

FOREACH(ignoreMe IN CASE WHEN b1 is not null THEN [1] ELSE [] END|

	CREATE (a)<-[:AVAILABLE]-(b1)

)

RETURN a

View solution in original post

7 REPLIES 7

PeteM
Node Clone

Maybe:

CREATE (a:A)
MATCH (b:B)-[:AVAILABLE]->(:A)
WITH a, b
CREATE (a)<-[:AVAILABLE]-(b)
RETURN a

It's creating a, even if i don't have b or connection from a to b, but the response is null and i had to add with a after the first line

PeteM
Node Clone

Perhaps try with OPTIONAL MATCH (b:B)-[:AVAILABLE]->(:A)

I don't have b:B or :AVAILABLE yet created, so it will give an error
"Failed to create relationship UNNAMED81, node b is missing. If you prefer to simply ignore rows where a relationship node is missing, set 'cypher.lenient_create_relationship = true' in neo4j.conf"

Try this: Modified PeteM code

CREATE (a:A)

OPTIONAL MATCH  (b:B)-[:AVAILABLE]->(:A)
WITH COALESCE(b) as b1, a

FOREACH(ignoreMe IN CASE WHEN b1 is not null THEN [1] ELSE [] END|

	CREATE (a)<-[:AVAILABLE]-(b1)

)

RETURN a

Hi! This works, only had to add
with a
after the first line.
I notice that i was making a mistake, on my way of thinking this. By doing the
match (b:B)-[:AVAILABLE]->(:A)
i was getting all AVAILABLE connections from all bs, i ended up doing match only on b

PeteM
Node Clone

Ok I misunderstood your problem.

I just ran the queries myself to see, and the problem is the MATCH (b:B).. query when those relationships don't exist. So the condition fails, hence nothing is returned even though node a is created.

First, since you have created the node a:A, do you really require that to be passed back?

If so, you might want to consider using CALL subquery to run the MATCH and CREATE. However this requires v4.1.0 of Neo4j since passing of variables from outer query was not supported before this.

Someone else may respond with a way around this, but I couldn't really find a different way of running the query to get the a:A node returned in this instance.