问题描述
我有一个集合 activity
,其中包含一个字段 activityDate
,其中包含日期,如 2017-02-24T19:04:18Z
I have a collection activities
it contains a field activityDate
which contain date like 2017-02-24T19:04:18Z
我想从此集合中删除所有早于 numberOfDays
的记录.
I want to delete all record from this collection which are older that numberOfDays
.
我正在通过编写cosmosdb存储过程来执行此任务
I am performing this task by writing cosmosdb stored procedure
我尝试
var query = 'SELECT * FROM activities a WHERE a.activityDate > = "' + numberOfDays+ '"';
我在执行查询时遇到问题,因为它在语法上不正确
I am facing problem executing the query as it's not syntactically correct
或者可以有另一种方式.
Or there can be some another way of doing it.
先谢谢了.
推荐答案
以下是我的问题的解决方案:
Here is the solution for my problem:
// SAMPLE STORED PROCEDURE
function deleteActivitiesBackDate(numberOfDays) {
var context = getContext();
var collection = context.getCollection();
var link = collection.getSelfLink();
var response = context.getResponse();
//validate inputs
if(!numberOfDays || (typeof numberOfDays != "string")){
return errorResponse(400, (!numberOfDays) ? "numberOfDays is Undefined":"String type is expected for numberOfDays.");
}
var targetDate = new Date();
targetDate.setDate(targetDate.getDate() - numberOfDays);
console.log("targetDate is "+targetDate);
var query = 'SELECT * FROM activities a WHERE a.activityDate < "' + targetDate+ '"';
var run = collection.queryDocuments(link, query, {}, callback);
function callback(err, docs) {
if (err){
return errorResponse(400, err.message);
}
if (docs.length > 0){
deleteDoc(docs);
}else {
return errorResponse(400, "The document was not found.");
}
}
if (!run) {
return errorResponse(400, "The document could not be deleted.");
}
function deleteDoc(document) {
var docDeleted = collection.deleteDocument(document._self, function(err, result){
if (err){
return errorResponse(400, err.message);
}
response.setBody(result);
});
if (!docDeleted) {
return errorResponse(400, "The document could not be deleted.");
}
};
function errorResponse(code,message){
var errorObj = {};
errorObj.code = code;
errorObj.message = message;
errorObj.date = getDateTime();
return response.setBody(errorObj);
}
function getDateTime(){
var currentdate = new Date();
var dateTime = currentdate.getFullYear() + "-" +(currentdate.getMonth()+1)+ "-" + currentdate.getDate()+ " " +currentdate.getHours()+":"+currentdate.getMinutes()+":"+currentdate.getSeconds();
return dateTime;
}
}
与此同时,还需要启用分区以执行(<,>,< =,> =,!=)
With that you also need to enable partitions to execute (<,>,<=,>=,!=)
所以尝试:
也在 custom
内也有以下JSON
also inside custom
have following JSON
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/*",
"indexes": [
{
"kind": "Range",
"dataType": "String",
"precision": -1
},
{
"kind": "Range",
"dataType": "Number",
"precision": -1
},
{
"kind": "Spatial",
"dataType": "Point"
},
{
"kind": "Spatial",
"dataType": "Polygon"
}
]
}
],
"excludedPaths": []
}
谢谢
这篇关于如何从CosmosDB特定日期删除记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!