问题
I am exploring GraphDB query languages, and asked a question about transitive closure support in OriendDB here? I would like to see how Neo4J supports this feature:
Briefly, suppose I have Nodes all labeled as PERSON. And I have Edges called "father" connecting these persons together. For a given node say p1, I am wondering how the following query looks like in Neo4j:
find all the ancestors of p1?
I am not familiar with Neo4j syntax (but I think it is possible to define such an structure I explained above there), so excuse me for skipping the schema definition.
回答1:
This is how you can find all the ancestors of a PERSON
named "Fred Flintstone":
MATCH (p1:PERSON {name: "Fred Flintstone"})-[:father*]->(f)
RETURN f;
And this is how you can find all his descendants:
MATCH (p1:PERSON {name: "Fred Flintstone"})<-[:father*]-(d)
RETURN d;
回答2:
You can take this further and create a sort for the ancestors:
MATCH (n:Person{RN:1}) match p=n-[:father|mother*..99]->x return x.RN as RN,x.fullname as Name,length(p) as generation,reduce(srt2 ='', q IN nodes(p)| srt2 + replace(replace(q.sex,'M','A'),'F','B')) AS sortOrder order by sortOrder
This was developed for a genealogy app, so it has both mother and father. In this case, the fathers sort before (A) the mothers (B). If you are just looking for the ends of the lines (union_id=1 means no parents):
MATCH (n:Person{RN:1}) match p=n-[:father|mother*..99]->x where x.union_id=1 return x.RN as RN,x.fullname as Name,length(p) as generation,reduce(srt2 ='', q IN nodes(p)| srt2 + replace(replace(q.sex,'M','A'),'F','B')) AS sortOrder,x.union_id
来源:https://stackoverflow.com/questions/29973806/neo4j-query-for-modeling-transitive-clousure