//在图中找到两个年龄最大的人和他们最近出演的三部电影。这需要用到 LIMIT 和 collect() 以及 ORDER BY 的组合。
// Get the two oldest people. 到两个年龄最大的人
MATCH (actor:Person)
WITH actor ORDER BY actor.born LIMIT 2
// Get their three most recent movies. 他们最近出演的三部电影
MATCH (actor)-[:ACTED_IN]->(movie:Movie)
WITH actor, movie ORDER BY movie.released DESC
RETURN actor.name, 2016 -actor.born AS age, collect(movie.title)[..3] AS movies;
/在图中找到两个年龄最大的人和他们最近出演的三部电影。这需要用到 LIMIT 和 collect() 以及 ORDER BY 的组合。
// Get the two oldest people. 到两个年龄最大的人
MATCH (actor:Person)
WITH actor ORDER BY actor.born LIMIT 2
// Get their three most recent movies. 他们最近出演的三部电影
MATCH (actor)-[:ACTED_IN]->(movie:Movie)
WITH actor, movie ORDER BY movie.released DESC
WITH actor, collect(movie)[..3] AS m
// Unwind the collection into rows. 把数组变成散列行
UNWIND m AS movie
RETURN actor.name, 2016 -actor.born AS age, movie.title;
1 collect 的用法 : 将列表转为数组
//1 返回电影名称数组
MATCH (n:Movie) RETURN collect(n.title)
//2 排序
MATCH (n:Movie)
with n
order by n.title desc
RETURN collect(n.title) //对数组内的结果排序后显示出来
//3 去重
RETURN collect( distinct n.title) //对数组内的结果排序并去重后显示出来
2 获取数组中的前6个
match (a:teacher) with collect(a) as t return t[..6]
match (a:teacher) with collect(a.name) as t return t[..6] //前6个, 即 012345个
// ["康民舞", "伍民舞", "余芭蕾", "元芭蕾", "卜舞", "顾舞"]
match (a:teacher) with collect(a.name) as t return t[2..6]
// [ "余芭蕾", "元芭蕾", "卜舞", "顾舞"] //2到6个, 即 2345个
3 获取节点中某关系按时间排名第一的数据
match (b:banji)-->(s:student)-->(j:jilu)
where id(b)=$bid and j.time>$time1 and j.time<$time2
with s, j order by j.time desc
return s.name, collect(j)[..1] as js
//具体测试
match (b:banji)--(s:student)-->(j:jilu)
where id(b)=2226 and j.time>1681205950000 and j.time<1681214969000
with s, j order by j.time desc
return s.name, collect(j)[..1] as js
//性能如何? 待测试
4 按关系类型统计
MATCH (n { name: 'Tom Hanks' })-[r]->()
RETURN type(r), count(*)
//对应sql : SELECT type,count(*) FROM Person where name = 'Tom Hanks' Group by type
按字段值统计1
//统计各个年龄出生的人数
match (n:Person) return n.born,count(*)
//对应sql: Select born,count(*) from Person group by born
//按 state, age ,height 统计
match (a:Test) return a.state,a.age,a.height,count(*) as c order by a.state, a.age
5 同一个表中分组排序返回前三
//按类型统计数量
match (a:order)
return a.type, count(*) as c
//按类型找出最大金额
match (a:order)
return a.type, max(a.money) as c
//按类型找出金额排名前3的的订单
match (a:order)
with a order by a.money desc
with a.type as type, collect(a) as ss
return type , ss[..3]
性能有待测试