如何使用 nodejs sdk 在 cosmos db 中定义正确的索引路径?

How do I define a correct indexing path in cosmos db using the nodejs sdk?

我目前 运行 遇到问题,试图为我的一个 cosmosdb 容器定义索引策略。我在 cosmosdb 中有一个容器,用于保存与用户会话相关的数据。我正在使用节点 sdk 来定义我的容器、分区键和索引策略。以下是我如何为会话容器定义索引策略和分区键。

else if(containerId.includes("sessions"))
    {
        indexingPolicy = {
            includedPaths: [ {"path" : "/startTime/"} ]
        };
        partitionKey = { paths: ["/id"] };
    }

当我发出 POST 请求并且容器不存在时,它将根据我在配置文件中定义的策略创建容器。但是,当我尝试 post 一个新会话时,我会根据索引策略收到各种错误。以下是我到目前为止所做的尝试以及遇到的错误。

{"path" : "/startTime/"} --> The indexing path '\/startTime\/' could not be accepted, failed near position '11'. Please ensure that the path is a valid path. Common errors include invalid characters or absence of quotes around labels.

{"path" : "/startTime/*"} --> "The special mandatory indexing path \"\/\" is not provided in any of the path type sets. Please provide this path in one of the sets."

{"path" : "/startTime/?"} --> "The special mandatory indexing path \"\/\" is not provided in any of the path type sets. Please provide this path in one of the sets."

{"path" : "/startTime"} --> "The indexing path '\/startTime' could not be accepted, failed near position '10'. Please ensure that the path is a valid path. Common errors include invalid characters or absence of quotes around labels."

任何有关如何正确定义索引策略的帮助将不胜感激!

Any indexing policy has to include the root path /* as either an included or an excluded path

a path leading to a scalar value (string or number) ends with /?

为了您的代码正常工作,您可以试试这个:

const indexingPolicy = {
    includedPaths: [ {"path" : "/*"},{"path" : "/startTime/?"} ]
}

await container.replace({
    id: containerId,
    partitionKey: { paths: ["/id"] },
    indexingPolicy: indexingPolicy
});

但据我所知,如果你的 includedPaths 中有 {"path" : "/*"},则不需要添加 {"path" : "/startTime/?"}。因为 /* 可以包含 "/startTime/?".

参考:Indexing policies in Azure Cosmos DB