Reputation: 1070
following details will describe my problem.
Framework:Spring boot
Database: Neo4j Embedded mode
Repository: GraphRepository
Below is my Organization 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
}
Tried so Far:
Using findOne with specific depth.
for example:
graphRepo.findOne(organizationId,3);
This will return full network of organization.
I Need to generate hierarchy data for Organization.
Is there any way to make recursive query to generate Organization hierarchy.
I need just id,name,children(Sub-Organization)
Sample format
[
{
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'
}
]
}
]
Upvotes: 2
Views: 486
Reputation: 122
I suggest you a solution I implemented in my application like below: First, define a OrganizationDTO for mapping data.
Class OrganizationDTO {
private String code;
private String name;
private List<OrganizationDTO> children;
//Add setter and getter
}
Then, modified your repository with your cypher query:
@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");
}
}
}
When Rest API implemented, the OrganizationDTO responds a JSON format as your expected. I hope that this can help you.
Upvotes: 1