Cosmos DB 存储过程
Posted
技术标签:
【中文标题】Cosmos DB 存储过程【英文标题】:Cosmos DB stored procedure 【发布时间】:2020-04-22 16:13:29 【问题描述】:我正在尝试运行一个程序来查询文档并根据一些规则调整一些属性,这些规则由我传递给查询的参数决定。
function downsample(ageInDays, downsampleFactor)
var collection = getContext().getCollection();
var responseBody =
deleted: 0,
message: ""
;
var downsampledDocuments = [];
var count = 0;
collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root r ' +
'WHERE (DATEDIFF(day, r.EventProcessedUtcTime, GETDATE()) > ' + ageInDays+ 'AND r.downsamplingFactor < ' + downsampleFactor + ')' +
'OR' +
'((DATEDIFF(day, r.EventProcessedUtcTime, GETDATE()) > ' + ageInDays + ' AND r.downsamplingFactor = null )' +
'ORDER BY r.did, r.resourceType ASC',
function (err, documents, options)
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else perform the downsampling
if (!documents || !documents.length)
var response = getContext().getResponse();
responseBody.message = "No documents found";
response.setBody(responseBody);
else
// We need to take into consideration that in a lot of cases, the data will already be downsampled so we
// example: previous downsampling factor of documents: 4, if a new downsampling is performed on these docs with factor 8 then we need to
var adjustedDownSamplingFactor;
if (documents[0].downsamplingFactor == null)
adjustedDownSamplingFactor = downsampleFactor;
else
adjustedDownSamplingFactor = downsampleFactor / documents[0].downsamplingFactor;
var aggregatedDocument = documents[0];
var documentValueSum = 0;
var documentCount = 0;
var aggregatedDocumentValue = 0;
for(doc in documents)
if(!aggregatedDocument)
aggregatedDocument = doc;
if(documentCount >= adjustedDownSamplingFactor || aggregatedDocument.did !== doc.did || aggregatedDocument.resourceType !== doc.resourceType)
// preparing aggregated document
aggregatedDocumentValue = documentValueSum / documentCount;
aggregatedDocument.value = aggregatedDocumentValue;
aggregatedDocument.downsamplingFactor = downsampleFactor;
//Adding the downsampled data to the Array which will be uploaded to the cosmosdb
downsampledDocuments.push(aggregatedDocument);
aggregatedDocument = null;
documentCount = 0;
documentValueSum = 0;
continue;
documentValueSum += doc.value;
documentCount++;
var response = getContext().getResponse();
tryDelete(documents);
// Call the CRUD API to create a document.
tryCreate(downsampledDocuments[count], callback);
responseBody.message = "Downsampling was succesful"
response.setBody(responseBody);
);
所以我没有将任何文档传递给查询,因此我不知道必须为存储过程提供哪个分区键。有什么方法可以避免提供分区键吗?我正在从 API 调用此存储过程,但不断收到一条消息,提示我应该提供分区键。
【问题讨论】:
【参考方案1】:有什么方法可以避免提供分区 钥匙?
很遗憾,没有。您必须提供一个分区键值。
【讨论】:
以上是关于Cosmos DB 存储过程的主要内容,如果未能解决你的问题,请参考以下文章
Azure Cosmos DB - '请求率很大。删除项目时可能需要更多请求单位的错误
在哪里存储以及如何在客户端维护来自 cosmos db 的延续令牌