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

Too bad...,
but thanks anyhow!

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

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 :slight_smile:

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.

2 Likes

I didn't know you could do this :open_mouth:

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.