如何编写 Cypher 查询以返回每个类别的 Top N 结果
下面的 Cypher 查询说明了如何在整个 :Score 人群中,按 field_of_study 属性显示前 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"}│
│ │] │
└───────────┴──────────────────────────────┘
此页面有帮助吗?