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');
constCosmosClient = cosmos.CosmosClient;

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

asyncfunctionrun() {
    const { container, database } = awaitinit();
    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 resultsbreak;
        }   
    }
}

asyncfunctioninit() {
    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:

asyncfunctionqueryItems1(continuationToken) {
    const { container, database } = awaitinit();
    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){
            awaitqueryItems1(token);
        }       
    }   
}

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