Warm tip: This article is reproduced from serverfault.com, please click

How to switch between databases in neo4j using java

发布于 2021-08-11 07:27:32

So I'm using neo4j-enterprise edition loaded with docker.

version: '3'
services:
  neo4j:
    image: neo4j:4.3.2-enterprise
    hostname: neo4j
    container_name: neo4j
    ports:
      - "7474:7474"
      - "7687:7687"
    environment:
      - NEO4J_ACCEPT_LICENSE_AGREEMENT=yes
      - NEO4J_dbms_memory_heap_maxSize=1G
      - NEO4JLABS_PLUGINS=["apoc"]
      - NEO4J_AUTH=neo4j/test
      - NEO4J_apoc_import_file_enabled=true
      - NEO4J_dbms_security_procedures_whitelist= apoc.*
      - NEO4J_dbms_security_procedures_unrestricted= apoc.*

I'm using bolt driver to connect with the neo4j.

public Neo4jSessionFactory(@ConfigProperty(name = "quarkus.neo4j.uri")String databaseUri,
                               @ConfigProperty(name = "quarkus.neo4j.authentication.username")String username,
                               @ConfigProperty(name = "quarkus.neo4j.authentication.password")String password) {
        Configuration neoConfig = new Configuration.Builder().uri(databaseUri**{bolt://localhost:7687}**).credentials(username, password)
                .useNativeTypes().build();
        sessionFactory = new SessionFactory(neoConfig, PACKAGES);
        LOGGER.info("Connection with Neo4j is successful");
    }

Im able to create a seperate database using "CREATE DATABASE <name>" cmd.

However I want to run my queries across the newly created Database. I can simply call "session.query("cypher_query_to_insert")" the data will get loaded to default database neo4j. We can switch between databases in the browser using :use <database name>. However when the cmd is run inside session.query(":use <database_name>") Im getting the following error:

Data Insertion failed. Cause: org.neo4j.driver.exceptions.ClientException: Invalid input ':': expected (line 1, column 1 (offset: 0)) ":use neo4j"

If anyone knows a solution let me know.

Questioner
Nirmal Mahen
Viewed
0
fbiville 2021-08-11 21:15:35

When you create a session, you can pass a SessionConfig instance with the database name, built via SessionConfig.Builder: https://neo4j.com/docs/api/java-driver/current/org/neo4j/driver/SessionConfig.Builder.html#withDatabase-java.lang.String-.