Recupera resultados de consultas
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Después de construir una consulta, se pueden especificar opciones de recuperación para tener más control sobre los resultados que se muestran.
Accede a consultas del almacén de datos para obtener más información acerca de cómo estructurar consultas en tu aplicación.
Recupera una sola entidad
Para recuperar solo una entidad única que coincida con tu consulta, usa el método Query.get()
(o GqlQuery.get()
):
q = Person.all()
q.filter("last_name =", target_last_name)
result = q.get()
Esto muestra el primer resultado que se encontró en el índice que coincide con la consulta.
Itera a través de los resultados de la consulta
Cuando iteras sobre los resultados de una consulta mediante el método run()
de un objeto Query
o GqlQuery
, Cloud Datastore recupera los resultados por lotes. Según la configuración predeterminada, cada lote contiene 20 resultados, pero puedes cambiar este valor si usas el parámetro batch_size
del método. Puedes seguir iterando a través de los resultados hasta que se muestren todos o hasta que se agote el tiempo de espera de la solicitud.
Cómo recuperar propiedades seleccionadas de una entidad
Para recuperar solo las propiedades seleccionadas de una entidad, en lugar de la entidad completa, usa una consulta de proyección. Este tipo de consulta se ejecuta más rápido y cuesta menos que las que muestran entidades completas.
Del mismo modo, una consulta de solo claves ahorra tiempo y recursos porque solo muestra las claves de las entidades con las que coincide, en lugar de las entidades completas en sí. Para crear este tipo de consulta, configura keys_only=True
cuando construyas el objeto de consulta:
q = Person.all(keys_only=True)
Establece un límite para tu consulta
Puedes especificar un límite para tu consulta a fin de controlar el número máximo de resultados que se muestran en un lote. En el siguiente ejemplo, se recuperan las cinco personas más altas de 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)
Próximos pasos
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-09-04 (UTC)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-04 (UTC)"],[[["\u003cp\u003eYou can refine query results by using various retrieval options to control the data returned.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003eQuery.get()\u003c/code\u003e method allows for the retrieval of a single entity that matches the query criteria.\u003c/p\u003e\n"],["\u003cp\u003eQuery results can be iterated through in batches, with the default batch size being 20, which can be adjusted with the \u003ccode\u003ebatch_size\u003c/code\u003e parameter.\u003c/p\u003e\n"],["\u003cp\u003eProjection 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.\u003c/p\u003e\n"],["\u003cp\u003eA 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.\u003c/p\u003e\n"]]],[],null,["# Retrieving query results\n\nAfter constructing a query, you can specify a number of retrieval options to\nfurther control the results it returns.\nSee [datastore queries](/appengine/docs/legacy/standard/python/datastore/queries) for more information on structuring queries for your app.\n\nRetrieving a single entity\n--------------------------\n\n\u003cbr /\u003e\n\nTo retrieve just a single entity matching your query, use the method [`Query.get()`](/appengine/docs/legacy/standard/python/datastore/queryclass#Query_get) (or [`GqlQuery.get()`](/appengine/docs/legacy/standard/python/datastore/gqlqueryclass#GqlQuery_get)): \n\n q = Person.all()\n q.filter(\"last_name =\", target_last_name)\n\n result = q.get()\n\nThis returns the first result found in the index that matches the query.\n\n\nIterating through query results\n-------------------------------\n\nWhen iterating through the results of a query using the `run()` method of a [`Query`](/appengine/docs/legacy/standard/python/datastore/queryclass#Query_run) or [`GqlQuery`](/appengine/docs/legacy/standard/python/datastore/gqlqueryclass#GqlQuery_run) object, Cloud Datastore retrieves the results in batches. By default each batch contains 20 results, but you can change this value using the method's `batch_size` parameter. You can continue iterating through query results until all are returned or the request times out.\n\nRetrieving selected properties from an entity\n---------------------------------------------\n\nTo retrieve only selected properties of an entity rather than the entire entity, use a [*projection query*](/appengine/docs/legacy/standard/python/datastore/projectionqueries). This type of query runs faster and costs less than one that returns complete entities.\n\nSimilarly, a [*keys-only query*](/appengine/docs/legacy/standard/python/datastore/queries#keys-only_queries) saves time and resources by returning just the keys to the entities it matches, rather than the full entities themselves. To create this type of query, set `keys_only=True` when constructing the query object: \n\n q = Person.all(keys_only=True)\n\nSetting a limit for your query\n------------------------------\n\nYou can specify a *limit* for your query to control the maximum number of results returned in one batch. The following example retrieves the five tallest people from Cloud Datastore: \n\n q = Person.all()\n q.order(\"-height\")\n\n for p in q.run(limit=5):\n print \"%s %s, %d inches tall\" % (p.first_name, p.last_name, p.height)\n\nWhat's next?\n------------\n\n- Learn the [common restrictions](/appengine/docs/legacy/standard/python/datastore/query-restrictions) for queries on Cloud Datastore.\n- Learn about [query cursors](/appengine/docs/legacy/standard/python/datastore/query-cursors), which allow an application to retrieve a query's results in convenient batches.\n- [Understand data consistency](/appengine/docs/legacy/standard/python/datastore/data-consistency) and how data consistency works with different types of queries on Cloud Datastore.\n- Learn the [basic syntax and structure of queries](/appengine/docs/legacy/standard/python/datastore/queries) for Cloud Datastore."]]