timestamp in milliseconds and date range - elasticsearch query string - date

I have a timstamp in milliseconds, like 1645825932144
I'd like to make a date range query with elastic search query string for being able to get all records whom timestamp is in the last 24h:
timestamp:[now-24h TO now]
This does not work as timestamp is in milliseconds and now produces strings like 2001-01-01 13:00:00
Is it possible to achieve this with a cast or something?
I read about range queries and date math, but did not find anything.

It's easy to compute the timestamp in milliseconds for now and now-24h so why not do it in your application logic and build the query out of those values?
For instance (in JS),
const now = new Date().getTime();
const now24h = now - 86400000;
const query = `timestamp:[${now24h} TO ${now}]`;
query would contain the following value:
timestamp:[1647785319578 TO 1647871719578]
UPDATE:
PS: I might have misunderstood the initial need, but I'm leaving the above answer as it might help others.
What you need to do in your case is to change your mapping so that your date field accepts both formats (normal date and timestamp), like this:
PUT your-index/_mapping
{
"properties": {
"timestamp": {
"type": "date",
"format": "date_optional_time||epoch_millis"
}
}
}
Then you'll be able to query like this by mix and matching timestamps and date math:
GET test/_search?q=timestamp:[now-24h TO 1645825932144]
and also like this:
GET test/_search?q=timestamp:[1645825932144 TO now]

Related

Get every round hour from Firestore

I have a data stored in Firestore, the data add to Firestore every second, so in 24 hours I have 1440 documents (24 * 60), I want to fetch only round hour from the Firestore for show it on a Graph, how can I get only round hour from Firestore?
First of all, you will have to store the firestore documents with a timestamp property and then query the documents with the timestamp value which gives a rounded hour using DateTime and DateFormat APIs of flutter.
Once you've got a timestamp back from Firestore, something like :
Timestamp(seconds=1560523991, nanoseconds=286000000)
You can get only rounded hour from the timestamp value using 2 ways :
You need to parse it into an object of type DateTime:
DateTime myDateTime = (snapshot.data.documents[index].data['timestamp']).toDate(); // prints 2020-05-09 15:27:04.074
This will return your Firestore timestamp in the dart's DateTime format. In order to convert your DateTime object you can use DateFormat class from the intl package. You can use your obtained DateTime object to get the format of your choice like this:
Possible Solution 1 :
DateFormat.Hm().format(myDateTime); //prints 15.27
So the query should look for documents with:
DateFormat.m().format(myDateTime) to be “00” as
DateFormat.m() returns minutes and if minutes == 00 then the timestamp is rounded to the nearest hour.
Possible Solution 2 :
Convert timestamp into timestring using :
Let TimeString = snapshot.data.documents[index].data['timestamp']).toDate().toString() // prints ‘2019-12-28 18:48:48.364’
Let time = TimeString.split(“ “)[1] // prints 18:48:48.364
To check if the minutes is “00” :
if time.substring(3,5) == “00”, then it's a rounded hour. //here it is 48
You will have to put these timestamp conversion logics and then query as I mentioned for the rounded hour timestamp. There are no readymade available functions/methods to get the firestore documents with rounded hours.
Firestore supports "IN" Queries.
Store as Timestamp, and try with following
const roundhour1 = new Date('2021-10-01T01:00:00.000z');
const roundhour2 = new Date('2021-10-01T02:00:00.000z');
And then write the query like below:
database.collection("collectionName").where("fieldName", "in", ["roundhour1", "roundhour2"]);
You can have up to 10 values (roundhourX) to check "IN" of, so need to fire 3 queries to get all 24 hours data.

Return documents created less than an hour ago - Elasticsearch query

I need to write a query in ES that only returns documents that have been created less than N minutes, or hours, ago.
There's a createdTimeStamp field in millis, and I am able to write a simple query like this:
{
"query": {
"match": {
"createdTimeStamp": "1526011575731"
}
}
}
However, this query returns the documents where the createdTimeStamp matches the value "1526011575731". Not sure if a range query would work here as the field stores millis values.
You can use range together with now for that. E.g. to get the last hour:
{
"query": {
"range" : {
"createdTimeStamp" : {
"gte" : "now-1h"
}
}
}
}
For minutes, use m instead of h. You can also round, etc., see Date Math documentation.
That your date is in milliseconds should not make a difference, as internally, all comparisons are handled like that anyway:
Internally, dates are converted to UTC (if the time-zone is specified) and stored as a long number representing milliseconds-since-the-epoch.
Queries on dates are internally converted to range queries on this long representation, and the result of aggregations and stored fields is converted back to a string depending on the date format that is associated with the field.
(from https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html)

mongodb difference in time

How can i filter database entries that have a datetime less than 60min in the past?
I tried some date operations as follows in mongodb with two fields timestamp and marketstartime that are of type date in all my documents:
{"$subtract": ["$timestamp", "$marketstartime"]}
but it returns always null for that operation. Why?
My timestamp and marketstartime entries in the db are in date type and look as follows, this should be correct:
2017-12-23 12:00:00.000Z
The actual question I’m trying to solve: How can I get all entries that have a timestamp less than 60 min in the past from now?
A query can composed for documents with timestamp value set less than 60 minutes ago.
from datetime import datetime, timedelta
query = {
'$timestamp': {
'$lt': datetime.now() + timedelta(minutes=-60)
}
}
cursor = db.collection.find(query)

How to do a TIMESTAMP comparison in mongo DB?

I have the following field in all my documents. And the Timestamp below will always be in string and I have no control to change it into any other type.
{ "TIMESTAMP": "2017-09-07T16:43:08.707-04:00" }
Since it is -04:00 the timestamp is in EST. but it can be in any timezone like -05:00 or -6:00 or whatever
The goal is to get all the documents that match the following criteria
currentTime > TIMSETAMP + 4 hours
where currentTime is in UTC and it is something I generate when I query.
I tried something like the following and I am not sure if there is anything wrong with this approach.
(new Date()- ISODate("2017-09-07T16:43:08.707-04:00"))/(60*60*1000) > 4

elasticsearch filter dates based on datetime fields

assuming I have the following nested document structure, where my document contains nested routes with an array of date time values.
{
property_1: ...,
routes: [
{
start_id: 1,
end_id: 2,
execution_times: ['2016-08-28T11:11:47+02:00', ...]
}
]
}
Now I could filter my documents that match certain execution_times with something like this.
query: {
filtered: {
query: {
match_all: { }
},
filter: {
nested: {
path: 'routes',
filter: {
bool: {
must: [
{
terms: {
'routes.execution_times': ['2016-08-28T11:11:47+02:00', ...]
}
},
...
]
}
}
}
}
}
}
But what if I would like to filter my documents based on execution dates. What's the best way achieving this?
Should I use a range filter to map my dates to time ranges?
Or is it better to use a script query and do a conversion of the execution_times to dates there?
Or is the best way to change the document structure to contain both, the execution_date and execution_time?
Update
"The dates are not a range but individual dates like [today, day after tomorrow, 4 days from now, 10 days from now]"
Well, this is still a range as a day means 24 hours. So if you store your field as date time, you can use leverage range query : from 20-Nov-2010 00:00:00 TO 20-Nov-2010 23:59:59 with appropriate time zone for a specific day.
If you store it as a String then you will lose all the flexibility of date maths and you would be able to do only exact String matches. You will then have to do all the date manipulations at the client side to find exact matches and ranges.
I suggest play with range queries using Sense plugin and I am sure it will satisfy almost all your requirements.
-----------------------
You should make sure that you use appropriate date-time mapping for your field and use range filter over that field. You don't need to split into 2 separate fields. Date maths will allow you to query just based on date.
This will make your life much easier if you want to do aggregations over date time field.
Reference:
Date Maths:
https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math
Date Mapping : https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html
Date Range Queries:
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html