Neo4j Cypher sort on collections

吃可爱长大的小学妹 提交于 2019-12-12 04:46:19

问题


I have a query (below) that returns collections of nodes containing create dates. I want to sort the rows by newest create date. Some of the rows have one create date, other rows have several. As can be seen, the node "name4" should be first. What corrections should I make to my query? Thanks.

MATCH (node:node) 
WITH node 
ORDER BY node.created DESC 
RETURN count(node.name) AS count, node.name, collect(node.created) AS created

count   node.name   created
3       "name1"     [1410234609620,1410234606534,1410234506799]
1       "name2"     [1410234434936]
1       "name3"     [1410234454573]
2       "name4"     [1410463902552,1410460561481]
1       "name5"     [1410234485185]
2       "name6"     [1410234548527,1410234525740]

回答1:


Assuming your timestamps are correctly ordered within your collections, you can take the first timestamp from each of the collections using HEAD([1, 2, 3]), which will return the first element of the collection. I've loaded this value into the timeSort property and used it as the ordering criteria.

MATCH (node:node) 
WITH node
ORDER BY node.created DESC 
WITH count(node.name) AS count, node.name as name, collect(node.created) AS created
WITH count, name, head(created) as timeSort, created
RETURN count, name, created
ORDER BY timeSort DESC



回答2:


This query first finds the max timestamp, x, for each name, and then sorts the results.

MATCH (node:node)
WITH node.name AS name, COLLECT(node.created) AS created
WITH name, created, REDUCE(t = 0, c IN created | CASE WHEN c > t THEN c ELSE t END) AS x
RETURN LENGTH(created) AS count, name, created
ORDER BY x DESC


来源:https://stackoverflow.com/questions/25796226/neo4j-cypher-sort-on-collections

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!