擷取查詢結果
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
建構查詢後,您可以指定多個擷取選項,進一步控制傳回的結果。如要進一步瞭解如何建構應用程式的查詢,請參閱資料儲存庫查詢。
擷取單一實體
如果只想擷取與查詢相符的單一實體,請使用 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 查詢的基本語法與結構。
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-06-16 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-06-16 (世界標準時間)。"],[[["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."]]],[]]