1
votes

Very straightforward question. I have the following function inside my index.js file.

const databaseId = config.database.id;
const collectionId = config.collection.id;
const client = new CosmosClient({ endpoint: CosmosDBName, auth: { masterKey: CosmosDBKey } });
const query = `SELECT c.message.id FROM ${collectionId} c WHERE c.message.timestampFormatted > '${start}' AND c.message.timestampFormatted < '${end}'`;

queryCosmosDB(client, databaseId, collectionId, query)

async function queryCosmosDB(client, databaseId, collectionId, query, context) {
    const querySpec = {
        query: query,
        parameters: []
    };

    const { result: results } = await client.database(databaseId).container(collectionId).items.query(querySpec).toArray();

    for (var queryResult of results) {
        let resultString = JSON.stringify(queryResult);
        context.log(`\tQuery returned ${resultString}\n`);
    }
}

If I execute this function the response is the following error (I omitted some useless information)

ERROR: {"code":400,"body":"{\"code\":\"BadRequest\",\"message\":\"Cross partition query is required but disabled. Please set x-ms-documentdb-query-enablecrosspartition to true, specify x-ms-documentdb-partitionkey, or revise your query to avoid this exception. ...}

Now, I get the partition schema that CosmosDB uses but, in my case, what would be the best thing to do? Should I change somehow the query and if so how? If I have to insert some sort of cross partition query string how should I do that?

The only other question I found regarding this is this SO's question but I don't manage data as he does since I think the SDK has changed a lot from a year and a half ago. I'm currently using this tutorial as baseline.

Thanks a lot in advance for the help!

1

1 Answers

2
votes

You can simply enable cross partition queries using the NodeJS sdk by providing it as part of the options on the query function level.

async function queryCosmosDB(client, databaseId, collectionId, query, context) {
    const querySpec = {
        query: query,
        parameters: []
    };

    const options = {
        enableCrossPartitionQuery: true
      };

    const { result: results } = await client.database(databaseId).container(collectionId).items.query(querySpec, options).toArray();

    for (var queryResult of results) {
        let resultString = JSON.stringify(queryResult);
        context.log(`\tQuery returned ${resultString}\n`);
    }
}