SarathSprakash
SarathSprakash

Reputation: 4624

Neo4j - multiple tasks with OPTIONAL MATCH

I am new to Ne04j, I have to write one cypher query for the following situation enter image description here

Possiblity 1 :

Possiblity 2 :

Problem is with the Possiblity 1, I could not delete the relationship and create the relationship at the same time.

I have tried the following query,but it fails

match (a:user{id:12345}) 
optional match (a)-[r:NEXT]->(b:data) 
delete r 
create unique (a)-[:NEXT]->(c:data{id:1})-[:NEXT]->(b) 
with a 
create unique (a)-[:NEXT]->(c:data{id:2})

Please help, Thanks in advance

Upvotes: 0

Views: 325

Answers (2)

SarathSprakash
SarathSprakash

Reputation: 4624

Finally I ,found the solution.I am not sure whether this query is perfect, but this working and it tooks only a few milli seconds to execute.

I am posting this answer to help other people having same doubt

MATCH (a:user{id:12345})
MERGE (a)-[r:NEXT]->(b:data)
ON CREATE SET b.id=1
with a,r,b
match (a)-[r]->(b)
where b.id<>1
CREATE (a)-[k:NEXT]->(c:data{id:1})-[m:NEXT]->(b)
delete r

Hope this helps, Thank you

Upvotes: 1

Sumeet Sharma
Sumeet Sharma

Reputation: 2583

Use below cypher query.

MATCH (a:user {id: "12345"}) 
WITH a  
MERGE (a)-[:NEXT]->(c:data {id: "2"}) 
WITH a,c
MATCH (a)-[r:NEXT]->(b:data) 
WHERE b<>c 
WITH a, collect(r) AS rels, collect(b) AS bs, c  
FOREACH (t IN range(0,length(rels)-1)| 
FOREACH (t1 IN [bs[t]]| 
FOREACH (t2 IN [rels[t]]|
MERGE c-[:NEXT]->t1 
DELETE t2))) 
RETURN a,c

The above query will create a new relation with node a and data node c with id: "2" and if any other nodes of data type previously connected will be appended after new node c

Upvotes: 1

Related Questions