简体   繁体   中英

In cypher, return node with latest date in relationship property

Here is the scenario. I am modeling a person that lives at one or more different locations. Included in the relationship is the start date (represented as ms since epoch) when they moved in.

(:person{name:'bill'}) -[:livesAt {since:1111000}]->(:place{name:'apartmentA'})

(:person{name:'bill'}) -[:livesAt {since:2222000}]->(:place{name:'apartmentB'})

I want to write a query that returns the single place node corresponding to the most recent place of residence for a given person. The most recent place is corresponding to the largest value in the 'since' property of the relationship. Note that multiple people may live at a given place.

I was trying something like this:

MATCH (n:person {name: 'bill'})-[r:livesAt]->(m:place)
WITH r
ORDER BY r.since DESC
LIMIT 1
MATCH (n:person)-[r]->(o:place)
RETURN o.name

If my query worked with the example above, I would expect to get 'apartmentB' back as the result.

The problem (maybe) is located on the last match clause. I tested a simpler version on Neo4j SandBox and seemed OK:

MATCH (n:person {name: 'bill'})-[r:livesAt]->(m:place)
WITH n, m
ORDER BY r.since DESC
LIMIT 1
RETURN m.name as place, n.name as person

Alternately, you can use max clause to get the max value of the relationship then find that node that corresponds to the most recent residence.

MATCH (n:person {name: 'bill'})-[r:livesAt]->(:place)   
WITH max(r.since) as most_recent, n
MATCH (n)-[:livesAt {since: most_recent}]->(m:place)
RETURN m

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM