【问题标题】:Generate Hierarchical data for a Neo4j node entity为 Neo4j 节点实体生成分层数据
【发布时间】:2017-04-30 22:00:39
【问题描述】:

以下详细信息将描述我的问题。
框架:Spring boot
数据库: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);
这将返回完整的组织网络。

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


我只需要 id、name、children(子组织)
示例格式

[
    {
      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'
       }

     ]
   }
 ] 

【问题讨论】:

  • 您是否尝试过使用带有@Query 注释的自定义存储库查询?

标签: java neo4j spring-data cypher spring-data-neo4j


【解决方案1】:

我建议您使用我在我的应用程序中实现的解决方案,如下所示: 首先,为映射数据定义一个 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 格式。希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2014-03-08
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多