John
John

Reputation: 351

How do I call neo4j GraphAlgoFactory aStar algorithm from Gremlin?

I'm a data scientist with mediocre coding skills, so until now in working with neo4j, I've avoided java in favor of Cypher and Gremlin.

I've shoved a bunch of graph data into neo4j with a weight property on each edge. I'd like to run aStar or dijkstra's on this graph from within the gremlin console if possible. JUNG seems not to have a weighted shortest path algorithm, so I've turned to GraphAlgoFactory, but all the discussion of it online seems to be in straight Java.

My goal is to get the shortest weighted path between two vertices of my choosing where the weights are dictated by the weight properties on the edges.

Thanks!

Upvotes: 3

Views: 1757

Answers (1)

Bobby Norton
Bobby Norton

Reputation: 1504

I'll give you an example to use as a starting point to explore your own graph. Start by firing up Gremlin and defining a utility method to create edges:

def edge(Graph g, Vertex v1, Vertex v2, int weight) {
    e = g.addEdge(null, v1, v2, "connects");
    e.setProperty("weight", weight);
}

Now create a simple graph with 4 nodes and 4 edges:

g = new Neo4jGraph("/tmp/dijkstra")
v1 = g.addVertex(1);
v2 = g.addVertex(2);
v3 = g.addVertex(3);
v4 = g.addVertex(4);

edge(g, v1, v2, 13);
edge(g, v1, v4, 20);
edge(g, v2, v3, 3);
edge(g, v4, v3, 40);

Since the version of Gremlin in the console runs on Groovy, you can mix and match Groovy and Java seamlessly to use the GraphAlgoFactory:

import org.neo4j.graphalgo.GraphAlgoFactory;
import org.neo4j.graphalgo.CommonEvaluators;
import org.neo4j.kernel.Traversal;

dijkstra = GraphAlgoFactory.dijkstra(Traversal.expanderForAllTypes(), CommonEvaluators.doubleCostEvaluator("weight"))
path = dijkstra.findSinglePath(((Neo4jVertex)v1).getRawVertex(), ((Neo4jVertex)v3).getRawVertex())
println path
// (1)--[connects,0]-->(2)--[connects,2]-->(3) weight:16.0

The code to use the GraphAlgoFactory comes mainly from the Neo4j documentation. The only difference is that you need to cast each Blueprints Vertex to an org.neo4j.graphdb.Node, since the GraphAlgoFactory doesn't understand Blueprints.

Upvotes: 3

Related Questions