为 Neo4j 节点实体生成分层数据

Generate Hierarchical data for a Neo4j node entity

下面的细节将描述我的问题。
框架:Spring启动
数据库:Neo4j 嵌入式模式
存储库:GraphRepository

下面是我的组织 POJO

@NodeEntity
public class Organization extends UserBaseEntity {

   @NotNull(message = "error.Organization.name.notnull")
   private String name;
   private String email;

   @Relationship(type = HAS_SUB_ORGANIZATION)
   private List<Organization> children = new ArrayList<>();

 // getter and setters
}

到目前为止尝试过: 使用具有特定深度的 findOne。
例如: graphRepo.findOne(organizationId,3);
这将 return 完整的组织网络。

我需要为组织生成层次结构数据。
有什么方法可以进行递归查询以生成组织层次结构。


我只需要 id,name,children(Sub-Organization)
示例格式

[
    {
      id: 1,
     name: 'Organization 1',
      children: [
        { id: 2, name: 'Organization 1 ' },
        { id: 3, name: 'Organization 2' }
      ]
    },
   {
     id: 4,
     name: 'Organization 2',
     children: [
       { 
          id: 5,
          name: 'Organization 2 unit'
       }

     ]
   }
 ] 

我建议您使用我在应用程序中实施的解决方案,如下所示: 首先,为映射数据定义一个OrganizationDTO。

Class OrganizationDTO {
private String code;
private String name;
private List<OrganizationDTO> children;
//Add setter and getter

}
然后,使用密码查询修改您的存储库:

@Repository
public class OrganisationRepositoryImpl implement OrganisationRepository {

    private final Neo4jUtils neo4jUtils;


    List<Organisation> findOrg(String orgCode) {

        Map<String, Object> params = map("orgCode", orgCode);

         String query = "MATCH (n:Organisation)-[r:HAS_SUB_ORGANIZATION*]->(m:Organisation) "+
        " where n.code = {orgCode} return " +
        " n.code, "+
        " n.name, "+ 
        " m is not null haschildren ," +
        " m as children" +
    return neo4jUtils.cypher(query, params)
                .map(this::mapToOrganization)
                .collect(toList());
    }

    private OrganizationDTO mapToOrganization(Map<String, Object> map) {
        OrganizationDTO org = new OrganizationDTO(
            map.get("n.code"), map.get("n.name"));
        if((Boolean)map.get("haschildren")){
            org.setChilren(m.get("children");
        }

    }
}


当实施 Rest API 时,OrganizationDTO 会按照您的预期响应 JSON 格式。希望对您有所帮助。