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.

Admin commands to create multiple DBs in Python

Hello,

Is it possible to create a new database with a specific name via the Python-Neo4j driver?
For example, executing the following Admin commands in a Python script:

:USE system
CREATE DATABASE dbname

Thanks, Ariel

1 ACCEPTED SOLUTION

It is possible to create a database through the driver. Here is a code snippet:

from neo4j import GraphDatabase


driver = GraphDatabase.driver(uri, auth=(username, password))

with driver.session(database="system") as session:
    with session.begin_transaction() as tx:
        res = tx.run("CREATE DATABASE db1 IF NOT EXISTS")
    bookmark = session.last_bookmark()

with driver.session(database="db1", bookmarks=(bookmark,)) as session:
    with session.begin_transaction() as tx:
        res = tx.run('CREATE (n:Node {foo: "bar"}) RETURN n')
        print(list(res))

Note that I'm passing along the bookmark of the session that creates the database to the session that uses the database. If you don't do this, you might end up with an error because the second session tries to start the transaction on db1 before it has been fully created.

View solution in original post

8 REPLIES 8

Too bad...,
but thanks anyhow!

You can maybe do a batch (.bat) script do achieve it. Then use Python to execute the batch script

Thanks for the suggestion!
I was thinking to create a TXT file with the names of all the databases that I want to create, e.g.:

:USE system
CREATE DATABASE db1;
CREATE DATABASE db2;

...

and to paste this manually into the Neo4j Browser. I would need to do this only once.

Yeah you could do this, it's the more easier

It is possible to create a database through the driver. Here is a code snippet:

from neo4j import GraphDatabase


driver = GraphDatabase.driver(uri, auth=(username, password))

with driver.session(database="system") as session:
    with session.begin_transaction() as tx:
        res = tx.run("CREATE DATABASE db1 IF NOT EXISTS")
    bookmark = session.last_bookmark()

with driver.session(database="db1", bookmarks=(bookmark,)) as session:
    with session.begin_transaction() as tx:
        res = tx.run('CREATE (n:Node {foo: "bar"}) RETURN n')
        print(list(res))

Note that I'm passing along the bookmark of the session that creates the database to the session that uses the database. If you don't do this, you might end up with an error because the second session tries to start the transaction on db1 before it has been fully created.

This is really useful.. Didn't know this. Thank you!

I didn't know you could do this

Thank you so much Rouven!
Although I already chose for the "manual" solution, it is good to know that the Python driver has this great option.