Skip to content

Instantly share code, notes, and snippets.

@red-0ne
Created September 28, 2011 05:21
Show Gist options
  • Save red-0ne/1247049 to your computer and use it in GitHub Desktop.
Save red-0ne/1247049 to your computer and use it in GitHub Desktop.
gremlin step for building trees from a graph traversal
// tree building gremlin defined step
// toTree()
// Redouane Lakrache, r3d0ne@gmail.com
toTree = {
current = [id:0, children:[]]; //init tree head
tree = [current]
parents = []; //tracking current branch
i = i + 1;
def depth = i; //setp call order
_()
.sideEffect{
def parents_length = parents.size();
def t = [:];
t.v = it;
t.children = [];
if(depth == 1) {
parents = [];
current = tree[0]
current.children.add(t);
}
else {
if(parents_length == depth) {
parents = parents[0..depth - 2];
parents[-1].children.add(t);
current = parents[-1];
}
if(parents_length < depth) {
parents[-1].children.add(t);
current = t;
}
if(parents_length > depth) {
parents = parents[0..depth -2];
current = parents[-1];
current.children.add(t);
}
}
parents.add(t);
}
}
Gremlin.defineStep('toTree', [Vertex, Pipe], toTree)
i = 0;
tree = [];
g = TinkerGraphFactory.createTinkerGraph()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment