Neo4j, empty list in first unwind stop second unwind from executing
01-26-2023 11:19 AM
I have two unwinds, that create some relationships and nodes, but if the list for the first unwinds is empty, the second unwind doesn't execute.
How can I fix that?
CALL apoc.periodic.iterate(
"
UNWIND $POSTS as post
RETURN post
",
"
MERGE (p:Post{id: post.id})
WITH p, post
UNWIND post.tags as value
MERGE (t:Tag{tag: value})
MERGE (t)-[:has_tag]->(p)
WITH p, post
UNWIND post.user_mentions as user_mention
MERGE (u1:User{id: user_mention})
MERGE (p)-[:mentions]->(u1)
",
{batchSize: 500, params: {POSTS: $POSTS}, iterateList:true}
)
Example results
Parameters, with non-empty tags
[
{
"id": 123,
"tags": [1],
"user_mentions": [123, 234],
}
]
Graph created in database - Expected result
Parameters, with empty tags
[
{
"id": 123,
"tags": [],
"user_mentions": [123, 234],
}
]
Graph created in the database (Lacking 'mentions' relationships) - Unexpected result
1 REPLY 1
01-26-2023 11:48 AM - edited 01-26-2023 03:24 PM
The behavior is expected. If the 'unwind' on line 10 results in zero records, the query stops. Try the following:
CALL apoc.periodic.iterate(
"
UNWIND $POSTS as post
RETURN post
",
"
MERGE (p:Post{id: post.id})
forEach(value in post.tags |
MERGE (t:Tag{tag: value})
MERGE (t)-[:has_tag]->(p)
)
forEach(user_mention in post.user_mentions |
MERGE (u1:User{id: user_mention})
MERGE (p)-[:mentions]->(u1)
)
",
{batchSize: 500, params: {POSTS: $POSTS}, iterateList:true}
)
Test 1: No missing data
Test 2: Missing Tag data
Test 3: Missing user_mentions data