Skip to main content
 首页 » 编程设计

python之在 Google DataStore 上使用限制/偏移量时获取总行数

2025年05月04日43birdshome

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

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

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

我可以使用 count() 来获取 total,如下所示:

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

但这似乎与 fetch() 的运行时间一样长,导致整个过程需要两倍的时间。

有更好的方法吗?

请您参考如下方法:

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

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

为此,您可以引入一个新实体 ListingStoreByAccount,并将 account_id 作为 key 中的 id,这样它就可以被非常快速地获取,并且 code>IntegerProperty 带当前计数。

您需要在每次创建或删除 ListingStore 实体时更新适当的实体,也许在交易中(每个 ListingStoreByAccount 作为实体组)如果并发是一个问题。

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