alexanoid
alexanoid

Reputation: 25842

Neo4j Cypher check if node is ancestor of child node

I have a following class:

@NodeEntity
public class Product {

    private final static String CONTAINS = "CONTAINS";

    @GraphId
    private Long id;

    @RelatedTo(type = CONTAINS, direction = Direction.INCOMING)
    private Set<Product> parentProducts = new HashSet<>();

}

I'm trying to implement a method:

public boolean isProductAncestor(Product productId, Product childProductId) {
    //some Cypher query
}

that will check if productId is an ancestor(any depth up to the root) of childProductId.

I need a Cypher query for it.

Upvotes: 0

Views: 254

Answers (1)

FrobberOfBits
FrobberOfBits

Reputation: 18022

This query finds the path between them:

MATCH path=(p:Product)-[:CONTAINS*]->(m:Product)
WHERE id(p) = {idp} AND id(m) = {idm}
RETURN path LIMIT 1;

If you get a result, that means that m is an ancestor of p. If you get nothing, there's no relationship between them.

Upvotes: 1

Related Questions