Archi Elements and Relationships to Gremlin-based Graph DB

Started by blakesha, June 06, 2024, 13:45:42 PM

Previous topic - Next topic

blakesha

Hi All

Just wanted to post this snippet of code for others to use that shows how to inject from Archi into a Gramlin-based Graph Database if anyone else is interested. It adds the properties of both the elements and the relationships to the graph.

console.log("Start");

Java.addToClasspath("C:\\Users\\XXX\\Documents\\Archi\\scripts\\gremlin-driver-3.7.2-shaded.jar");
Java.addToClasspath("C:\\Users\\XXX\\Documents\\Archi\\scripts\\slf4j-api-2.0.9.jar");

var imports = new JavaImporter(java.util, java.util.concurrent, org.apache.tinkerpop.gremlin.driver);

with(imports) {
    var clusterBuilder = Cluster.build();
    clusterBuilder.addContactPoint("localhost");
    clusterBuilder.port(65400);
    clusterBuilder.credentials("/dbs/<database>/colls/<container>", "<passkey>");
    clusterBuilder.enableSsl(false);
    clusterBuilder.serializer("GRAPHSON_V2");
    var cluster = clusterBuilder.create();

    // Connect to the cluster and drop everthing from the graph. Closing will ensure the task completes.
    var client = cluster.connect();
    results = client.submit("g.V().drop()");
    client.close();

    // Reconnect to the cluster and add all vertices and edges for the elements and relationships.
    client = cluster.connect();

    var elements = $("element");
    var query = "";
    var props = "";

    elements.each(function(obj) {
        props = ""
        obj.prop().forEach(property => {
            props += ".property('"+property+"', '"+obj.prop(property)+"')";
        });
        query = "g.addV('"+obj.type+"').property('element_id', '"+obj.id+"').property('name', '"+obj.name+"')"+props;
       
        results = client.submit(query);
    });
 
    var relationships = $("relationship");
    relationships.each(function(obj) {
        props = ""
        obj.prop().forEach(property => {
            props += ".property('"+property+"', '"+obj.prop(property)+"')";
        });
        query = "g.V().has('element_id', '"+obj.source.id+"').addE('"+obj.type+"').property('name', '"+obj.name+"')"+props+".to(g.V().has('element_id', '"+obj.target.id+"'))";
       
        results = client.submit(query);
    })

    // Close and cleanup client and cluster.
    client.close();
    cluster.close();
}

console.log("End");

If you google search for the two jars required they are easily found on the interweb.

Enjoy.

Phil Beauvoir

If you value and use Archi, please consider making a donation!
Ask your ArchiMate related questions to the ArchiMate Community's Discussion Board.