Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
05-06-2021 04:16 AM
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
Solved! Go to Solution.
05-06-2021 07:37 AM
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.
05-06-2021 06:32 AM
Too bad...,
but thanks anyhow!
05-06-2021 06:53 AM
You can maybe do a batch (.bat) script do achieve it. Then use Python to execute the batch script
05-06-2021 07:20 AM
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.
05-06-2021 07:23 AM
Yeah you could do this, it's the more easier
05-06-2021 07:37 AM
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.
04-29-2022 04:16 PM
This is really useful.. Didn't know this. Thank you!
05-06-2021 07:44 AM
I didn't know you could do this
05-06-2021 08:45 AM
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.
All the sessions of the conference are now available online