Search code examples
neo4jspring-data-neo4j

Cannot fetch child entity (contains) in spring-data-neo4j


Parent class

@Node
@NoArgsConstructor
@AllArgsConstructor
public class Dish {
  @Id
  private String dishName;
  @Relationship(type = "CONTAINS", direction = Relationship.Direction.OUTGOING)
  private List<Ingredient> ingredients;
  private String recipeUrl;
  private String cuisine; // New field for cuisine
  private String dishType; // New field for dish type

  // Getters and Setters for all fields

Child class

@Getter
@Setter
public class Ingredient {
  @Id
  private String nameInEnglish;
  private String nameInHindi;
  private String nameInGerman;

mapping in neo4j

MATCH (d:Dish {dishName: 'Paneer Butter Masala'}),
      (i1:Ingredient {nameInEnglish: 'Paneer'}),
      (i2:Ingredient {nameInEnglish: 'Butter'}),
      (i3:Ingredient {nameInEnglish: 'Tomato'})
CREATE (d)-[:CONTAINS]->(i1),
       (d)-[:CONTAINS]->(i2),
       (d)-[:CONTAINS]->(i3);

neo4j browser returns one dish with one ingredient

    MATCH (d:Dish)-[:CONTAINS]->(i:Ingredient)
    WHERE i.nameInEnglish = "Paneer"
    RETURN d,collect(i) as ingredients

but Java response has 1 dish with an ingredient arraylist always empty in the IntelliJ debugger debugger using query enter image description here but the neo4j browser enter image description here


Solution

  • The browser is "lying" to you. In the settings page, there is a option that is checked by default to connect your results:

    Neo4j Browser settings

    In reality, your query does not return the relationships but only the Dishes and Ingredients.

    For this to work in SDN, you would have to provide the relationships and alter your query into something like this

    MATCH (d:Dish)-[r:CONTAINS]->(i:Ingredient)
    WHERE i.nameInEnglish = "Paneer"
    RETURN d, collect(r), collect(i) as ingredients
    

    Otherwise SDN cannot guess what it should do with the returned Dish and the Ingredients. It will not just connect them because they also could have been connected via another relationship type.