开发者

How to store tree structure using neo4j and gremlin

开发者 https://www.devze.com 2023-03-24 02:31 出处:网络
I want to store following directory tree structure using neo4j local database and Gremlin in Java. (ROOT)

I want to store following directory tree structure using neo4j local database and Gremlin in Java.

           (ROOT)
        /          \
    Dir2           Dir3
   开发者_如何转开发 /    \             \
  Dir4   Dir5        Dir6
  /
Dir7 

I have defined a method StorePath(String path).

What i want : When i call StorePath(path) with path = "Root\Dir2\Dir4\Dir7" then data should be stored as follows

         Root
         /
       Dir2
       /
     Dir4
     /
   Dir7 

where Root and Dir* are vertices with blank edges. Please help me with the java code.


private static final RelationshipType SUB_DIR = DynamicRelationshipType.withName("SUB_DIR");

public void storePath(String path) {
    Node dir = graphDb.getReferenceNode();
    for (String name : path.split(File.separator)) {
        dir = obtainSubDir(dir, name);
    }
}

private Node obtainSubDir(Node dir, String name) {
    Node subDir = getSubDir(dir,name);
    if (subDir!=null) return subDir;
    return createSubDir(dir, name);
}

private Node getSubDir(Node dir, String name) {
    for (Relationship rel : dir.getRelationships(SUB_DIR, Direction.OUTGOING)) {
        final Node subDir = rel.getEndNode();
        if (subDir.getProperty("name", "").equals(name)) return subDir;
    }
    return null;
}

private Node createSubDir(Node dir, String name) {
    Node subDir = dir.getGraphDatabase().createNode();
    subDir.setProperty("name", name);
    dir.createRelationshipTo(subDir, SUB_DIR);
    return subDir;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消