如何编写 Cypher 查询以返回每个类别的前 N 个结果
以下 Cypher 描述了如何显示整个 :Score 种群中按 field_of_study 属性细分的 Top 5 测试分数。
create (n:Score {student_id: 'DC001', score: 89, field_of_study: 'chemistry'});
create (n:Score {student_id: 'MK812', score: 97, field_of_study: 'chemistry'});
create (n:Score {student_id: 'JT909', score: 77, field_of_study: 'chemistry'});
create (n:Score {student_id: 'SA743', score: 84, field_of_study: 'chemistry'});
create (n:Score {student_id: 'EH331', score: 68, field_of_study: 'chemistry'});
create (n:Score {student_id: 'AE034', score: 89, field_of_study: 'economics'});
create (n:Score {student_id: 'DC001', score: 91, field_of_study: 'economics'});
create (n:Score {student_id: 'JF623', score: 74, field_of_study: 'economics'});
create (n:Score {student_id: 'TP810', score: 77, field_of_study: 'economics'});
create (n:Score {student_id: 'BB317', score: 82, field_of_study: 'economics'});
create (n:Score {student_id: 'AH042', score: 61, field_of_study: 'economics'});
create (n:Score {student_id: 'RV448', score: 59, field_of_study: 'economics'});
运行
match (n:Score)
with n order by n.score desc
with n.field_of_study as class,collect(n.student_id + '('+ n.score +')') as student
return class,student[0..5]
order by class
将返回以下输出
class student[0..5] chemistry [MK812(97), DC001(89), SA743(84), JT909(77), EH331(68)] economics [DC001(91), AE034(89), BB317(82), TP810(77), JF623(74)]
并且在上面,学生的成绩已通过引用 '('+ n.score +')'
附加到他们的 student_id 值。
Cypher 也可以写成
match (n:Score)
with n order by n.score desc
with n.field_of_study as class,collect({student_id:n.student_id, score:n.score}) as student
return class,student[0..5]
order by class
将产生相同的输出,但 Top 5 学生将列在作者和分数的映射中:因此
╒═══════════╤══════════════════════════════╕ │"class" │"student[0..5]" │ ╞═══════════╪══════════════════════════════╡ │"chemistry"│[{"student_id":"MK812","score"│ │ │:"97"},{"student_id":"DC001","│ │ │score":"89"},{"student_id":"SA│ │ │743","score":"84"},{"student_i│ │ │d":"JT909","score":"77"},{"stu│ │ │dent_id":"EH331","score":"68"}│ │ │] │ ├───────────┼──────────────────────────────┤ │"economics"│[{"student_id":"DC001","score"│ │ │:"91"},{"student_id":"AE034","│ │ │score":"89"},{"student_id":"BB│ │ │317","score":"82"},{"student_i│ │ │d":"TP810","score":"77"},{"stu│ │ │dent_id":"JF623","score":"74"}│ │ │] │ └───────────┴──────────────────────────────┘
此页面是否有帮助?