Skip to content Skip to sidebar Skip to footer

How To Get & Set Cosmos Db Continuation Token In Javascript

Using the V2 Javascript SDK for CosmosDb, I'm getting the TOP 10 items from the db: var query = 'SELECT TOP 10 * FROM People' const querySpec = { query: query }; var result =

Solution 1:

Emre. Please refer to my working sample code:

const cosmos = require('@azure/cosmos');
const CosmosClient = cosmos.CosmosClient;

const endpoint = "https://***.documents.azure.com:443/";                 // Add your endpoint
const masterKey = "***";  // Add the masterkey of the endpoint
const client = new CosmosClient({ endpoint, auth: { masterKey } });
const databaseId = "db";
const containerId = "coll";

async function run() {
    const { container, database } = await init();
    const querySpec = {
        query: "SELECT r.id,r._ts FROM root r"
    };
    const queryOptions  = {
        maxItemCount : 1
    }
   const queryIterator = await container.items.query(querySpec,queryOptions);
    while (queryIterator.hasMoreResults()) {
        const { result: results, headers } = await queryIterator.executeNext();
        console.log(results)
        console.log(headers)

        if (results === undefined) {
            // no more results
            break;
        }   
    }
}

async function init() {
    const { database } = await client.databases.createIfNotExists({ id: databaseId });
    const { container } = await database.containers.createIfNotExists({ id: containerId });
    return { database, container };
}

run().catch(err => {
    console.error(err);
});

You could find the continuation token in the console.log(headers).

enter image description here

More details ,please refer to the source code.


Update Answer:

Please refer to my sample function:

    async function queryItems1(continuationToken) {
    const { container, database } = await init();
    const querySpec = {
        query: "SELECT r.id,r._ts FROM root r"
    };
    const queryOptions  = {
        maxItemCount : 2,
        continuation : continuationToken
    };

    const queryIterator = await container.items.query(querySpec,queryOptions);
    if (queryIterator.hasMoreResults()) {
        const { result: results, headers } = await queryIterator.executeNext();
        console.log(results)
        const token = headers['x-ms-continuation'];
        if(token){
            await queryItems1(token);
        }       
    }   
}

Post a Comment for "How To Get & Set Cosmos Db Continuation Token In Javascript"