检索查询结果
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
构建查询后,您可以指定一些检索选项以进一步控制查询返回的结果。如需详细了解如何为应用构建查询,请参阅数据存储区查询。
检索单个实体
要仅检索与查询匹配的单个实体,请使用 Query.get()
(或 GqlQuery.get()
)方法:
q = Person.all()
q.filter("last_name =", target_last_name)
result = q.get()
该方法将返回索引中找到的与查询匹配的第一个结果。
遍历查询结果
使用 Query
或 GqlQuery
对象的 run()
方法遍历查询结果时,Cloud Datastore 会对结果进行批量检索。默认情况下,每批包含 20 个结果,但您可以使用该方法的 batch_size
参数更改此值。您可以持续遍历查询结果,直到返回所有结果或者请求超时。
检索实体的特定属性
如需仅检索实体的选定属性(而非检索整个实体),请使用投影查询。与返回完整实体的查询相比,此类查询运行速度更快,且花费更低。
与之类似,仅限于键的查询将仅返回匹配的实体的键(而非完整实体),以节省时间和资源。要创建此类查询,请在构建查询对象时设置 keys_only=True
:
q = Person.all(keys_only=True)
设置查询限制
您可以为查询指定限制,以控制一个批次中可返回的最大结果数。以下示例将从 Cloud Datastore 中检索身高排名前五的人:
q = Person.all()
q.order("-height")
for p in q.run(limit=5):
print "%s %s, %d inches tall" % (p.first_name, p.last_name, p.height)
后续步骤
- 了解 Cloud Datastore 查询的常见限制。
- 了解查询游标,应用可通过它以便利的批次形式检索查询结果。
- 了解数据一致性以及它如何与 Cloud Datastore 上不同类型的查询搭配使用。
- 了解 Cloud Datastore 查询的基本语法和结构。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-04-01。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-04-01。"],[[["You can refine query results by using various retrieval options to control the data returned."],["The `Query.get()` method allows for the retrieval of a single entity that matches the query criteria."],["Query results can be iterated through in batches, with the default batch size being 20, which can be adjusted with the `batch_size` parameter."],["Projection queries allow you to retrieve only selected properties of an entity, enhancing query speed and efficiency, while keys-only queries only return the keys to the entities, saving time and resources."],["A limit can be set on queries to restrict the number of results returned in a single batch, useful for controlling the amount of data processed."]]],[]]