Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4j, Cypher: Conditional Create

Tags:

neo4j

cypher

I have a specific problem to make a conditional create statement. I can't use MERGE here since the MATCH AND CREATE statement are different. Here is the query..

....
WITH m
OPTIONAL MATCH (x)-[r1:FeedNext{user_id:USER_ID}]->(m)-[r2:FeedNext{user_id:USER_ID}]->(y) 
WHERE x IS NOT NULL AND y IS NOT NULL 
WITH x, y, m, r1, r2
CREATE (x)-[:FeedNext{user_id:USER_ID}]->(y) 
DELETE r1, r2 
RETURN m 

returns 0 rows For the case when x and y are null.

While m is not returned null for the same case on running..

....
WITH m
OPTIONAL MATCH (x)-[r1:FeedNext{user_id:USER_ID}]->(m)-[r2:FeedNext{user_id:USER_ID}]->(y) 
RETURN m 

What's the way around, to return the value of m in all cases?

like image 418
red-devil Avatar asked Jul 17 '14 12:07

red-devil


1 Answers

Your WHERE condition limits CREATE by making sure it´s never reached if x and y are NULL, but then the RETURN clause is not reached either. If you want to return whether or not you create you have to filter only the CREATE clause. One way to do so is by creating and deleting within a FOREACH clause. The FOREACH clause takes a collection, and you can do your filtering by letting the collection be empty in the one case and contain x,y in the other case. With nested FOREACH you can do that like so

....
WITH m
OPTIONAL MATCH (x)-[r1:FeedNext {user_id:{USER_ID}}]->(m)-[r2:FeedNext {user_id:{USER_ID}}]->(y)
FOREACH (a IN CASE WHEN x IS NULL THEN [] ELSE [x] END | 
    FOREACH (b IN CASE WHEN y IS NULL THEN [] ELSE [y] END | 
        CREATE a-[:FeedNext { user_id:{USER_ID}}]->b
        DELETE r1, r2
    )
)
RETURN m
like image 54
jjaderberg Avatar answered Oct 18 '22 18:10

jjaderberg