Skip to content

Instantly share code, notes, and snippets.

@jexp
Created November 13, 2019 10:29
Show Gist options
  • Save jexp/1e2dddf76fa6d4c02f0c583c18634105 to your computer and use it in GitHub Desktop.
Save jexp/1e2dddf76fa6d4c02f0c583c18634105 to your computer and use it in GitHub Desktop.
Transfer Data from an RDBMS via JDBC to any Neo4j DB
@GrabConfig( systemClassLoader=true )
@Grapes([
@Grab(group='org.postgresql', module='postgresql', version='42.0.0'),
@Grab(group='org.neo4j.driver', module='neo4j-java-driver', version='1.7.5')
])
import org.neo4j.driver.v1.*;
import java.sql.*;
Class.forName("org.postgresql.Driver");
table = "products";
JDBC = [url:"jdbc:postgresql://db-examples.cmlvojdj5cci.us-east-1.rds.amazonaws.com/northwind", user:"n4examples", pass:"36gdOVABr3Ex"];
NEO4J=[url:"bolt://localhost:7687", user:"neo4j",pass:"test"];
// see https://neo4j.com/docs/api/java-driver/current/
GraphDatabase.driver(NEO4J.url, AuthTokens.basic(NEO4J.user, NEO4J.pass)).withCloseable{ neo4j ->
DriverManager.getConnection(JDBC.url, JDBC.user, JDBC.pass).withCloseable { rdbms ->
stmt = rdbms.prepareStatement("SELECT * FROM ${table}");
stmt.executeQuery().withCloseable{ rs ->
neo4j.session().withCloseable{ session ->
session.writeTransaction { tx ->
meta = rs.getMetaData();
cols = meta.getColumnCount();
while (rs.next()) {
params = [:];
for (int i=0;i<cols;i++) {
params[meta.getColumnName(i+1)]=rs.getObject(i+1);
}
println(params);
tx.run("CREATE (n:${table}) SET n += \$props", Values.value([props:params])).consume();
}
}
}}}}
@jexp
Copy link
Author

jexp commented Nov 13, 2019

You can install groovy using sdkman.io via sdk use groovy 2.5.8
and then run groovy rdbms2graph.groovy

Bildschirmfoto 2019-11-13 um 11 36 20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment