如何编写Cypher查询以返回每个类别的Top N结果
以下 Cypher 描述了如何按 `field_of_study` 属性分组,显示整个 `:Score` 总体中前 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
将产生相同的输出,但前 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"}│ │ │] │ └───────────┴──────────────────────────────┘
此页面有帮助吗?