Hello! Is there a way to create lots of nodes at once using a loop?
For example, making calls from the JavaScript driver (code is reduced):
let session = driver.session()
for (i=0; i<100; i++){
create_node(i)
}
function create_node(counter){
session.writeTransaction(function(tx) {
tx.run(`CREATE (a:User {id: $id}`, {
id: counter
})
session.close()
}
If I use session.run(), I get an error saying "Queries cannot be run directly on a session with an open transaction; either run from within the transaction or use a different session".
If I use tx.run() I get an unhandled promise rejection (even if I include a "catch" statement).
Any help with this would be appreciated! :)
Hello,
Looks like there may be some typos here, as I don't see the closing parenthesis around the node, and it looks like you used backticks instead of quotes around the query string.
As to your original question, if you instead create a list of ids, or if you know the bounds of the range you would like to use, you can then UNWIND the list back into rows and create all the nodes at once in a single transaction.
For example, if you passed in an ids
list parameter:
UNWIND $ids as id
CREATE (a:User {id:id})
Or if you knew your range was 0 to 100 and used this explicitly in the query:
UNWIND range(0, 100) as id
CREATE (a:User {id:id})
And if you needed a dynamic range you could pass in the bounds as parameters and use that in your query.
1 Like