如何使用neo4j和gremlin存储树结构

时间:2011-08-01 14:03:23

标签: graph neo4j graph-databases gremlin

我想在Java中使用neo4j本地数据库和Gremlin存储以下目录树结构。

           (ROOT)
        /          \
    Dir2           Dir3
    /    \             \
  Dir4   Dir5        Dir6
  /
Dir7 

我已经定义了一个方法StorePath(String path) 我想要的:当我使用path =“Root \ Dir2 \ Dir4 \ Dir7”调用StorePath(路径)时,数据应存储如下

         Root
         /
       Dir2
       /
     Dir4
     /
   Dir7 

其中Root和Dir *是带有空白边的顶点。 请帮我解决java代码。

1 个答案:

答案 0 :(得分:6)

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;
}