I am trying to simply delete an item inside Record in Algolia, but I can not achieve it.(Im working in Javascript)
My structure is the following in each record:
- title
- desc
- date
I want to delete each item in which the date is equal to (for example): 03/04/17
I was trying the following without good results:
var client = algoliasearch('-------', '-------');
var index = client.initIndex('------');
index.deleteBy({
date:'03/04/17',
}, function(err, content) {
if (err) throw err;
alert(JSON.stringify(content));
});
The date to delete by needs to be specified in the filter parameters and as a unix timestamp.
const date = new Date('03/11/17')
const unixDate = date.getTime() / 1000
//...
index.deleteBy({ filter: `date=${unixDate}` }, callback);
Related
Contact center should not work on holidays so for that we are trying to add holiday list in dynamodb table(which has only one column "date") and write a lambda which will compare with the current date
If the date matches it has to return true
If the date does not match it has to return false
Using this link [https://www.fernandomc.com/posts/eight-examples-of-fetching-data-from-dynamodb-with-node/][1] reference i tried match the current date with existing values
but somehow it is returning Error:"UnexpectedParameter: Unexpected key '7' found in params.ExpressionAttributeValues[':date']"
Edited
Table : Partition key: date (String) and the format is YYYY-DD-MM
var dynamodb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });
exports.handler = async (event) => {
let response = '';
var tableName = "table";
const currentdate = new Date().toISOString().split('T')[0];
try {
var params = {
KeyConditionExpression: '#D = :d',
ExpressionAttributeValues: {
':d': { S: currentdate }
},
ExpressionAttributeNames: {
'#D': 'date'
},
TableName: tableName
};
var result = await dynamodb.query(params).promise()
console.log(JSON.stringify(result))
return true;
} catch (error) {
console.error(error);
return false;
}
};
A couple of problems.
Your ExpressionAttributeValues has the incorrect syntax - you need to tell DynamoDB what data type the field is, like this:
ExpressionAttributeValues: {
':d': { S: currentdate }
},
date is a reserved word in DynamoDB, so you will need to add an ExpressionAttributeNames clause too, like this:
ExpressionAttributeNames: {
'#D': 'date'
}
Which also necessitates you changing the KeyConditionExpression to:
KeyConditionExpression: '#D = :d'
Double check the docs if need be.
And just in case you do actually store the date in YYYY-DD-MM format, an ISO date is YYYY-MM-DD. I'm just assuming this is a typo, however.
I want to make a cron job that deletes deeply nested objects in my realtime database that are older than 24 hours.
I have looped through and reached the deeply nested object, but I can't grab/target the value of "addedTime" in the object. How do I grab that value so I can run .remove on the parent? So far, it comes back as undefined or it throws an error.
.schedule("every 1 hours")
.onRun(context => {
const rootDatabaseRef = admin.database().ref("ghostData/");
return rootDatabaseRef.ref.once("value").then(function(snapshot) {
console.log("snap", snapshot.val());
snapshot.forEach(function(userSnapshot) {
let buckets = userSnapshot.val().buckets;
console.log("buckets", buckets);
buckets.forEach(function(bucket) {
let currentTimeYesterday = new Date(
new Date().getTime() - 24 * 60 * 60 * 1000
).getTime();
let addedTime = bucket.val().addedTime;
console.log("curr time", currentTimeYesterday);
console.log("addedTime", addedTime);
});
});
Here is the data in my realtime database as well as the logs from the serverless cloud functions:
I think you're having problems with looping, because when you do this "buckets.forEach(function(bucket)" --> bucket in your case is the first element of the list ,
and every element has a nested dictionary , so first you have to iterate the dictionary and for each key in the dictionary , you'll get another dictionary , and you've to grab
only the added-time value.
I know it's difficult to understand but I think it's happening because you're not looping correctly.
Try the code below or something similar.
buckets.forEach(function(bucket){
let currentTimeYesterday = new ......
bucket.forEach(function(dict){
Object.keys(dict).forEach(k => {
console.log(k, ':', dict[k].addedTime);
let addedTime = dict[k].addedTime;
});
....
}
....
}
I have an application that displays services upon which I would like the user to be able to filter by service name while always being sorted (descending) by date (no sorting on service name).
Also the following question doesn't contain the appropriate solution:
Couch DB filter by key and sort by another field
Below is a simplistic version of the code to give an idea of what I am currently trying (serviceName must be first key as I cannot filter exclusively with the second key):
function(doc) {
if(doc.type && doc.type=="incident"){
emit([doc.serviceName, doc.date], doc)
}
};
Here is a Snippet where from my API writen in Node, that builds the parameters for the query:
if (req.query.search !== "") {
const search = req.query.search;
params = {
limit: limit,
skip: skip,
startkey: [search+"Z"],
endkey: [search],
descending:true,
include_docs: true
};
} else {
params = { limit: limit, skip: skip, descending:true, include_docs: true };
The above code currently filters service name but also sorts by service name before sorting by date. Is there anything I can add like (check snippet below) to force the query to sort the results by date without me having to do it in the code after I get the result.
const sort = [{'date': 'desc'}];
What I want is something like this when filtering by servicename:
SELECT * FROM incidents
WHERE serviceName LIKE #search+'%'
ORDER BY date DESC
But when not filtering by servicename:
SELECT * FROM incidents
ORDER BY date DESC
One way to do this is to ensure that the second element of the array you emit (the date-related bit) goes down as time proceeds. This can be achieved with a bit of hacking in the map function
function(doc) {
if(doc.type && doc.type=="incident") {
// get the date from the document
var d = doc.date;
// remove dash characters
var d1 = d.replace(/\-/g,'');
// convert to integer
var d2 = parseInt(d1)
// Subtract from number representing the year 3000
emit([doc.serviceName, 30000000 - d2], doc)
}
}
You may now query this view in ascending order (without descending=true) and the data will be sorted by serviceName and the time (reversed).
I have a JSON model that is bound to a sap.m.Table. I am trying to filter data based on a column "Date" (bound to property[CreatedOn] of the model) which the service returns in the JSON Object Format ("/Date(timeStamp)"). The table is as below:
sample Date from server:
I am trying to filter the table on the client side but I am not sure on how to implement date filters on the client side. The date displayed are formatted based on
sap.ui.model.type.Date({pattern: 'dd/MM/YYYY'})
The filtering code looks as below:
var fromD = this.getView().byId("idKMFilterPaneDocDateF").getValue() ? new Date(this.getView().byId("idKMFilterPaneDocDateF").getValue()) :
undefined;
var dtFilter = new sap.ui.model.Filter({
path: "CreatedOn",
operator: "EQ",
value1: "dateTime'" + fromD.toJSON() + "'"
});
var binding = oTable.getBinding("items");
binding.filter([filter], "Application");
binding.refresh();
When I execute the above code, I always get "NO Data". I need to implement the "BT" filters as well based on user selection criteria but can't get it to work with "EQ" itself.
Create Custom Filter
var fromD = this.getView().byId("idKMFilterPaneDocDateF").getValue() ? new Date(this.getView().byId("idKMFilterPaneDocDateF").getValue()) :undefined;
var dtFilter = new sap.ui.model.Filter("CreatedOn");
dtFilter.fnTest = function(value) {
//check what value are you getting here. If its string, get only time out of it
//Compare the date values(in milliseconds)
fromD.setHours(0); //get rid of time and concern about date
fromD.setMinutes(0);
fromD.setSeconds(0);
fromD.setMilliseconds(0);
//value should be date object, else change accordingly..
if(fromD.getTime() === value.getTime()){
return true;
}
return false;
};
PS:If you can get working JSFiddle with your coding context, I could debug.
I have a table in my Parse database with columns validFrom and uniqueId. There can be multiple records with the same uniqueId (like a name)
What query do I have to use to get the items with the latest validFrom for a given set of uniqueIds? I tried the following but this limits my search to 1 item for the entire set rather than 1 item per unique_id record:
var UpdateObject = Parse.Object.extend("UpdateObject");
var query = new Parse.Query(UpdateObject);
query.containedIn("unique_id", uniqueIdsArray).select('status', 'unique_id').descending("validFrom").limit(1);
The query semantics are limited, so the only approach is to query for a superset and manipulate the result to what you need. This is better done on the server to limit the transmission of extra objects.
Big caveat: did this with pencil and paper, not a running parse.app, so it may be wrong. But the big idea is to get all of the matching objects for all of the uniqueIds, group them by uniqueId, and then for each group return the one with the maximum validFrom date...
function updateObjectsInSet(uniqueIdsArray ) {
var query = new Parse.Query("UpdateObject");
// find all of the UpdateObjects with the given ids
query.containedIn("unique_id", uniqueIdsArray);
query.limit(1000);
return query.find().then(function(allUpdates) {
// group the result by id
var byId = _.groupBy(allUpdates, function(update) { return update.get("unique_id"); });
// for each group, select the newest validFrom date
return _.map(byId, function (updates) {
_.max(updates, function(update) { return -update.get("validFrom").getTime(); });
});
});
}
To place this in the cloud, just wrap it:
Parse.Cloud.define("updateObjectsInSet", function(request, response) {
updateObjectsInSet(request.params.uniqueIdsArray).then(function(result) {
response.success(result);
}, function(error) {
response.error(error);
});
});
Then use Parse.Cloud.run() from the client to call it.