偏移分页与游标分页

Offset pagination vs Cursor pagination

我正在研究分页,我有一些问题。

  1. 两种方法有什么区别?
  2. 基于游标的分页的最佳用例?
  3. 基于游标的分页可以转到特定页面吗?
  4. 基于光标的分页可以返回上一页吗?
  5. 两者在性能上有什么区别吗?

我的想法

我认为基于游标的要复杂得多,这使得基于偏移的分页更加可取。只有以实时数据为中心的系统需要基于游标的分页。

Cursor pagination is most often used for real-time data due to the frequency new records are added and because when reading data you often see the latest results first. There different scenarios in which offset and cursor pagination make the most sense so it will depend on the data itself and how often new records are added. When querying static data, the performance cost alone may not be enough for you to use a cursor, as the added complexity that comes with it may be more than you need.

引自此awesome blog post,编码愉快!

另外,看看这个:

Pagination is a solution to this problem that ensures that the server only sends data in small chunks. Cursor-based pagination is our recommended approach over numbered pages, because it eliminates the possibility of skipping items and displaying the same item more than once. In cursor-based pagination, a constant pointer (or cursor) is used to keep track of where in the data set the next items should be fetched from.

此解释来自Appolo GraphQL docs.

This post explains the difference between them.

What is the difference between two approaches?

差别很大。一个使用偏移量分页,另一个使用游标分页。两种方法都有多种 pros/cons。例如,偏移分页可以跳转到任何页面,而在 Cursor-based 分页中,您只能跳转到 next/previous 页。

下面的实现也有很大的不同。 Offset 很可能要加载从第一页到你想要获取的页面的所有记录。有一些技术可以避免这种情况。

如需了解更多优缺点,我建议阅读 the article

Best use-case for a cursor based pagination?

如果您使用的是关系数据库并且有数百万条记录。查询高 Offset 可能会花费很多 time/timeout,而游标分页会更高效。

Can cursor based pagination go to a specific page?

不,这是该方法的缺点之一。

Can cursor based pagination go back to the previous page?

提供两个游标作为响应是一种非常常见的技术,一个包含上一页,另一个包含下一页。如果是这样,您可以转到上一页。否则,你不能。

Are there any performance differences between the two?

是的!看我上面的评论。