0
votes

In the Neo4J database, I have an entity 'Person' which can be related to other Persons as a PARENT_OF or a CHILD_OF relationship

For instance, the cypher query

Match (p:Person) - [:PARENT_OF] -> (c:Person) where id(p) = {p_id} return p, c

will return a parent record p with id p_id and a set of child records c

In Java, I have a base class Person

public class Person {
    @GraphId private Long id;
    @Property @NonNull private String profile;
    @Relationship(type="RELATED_TO", direction="OUTGOING") Experience experience;
    @Relationship(type="RELATED_TO", direction="OUTGOING") Activity activity;
}

and 2 child classes

@NodeEntity (label="Person")
public class Parent extends Person {
    @Relationship(type="PARENT_OF", direction="OUTGOING") private List<Child> child;
}

@NodeEntity (label="Person")
public class Parent extends Person {
    @Relationship(type="PARENT_OF", direction="OUTGOING") private List<Child> children;
}

Assume suitable getters and setters

I want to use Neo4J-OGM in Java and get a Parent given a parent's id. This parent should have a list of Children pre-loaded

So a query case like this:

    final Iterable<Parent> parents = session.query(Parent.class, "MATCH (parent:Person) - [:PARENT_OF] -> (child:Person) where id(parent) = {personId} return parent --> child", ImmutableMap.of("personId", 15L));
    System.out.println (parent.get(0));

I want the parent object to be loaded with all its children (the List attribute should be populated).

How do I go about doing this? I need to use Cypher.

1

1 Answers

2
votes

The simplest thing to do is

Person parent = session.load(Person.class, parentId); The default loading depth is one so it will load children. You can customize this depth if you wish.

Not sure why you need to use Cypher but if you want to, then the loadAll methods on the Session which accept Filter should work.

Here's an example https://github.com/neo4j/neo4j-ogm/blob/master/src/test/java/org/neo4j/ogm/domain/tree/Entity.java

used in test https://github.com/neo4j/neo4j-ogm/blob/master/src/test/java/org/neo4j/ogm/integration/tree/TreeIntegrationTest.java