Scala Slick. Wrong pagination \w Postgres

二次信任 提交于 2019-12-23 01:19:28

问题


I'm trying to make simple pagination using Slick with Postgres, but it does not work as expected.

// Table 
// "users_pkey" PRIMARY KEY, btree (id)
// "users_id_idx" btree (id)
val id: Column[Option[Long]] = column("id", O.PrimaryKey, O.AutoInc, O.DBType(BigSerial))

// Pagination queries
users.drop(0).take(20).sortBy(_.id.desc).list
users.drop(20).take(20).sortBy(_.id.desc).list

But results are not ordered as expected. Users ordered by id on inside page, e.g. first page will be like 40, 35, 34 ... 4, 2 and second 39, 38, 36, ... 3, 1.


回答1:


The issue is that you are sorting after taking your values. If, in the initial order, 39 is in the 21st position and you take and sort the first 20 values, it cannot be sorted into the correct place, as you sort without it there.

If you want correct ordering, you should sort your users before taking the chunks, e.g:

val sortedUsers = users.sortBy(_.id.desc)
sortedUsers.drop(0).take(20).list
sortedUsers.drop(20).take(20).list


来源:https://stackoverflow.com/questions/28836336/scala-slick-wrong-pagination-w-postgres

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!