如何在JavaScript中获取和设置Cosmos Db连续令牌

时间:2018-09-03 12:18:07

标签: javascript azure-cosmosdb

使用V2 Javascript SDK for CosmosDb,我从数据库中获得了前10名:

var query = "SELECT TOP 10 * FROM People"

const querySpec = {
    query: query
};

var result = await container.items.query(querySpec).toArray();

如何获取下10个结果的延续令牌,以及如何在下一个查询中设置它?

1 个答案:

答案 0 :(得分:2)

Emre。请参考我的工作示例代码:

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);
});

您可以在console.log(headers)中找到延续标记。

enter image description here

更多详细信息,请参阅source code


更新答案:

请参考我的示例函数:

    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);
        }       
    }   
}