在 Google DataStore 上使用 limit/offset 时获取总行数

Get total rows when using limit/offset on Google DataStore

ListingStore.query().filter(ListingStore.account_id==1).fetch(10, offset=40)

以上是对 return 我数据集中第 5 页结果的查询。 我的问题是我还必须 return 总行数,如下所示:

{
    "data": ...,
    "limit": 10,
    "offset": 40,
    "total": 1235
}

我可以使用 count() 得到 total,像这样:

ListingStore.query().filter(ListingStore.account_id==1).count()

但这似乎与 fetch() 到 运行 所花的时间一样长,导致整个过程花费了两倍的时间。

有更好的方法吗?

.count() 比等效查询更有效,但仅是一些常数因子(取决于每个实体的大小——与键相比最小) -仅查询)。

您可以获得的唯一显着性能加速是通过 非规范化 您的数据模型 "redundantly" 跟踪每个实体有多少 ListingStore account_id.

为此,您可以引入一个新实体 ListingStoreByAccount,并将 account_id 作为密钥中的 id,这样可以非常快速地获取它,并且 IntegerProperty w/the 当前计数。

您需要在每次创建或删除 ListingStore 实体时更新适当的实体,也许是在交易中(每个 [=13= 使用假密钥 "parent" ] 作为实体组)如果并发性是一个问题。

如果计数器争用成为问题,请改用高速分片计数器,例如 https://cloud.google.com/appengine/articles/sharding_counters and the example https://github.com/GoogleCloudPlatform/appengine-sharded-counters-python 作为示例代码。

除非你一直需要每个account_id的计数,否则我会在需要时使用The Memcache Pattern到运行到count(),并缓存结果以供后续使用页面查询。

然后,正如 Alex 提到的那样,当 ListingStore 更改时删除相应的缓存条目。