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

标签 python google-app-engine google-cloud-datastore app-engine-ndb

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作为示例代码。

关于python - 在 Google DataStore 上使用限制/偏移量时获取总行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29126206/

相关文章:

google-app-engine - 是否可以在没有 Google Cloud SQL 的情况下在 App Engine/PHP 中使用数据库

google-app-engine - App Engine Go 中的无条件查询

google-app-engine - GAE 上传下载数据/导入数据到本地主机以在我的开发服务器上进行测试

google-app-engine - 谷歌应用引擎的数据库建模,用于实体的多次修订

python - 在 Dockerfile 中的 python 图像上安装 google-chrome-stable 时出错

python - 如何有条件地修改 numpy 多维数组的每个元素?

java - 使用 GAE/J URLFetchServiceFactory.getURLFetchService() 的 JUnit 代码测试

python - Python中根据多个条件返回列的方法

python - 在 Plone 中添加文件夹的自定义限制

python - 是否可以将 Python 与 Go 一起使用