Couchbase document dates search - DateTime.Now() - couchbase

I have a document in CB which has two dates, a start date and an end date. Let's say, a product's price discount. 10% off starting from today and ends next Friday. How can I get all the documents from CB which have a valid discount today?
I made a view and have the following in it:
var dt = new Date();
Which gets today's date. Then I can do a simple
if(doc.FromDate < dt && doc.ToDate > dt){ emit([ ..... ]);
This filters the documents how I want. But...
Question
Is this a good approach re view and index updating? Will the index update every day because the date changed? Just trying to understand the working of CB in this respect
What is the best approach for this type of searching? If not possible please tell me!
Cheers
Robin
Note: Please note, the question is NOT like this here or this here

Let's me clarify something here:
the map() function is used to create/update the index on disk, and this occurs just "after" the document is saved on disk. This is why using date.now() in the map reduce does not really makes sense.
So what you will do is to emit the date for example emit( dateToArray(doc.startDate) );
then when you query the view(index) you can use the startkey & endkey to do a range query.
&startkey=[2013,4,16]&endkey=[2013,4,24]

the index won't be updated just because system date changed, you have to update the document. also view indexer doesn't allow you to pass any arguments defined by user. in this case you should emit the data and use date as a part of the key to filter on view query. I guess the same behaviour for SQL indexes too. you cannot predict when exactly this document will indexed, in your example you are freezing timestamp when the doc has been indexed, it isn't even the time when it was changed

Related

How to construct time based if statements in Google Apps Script

I am attempting to construct some simple logic for events happening in my spreadsheet before a certain time (2pm) each day. I want the function to tell me if the date entered represented in this case by the variable "tradeTime" is before or after 2pm CT. No matter what sample data I have provided the if statement always returns "Trade time is not less than 2pm"
You are currently comparing strings to each other which is not what you really want to do. Time or Date is easily converted to a numbers using the valueOf() function on a Date Object, see references for more information.
Therefore I propose the following:
function isEventBeforeDeadline(){
const eventTime = new Date(2021,2,2,14).valueOf()
const deadline = new Date(2021,2,2,14).valueOf()
if( eventTime > deadline ) console.log("Too late")
if( eventTime < deadline ) console.log("Made it")
if( eventTime == deadline ) console.log("Perfect")
}
Please also see comments on your post.
Be more specific with where these dates are coming from, e.g. from a Sheet, API, or elsewhere. We assume you will not enter dates manually everyday.
Do not post images of code, post code of code. See here > Syntax Highlighting for Code
You are likely to need to build a Trigger which runs automatically. Then the code needs to be modified check for todays date, I assume. Here are the docs for that.
Reference
- Date Object
- Date.valueOf()

Speeding up a Django query for "latest" ForeignKey related object

With Django, I have two related models. Call the first one BaseObject. The second one is called BaseObjectObservation, where every 6 hours or so I create a new BaseObjectObservation that's linked via ForeignKey to a BaseObject and has another field for a particular data point about that object at that time, along with a timestamp.
As you might expect, one thing I'm always interested in is the "latest" BaseObjectObservation for a given BaseObject. The trouble is that there are now lots of observations for each BaseObject, and even with ~500 BaseObjects, loading a page with all BaseObjects with each one's latest observation gets very slow.
Any recommendations on how to speed up the retrieval of the latest observation?
Bonus question: I'm also interested in how each object's observation has changed over the last 24 hours. Previously I tried querying for the latest observation and the observation closest to 24 hours ago and calculating the difference; this was too slow as well. Any recommendations here?
You could do something like:
class BaseObject(models.Model):
pass
class BaseObjectObservation(models.Model):
base_object = models.ForeignKey(BaseObject, related_name="observations")
last_modification = models.DateTimeField(auto_now=True)
latest = models.BooleanField(default=False)
def save(self, **kwargs)
if not self.pk:
# mark new instance as latest
self.latest = True
# Update previous observations
self.base_object.observations.update(latest=False)
super().save(**kwargs)
Then, if you want to get latest observations with their base object, you can do :
BaseObjectObservation.objects.filter(latest=True).select_related('base_object')
The select_related clause will save you 500 queries, because it will fetch the base object, along the observation.
Since you do everything in a single query, performance should be better. However, some cleanest solutions may exist without needing to store a boolean on each instance.
Bonus
For your bonus question, you can probably get some inspiration here:
import datetime
from django.utils import timezone
24_hours_ago = timezone.now() - datetime.timedelta(hours=24)
current_observation = base_object.observations.get(latest=True)
closest_observation_greater = base_object.observations.filter(creation_date__gt=24_hours_ago).first()
closest_observation_lower = base_object.observations.filter(creation_date__lte=24_hours_ago).first()
if closest_observation_greater - target > target - closest_observation_lower:
return closest_observation_lower
else:
return closest_observation_greater
However, that's still two query for each observation. You can probably optimize it, but you can also reduce
the number of element you display on each page. Do you really need to display 500 elements on the same page ?

'ts' Number Field in Database? (ex. 1428881039)

Thanks to outsourced development, each row in many of my tables has an undocumented field called ts with values such as 1428881039. This is in addition to an actual created_at timestamp field with values such as 2015-04-12 17:23:59 MDT.
These values are passed to this function before displaying it on the web page:
public static function display($ts, $created_at, $format = self::FORMAT_DETAILS){
if ($ts && Session::has('tz_offset')){
$adminTzOffset = Session::get('tz_offset');
$final = (int)$ts - (int)$adminTzOffset;
return date($format, $final);
}else{
return $created_at;
}
}
I understand that it has something to do with possibly making sure that the date shown is for the user's correct timezone, but it doesn't even seem to work; it ends up showing the wrong time. Obviously I could just display the created_at timestamp, but I understand what this is trying to do here.
Any ideas of what this ts field represents?
Based on the info garnered from the comments, I would say that the ts field is an attempt to record UTC time - since it appears it is 6 hours ahead of your created_at field.
The code itself looks like it is using this $ts value to calculate a corrected timezone based off a session variable. If you're getting incorrect times, maybe the logged in user has an incorrect timezone setup?

Between two datestime in mysql

I am trying to create a reservation system in php and i have a table(field_data_field_dateres) that has two fields field_dateres_value(start date) and field_dateres_value2(end date). I want to find that if conflict occurs between reservation.
Currently table has a record like this
currently i am writing query like this
SELECT * FROM `field_data_field_dateres` WHERE field_dateres_value>='2014-02-14 20:15:00' and field_dateres_value2<='2014-02-14 20:30:00';
where 2014-02-14 20:15:00,2014-02-14 20:30:00 will come from php side. But its returning empty record. thanks for any help.
Since you want to find times overlapping (conflicting), the query you want is probably instead;
SELECT * FROM `field_data_field_dateres`
WHERE field_dateres_value < '2014-02-14 20:30:00'
AND field_dateres_value2 > '2014-02-14 20:15:00';
Note that the end time is compared to your new time slot's start time, and the start time is compared to your new time slot's end time. This will return all time windows in the database that overlap with your new range.
An SQLfiddle to test with.

Sails.js Waterline query modifiers for dates with sails-mysql?

I just started using Sails.js with its ORM, Waterline, and absolutely love it, but I am not sure how to use query modifiers for dates. I am using sails-mysql. Specifically, I am trying to get rows that have a datetime field between two specific dates. I have tried doing this:
MyModel.find()
.where({ datetime_field: { '>=': startDate } })
.where({ datetime_field: { '<=': endDate } })
.done(function(err, objects){
// ...
});
startDate and endDate are two Date objects. I have also tried converting them to strings with toString(). In both cases, I get every row from the database instead of rows between the two dates. Is there a way to do this or is this functionality not yet part of either Waterline or sails-mysql?
In the same boat (no pun intended) but using sails-mongo.
Provided you have the correct date formatting (as Jeremie mentions). I personally store dates in UTC moment(startDate).toISOString() on the client you can moment(startDate) to work in local date and time.
Looking at the Waterline source for deferred queries (see the where method) it applies the most recent datetime_field criteria it finds to be valid.
After trawling through code, searches and the group I didn't find anything that helped. I sure hope I've missed something obvious, but for now my current suggestion would be to anchor the results on your startDate and then cap it with a limit,
e.g.
.where({ datetime_field: { '>=': startDate } })
.limit(100)
You will need to format your date as a string in the YYYY-MM-DD format.
If you need help formatting your dates, moment.js has a lot of cool features for that.
formating your date would look something like
var formatedStartDate = moment(startDate).format('YYYY-MM-DD');