Cursor paging
Stay organized with collections
Save and categorize content based on your preferences.
Use cursor paging.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis content demonstrates how to implement cursor-based pagination for Datastore queries across multiple languages including C#, Go, Java, Node.js, PHP, Python, and Ruby.\u003c/p\u003e\n"],["\u003cp\u003eEach code sample sets a \u003ccode\u003elimit\u003c/code\u003e on the query to define the page size, then uses a \u003ccode\u003ecursor\u003c/code\u003e to define the starting point, enabling the retrieval of specific pages of results.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples demonstrate how to set up authentication using Application Default Credentials to interact with the Datastore mode.\u003c/p\u003e\n"],["\u003cp\u003eThe samples show how to retrieve a cursor for the next page of results, which can then be used to efficiently fetch subsequent pages of data, and is referenced as \u003ccode\u003enextCursor\u003c/code\u003e, \u003ccode\u003enextPageCursor\u003c/code\u003e, or \u003ccode\u003epageCursor\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe content provides links to detailed documentation on Datastore queries and client libraries for each language, as well as the API reference for all the presented languages.\u003c/p\u003e\n"]]],[],null,["# Cursor paging\n\nUse cursor paging.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Datastore queries](/datastore/docs/concepts/queries)\n\nCode sample\n-----------\n\n### C#\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode C# API\nreference documentation](https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Datastore.V1/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n Query query = new Query(\"Task\")\n {\n Limit = pageSize,\n };\n if (!string.IsNullOrEmpty(pageCursor))\n query.StartCursor = ByteString.FromBase64(pageCursor);\n\n return _db.RunQuery(query).EndCursor?.ToBase64();\n\n### Go\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Go API\nreference documentation](https://cloud.google.com/go/docs/reference/cloud.google.com/go/datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n // cursorStr is a cursor to start querying at.\n cursorStr := \"\"\n\n const pageSize = 5\n query := datastore.NewQuery(\"Tasks\").Limit(pageSize)\n if cursorStr != \"\" {\n \tcursor, err := datastore.DecodeCursor(cursorStr)\n \tif err != nil {\n \t\tlog.Fatalf(\"Bad cursor %q: %v\", cursorStr, err)\n \t}\n \tquery = query.Start(cursor)\n }\n\n // Read the tasks.\n it := client.Run(ctx, query)\n var tasks []Task\n for {\n \tvar task Task\n \t_, err := it.Next(&task)\n \tif err == iterator.Done {\n \t\tbreak\n \t}\n \tif err != nil {\n \t\tlog.Fatalf(\"Failed fetching results: %v\", err)\n \t}\n \ttasks = append(tasks, task)\n }\n\n // Get the cursor for the next page of results.\n // nextCursor.String can be used as the next page's token.\n nextCursor, err := it.Cursor()\n\n### Java\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Java API\nreference documentation](https://cloud.google.com/java/docs/reference/google-cloud-datastore/latest/history).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n EntityQuery.Builder queryBuilder =\n Query.newEntityQueryBuilder().setKind(\"Task\").setLimit(pageSize);\n if (pageCursor != null) {\n queryBuilder.setStartCursor(pageCursor);\n }\n QueryResults\u003cEntity\u003e tasks = datastore.run(queryBuilder.build());\n while (tasks.hasNext()) {\n Entity task = tasks.next();\n // do something with the task\n }\n Cursor nextPageCursor = tasks.getCursorAfter();\n\n### Node.js\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Node.js API\nreference documentation](https://cloud.google.com/nodejs/docs/reference/datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n // By default, google-cloud-node will automatically paginate through all of\n // the results that match a query. However, this sample implements manual\n // pagination using limits and cursor tokens.\n async function runPageQuery(pageCursor) {\n let query = datastore.createQuery('Task').limit(pageSize);\n\n if (pageCursor) {\n query = query.start(pageCursor);\n }\n const results = await datastore.runQuery(query);\n const entities = results[0];\n const info = results[1];\n\n if (info.moreResults !== Datastore.NO_MORE_RESULTS) {\n // If there are more results to retrieve, the end cursor is\n // automatically set on `info`. To get this value directly, access\n // the `endCursor` property.\n const results = await runPageQuery(info.endCursor);\n\n // Concatenate entities\n results[0] = entities.concat(results[0]);\n return results;\n }\n\n return [entities, info];\n }\n\n### PHP\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode PHP API\nreference documentation](https://googleapis.github.io/google-cloud-php/#/docs/cloud-datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n /**\n * Fetch a query cursor.\n *\n * @param int $pageSize\n * @param string $pageCursor\n * @param string $namespaceId\n */\n function cursor_paging(int $pageSize, string $pageCursor = '', string $namespaceId = null)\n {\n $datastore = new DatastoreClient(['namespaceId' =\u003e $namespaceId]);\n $query = $datastore-\u003equery()\n -\u003ekind('Task')\n -\u003elimit($pageSize)\n -\u003estart($pageCursor);\n $result = $datastore-\u003erunQuery($query);\n $nextPageCursor = '';\n $entities = [];\n /* @var Entity $entity */\n foreach ($result as $entity) {\n $nextPageCursor = $entity-\u003ecursor();\n $entities[] = $entity;\n }\n\n printf('Found %s entities', count($entities));\n\n $entities = [];\n if (!empty($nextPageCursor)) {\n $query = $datastore-\u003equery()\n -\u003ekind('Task')\n -\u003elimit($pageSize)\n -\u003estart($nextPageCursor);\n $result = $datastore-\u003erunQuery($query);\n\n foreach ($result as $entity) {\n $entities[] = $entity;\n }\n\n printf('Found %s entities with next page cursor', count($entities));\n }\n }\n\n### Python\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Python API\nreference documentation](https://cloud.google.com/python/docs/reference/datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n from google.cloud import https://cloud.google.com/python/docs/reference/datastore/latest/\n\n # For help authenticating your client, visit\n # https://cloud.google.com/docs/authentication/getting-started\n client = https://cloud.google.com/python/docs/reference/datastore/latest/.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html()\n\n\n def get_one_page_of_tasks(cursor=None):\n query = client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_query(kind=\"Task\")\n query_iter = query.fetch(start_cursor=cursor, limit=5)\n page = next(query_iter.pages)\n\n tasks = list(page)\n next_cursor = query_iter.next_page_token\n\n return tasks, next_cursor\n\n### Ruby\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Ruby API\nreference documentation](/ruby/docs/reference/google-cloud-datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n page_size = 2\n query = datastore.query(\"Task\")\n .limit(page_size)\n tasks = datastore.run query\n\n page_cursor = tasks.cursor\n\n query = datastore.query(\"Task\")\n .limit(page_size)\n .start(page_cursor)\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=datastore)."]]