neo4j 分组排序返回前3

文章介绍了Neo4j图形数据库中collect函数的多种用法,包括将列表转换为数组、对数组进行排序、去重,以及获取数组的子集。同时展示了如何根据关系类型和节点属性进行数据统计和分组查询,例如按时间排序、按类型统计数量和找寻金额最高的订单。
摘要由CSDN通过智能技术生成

//在图中找到两个年龄最大的人和他们最近出演的三部电影。这需要用到 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


//性能如何? 待测试

按关系类型统计

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]

性能有待测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值