I have ~100 documents coming in per hour. Every document has a viewers property (integer).
By the end of the day I want to aggregate an array of 24 documents, one for every hour of the day, represented by the document with the highest viewers count.
My query so far:
// query, fetch all documents of a specific day
var query = {
bool : {
filter : [
{
range : {
'created' : {
gte : day,
lte : day + (60 * 60 * 24)
}
}
}
]
}
}
// aggregation
var aggs = {
// ?
}
I think this could be achieved using Date Histogram plus Top Hits aggregations. Look at this:
{
"size": 0,
"aggs": {
"articles_over_time": {
"date_histogram": {
"field": "created",
"interval": "minute"
},
"aggs": {
"Viewers": {
"top_hits": {
"size": 1,
"sort": [
{
"viewers": {
"order": "desc"
}
}
]
}
}
}
}
}
}
Date Histogram aggregation will create buckets for each hour in filtered date range and top hits agg will bring back document with highest viewers (we're ordering documents by viewers in descending order and bringing top 1 hit).
Let me know if this works.
Related
I have a collection ticket_masters,which contain createdAt field and it store the date and time .
[
{
"_id": "5e78f2ddc0e09128e81db47a",
"NAME": "Jasin",
"PHONE": "2252545414",
"MAIL": "sdsdm#m.com",
"createdAt": "2020-03-23T17:33:17.470Z",
"updatedAt": "2020-03-23T17:33:17.470Z",
"__v": 0
}
]
Now i want find records according to createAt field from the user collection. Already tried with the following code snippet.
db.getCollection('ticket_masters').find({
"createdAt" : '2020-03-17T18:30:00.237+00:00'
})
Output :
Fetched 0 record(s) in 1ms
But zero records found as per the above code snippet.Kindly help me to resolve issues
Thank you
By specifying the Date type.
The $eq operator matches documents where the value of a field equals the specified value.
// Date and time
db.getCollection('ticket_masters').aggregate([
{
$match: {
"createdAt": {$eq: new Date('2020-03-17T18:30:00.237+00:00')}
}
},
])
OR
// Only Date
db.getCollection('ticket_masters').aggregate([
{
$match: {
"createdAt": {"$gte": new Date("2020-03-17"), $lt : new Date("2020-03-18") }
}
},
])
The dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day
Using momentjs
Example:
// start today
var start = moment().startOf('day');
// end today
var end = moment(today).endOf('day');
{ createdAt: { '$gte': start, '$lte': end }
$gt Matches values that are greater than a specified value.
$lt Matches values that are less than a specified value.
For more information: https://docs.mongodb.com/manual/reference/operator/query-comparison/
Hope this will help you.
db.getCollection('ticket_masters').find({
"createdAt" : ISODate("2020-03-17T18:30:00.237+00:00")
})
or you can try this.
db.getCollection('ticket_masters').aggregate([
{
$match: {
"createdAt":ISODate("2020-03-17T18:30:00.237+00:00")
}
},
])
I have a MongoDB datastore set up with location data stored like this:
{
"_id" : ObjectId("51d3e161ce87bb000792dc8d"),
"datetime_recorded" : ISODate("2013-07-03T05:35:13Z"),
"loc" : {
"coordinates" : [
0.297716,
18.050614
],
"type" : "Point"
},
"vid" : "11111-22222-33333-44444"
}
I'd like to be able to perform a query similar to the date range example but instead on a time range. i.e. Retrieve all points recorded between 12AM and 4PM (can be done with 1200 and 1600 24 hour time as well).
e.g.
With points:
"datetime_recorded" : ISODate("2013-05-01T12:35:13Z"),
"datetime_recorded" : ISODate("2013-06-20T05:35:13Z"),
"datetime_recorded" : ISODate("2013-01-17T07:35:13Z"),
"datetime_recorded" : ISODate("2013-04-03T15:35:13Z"),
a query
db.points.find({'datetime_recorded': {
$gte: Date(1200 hours),
$lt: Date(1600 hours)}
});
would yield only the first and last point.
Is this possible? Or would I have to do it for every day?
Well, the best way to solve this is to store the minutes separately as well. But you can get around this with the aggregation framework, although that is not going to be very fast:
db.so.aggregate( [
{ $project: {
loc: 1,
vid: 1,
datetime_recorded: 1,
minutes: { $add: [
{ $multiply: [ { $hour: '$datetime_recorded' }, 60 ] },
{ $minute: '$datetime_recorded' }
] }
} },
{ $match: { 'minutes' : { $gte : 12 * 60, $lt : 16 * 60 } } }
] );
In the first step $project, we calculate the minutes from hour * 60 + min which we then match against in the second step: $match.
Adding an answer since I disagree with the other answers in that even though there are great things you can do with the aggregation framework, this really is not an optimal way to perform this type of query.
If your identified application usage pattern is that you rely on querying for "hours" or other times of the day without wanting to look at the "date" part, then you are far better off storing that as a numeric value in the document. Something like "milliseconds from start of day" would be granular enough for as many purposes as a BSON Date, but of course gives better performance without the need to compute for every document.
Set Up
This does require some set-up in that you need to add the new fields to your existing documents and make sure you add these on all new documents within your code. A simple conversion process might be:
MongoDB 4.2 and upwards
This can actually be done in a single request due to aggregation operations being allowed in "update" statements now.
db.collection.updateMany(
{},
[{ "$set": {
"timeOfDay": {
"$mod": [
{ "$toLong": "$datetime_recorded" },
1000 * 60 * 60 * 24
]
}
}}]
)
Older MongoDB
var batch = [];
db.collection.find({ "timeOfDay": { "$exists": false } }).forEach(doc => {
batch.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": {
"$set": {
"timeOfDay": doc.datetime_recorded.valueOf() % (60 * 60 * 24 * 1000)
}
}
}
});
// write once only per reasonable batch size
if ( batch.length >= 1000 ) {
db.collection.bulkWrite(batch);
batch = [];
}
})
if ( batch.length > 0 ) {
db.collection.bulkWrite(batch);
batch = [];
}
If you can afford to write to a new collection, then looping and rewriting would not be required:
db.collection.aggregate([
{ "$addFields": {
"timeOfDay": {
"$mod": [
{ "$subtract": [ "$datetime_recorded", Date(0) ] },
1000 * 60 * 60 * 24
]
}
}},
{ "$out": "newcollection" }
])
Or with MongoDB 4.0 and upwards:
db.collection.aggregate([
{ "$addFields": {
"timeOfDay": {
"$mod": [
{ "$toLong": "$datetime_recorded" },
1000 * 60 * 60 * 24
]
}
}},
{ "$out": "newcollection" }
])
All using the same basic conversion of:
1000 milliseconds in a second
60 seconds in a minute
60 minutes in an hour
24 hours a day
The modulo from the numeric milliseconds since epoch which is actually the value internally stored as a BSON date is the simple thing to extract as the current milliseconds in the day.
Query
Querying is then really simple, and as per the question example:
db.collection.find({
"timeOfDay": {
"$gte": 12 * 60 * 60 * 1000, "$lt": 16 * 60 * 60 * 1000
}
})
Of course using the same time scale conversion from hours into milliseconds to match the stored format. But just like before you can make this whatever scale you actually need.
Most importantly, as real document properties which don't rely on computation at run-time, you can place an index on this:
db.collection.createIndex({ "timeOfDay": 1 })
So not only is this negating run-time overhead for calculating, but also with an index you can avoid collection scans as outlined on the linked page on indexing for MongoDB.
For optimal performance you never want to calculate such things as in any real world scale it simply takes an order of magnitude longer to process all documents in the collection just to work out which ones you want than to simply reference an index and only fetch those documents.
The aggregation framework may just be able to help you rewrite the documents here, but it really should not be used as a production system method of returning such data. Store the times separately.
I have a program that runs every 5 minutes and checks the last time a users data was updated. If it's been greater than 4 hours an update routine is called but as the service grows, I've seen some spikes in the number of calls at given times. I want to start spreading out the update times. Since I know each time the program updated each users data last, I was wondering if there was an elegant way to find the largest gap between times and set the new users update time to that?
Here's an example. Given the following data:
{
"_id": "1",
"updatedAt": "2018-01-17T01:12:33.807Z"
},{
"_id": "2",
"updatedAt": "2018-01-17T03:17:33.807Z"
},{
"_id": "3",
"updatedAt": "2018-01-17T02:22:33.807Z"
},{
"_id": "4",
"updatedAt": "2018-01-17T02:37:33.807Z"
}
The largest time between the given updates is 1 hour and 10 minutes between id: 1 and id: 3. I want a function that can find that largest gap of time and returns the a suggested update time for the next item added to the database of '2018-01-17T01:47:33.807Z'. Which was calculated by taking the 1 hour and 10 minutes and dividing it by 2 and then adding it to id: 1's date.
I would also like to spread out all the existing users update time but I suppose that would be a different function.
You can't use aggregation framework for a difference style comparison. However you can use map reduce to get the largest time diff between documents.
Something like
db.col.mapReduce(
function () {
if (typeof this.updatedAt != "undefined") {
var date = new Date(this.updatedAt);
emit(null, date);
}
},
function(key, dates) {
result = {"prev":dates[0].getTime(), "last":dates[0].getTime(), "diff":0}
for (var ix = 1; ix < dates.length; ix++) {
value = dates[ix].getTime();
curdiff = value - result.prev;
olddiff = result.diff;
if(olddiff < curdiff)
result = {"prev":value, "diff":curdiff, "last":result.prev};
}
return result;
},
{
"sort":{"updatedAt":1},
"out": { "inline": 1 },
"finalize":function(key, result) {
return new Date(result.last + result.diff/2);
}
}
)
Aggregation query:
db.col.aggregate([
{"$match":{"updatedAt":{"$exists":true}}},
{"$sort":{"updatedAt":1}},
{"$group":{
"_id":null,
"dates":{"$push":"$updatedAt"}
}},
{"$project":{
"_id":0,
"next":{
"$let":{
"vars":{
"result":{
"$reduce":{
"input":{"$slice":["$dates",1,{"$subtract":[{"$size":"$dates"},1]}]},
"initialValue":{"prev":{"$arrayElemAt":["$dates",0]},"last":{"$arrayElemAt":["$dates",0]},"diff":0},
"in":{
"$cond":[
{"$lt":["$$value.diff",{"$subtract":["$$this","$$value.prev"]}]},
{"prev":"$$this","last":"$$value.prev","diff":{"$subtract":["$$this","$$value.prev"]}},
"$$value"
]
}
}
}
},
"in":{
"$add":["$$result.last",{"$divide":["$$result.diff",2]}]
}
}
}
}}
])
I'm building a leaderboard with elasticsearch. I'd like to query all documents who have points greater than a given amount using the following query:
{
"constant_score" : {
"filter" : {
"range" : {
"totalPoints" : {
"gt": 242
}
}
}
}
This works perfectly -- elasticsearch appropriately returns all documents with points greater than 242. However, all I really need is the count of elements matching this query. Since I'm sending the result over the network, it would be helpful if the query simply returned the count, as opposed to all of the documents matching the filter.
How do I get elasticsearch to only report the count of documents matching the filter?
EDIT: I've learned that what I'm looking for is setting search_type to count. However, I'm not sure how to do this with elastic.js. Any noders willing to pitch in their advice?
You can use the query type count for exactly that purpose:
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-request-search-type.html#count
This is an example that should help you:
GET /mymusic/itunes/_search?search_type=count
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"range": {
"year": {
"gt": 2000
}
}
}
}
}
}
I want to simulate a parent child relation in elastic search and perform some analytics work over it. My use case is something like this
I have a shop owner like this
"_source": {
"shopId": 5,
"distributorId": 4,
"stateId": 1,
"partnerId": 2,
}
and now have child records (for each day) like this:
"_source": {
"shopId": 5,
"date" : 2013-11-13,
"transactions": 150,
"amount": 1980,
}
The parent is a record per store, while the child is the transactions each store does for
day. Now I want to do some complex query like
Find out total transaction for each day for the last 30 days where distributor is 5
POST /newdb/shopsDaily/_search
{
"query": {
"match_all": {}
},
"filter": {
"has_parent": {
"type": "shop",
"query": {
"match": {
"distributorId": "5"
}
}
}
},
"facets": {
"date": {
"histogram": {
"key_field": "date",
"value_field": "transactions",
"interval": 100
}
}
}
}
But the result I get do not take the filtering into account which I applied.
So I changed the query to this:
POST /newdb/shopDaily/_search
{
"query": {"filtered": {
"query": {"match_all": {}},
"filter": { "has_parent": {
"type": "shop",
"query": {"match": {
"distributorId": "13"
}}
}}
}},
"facets": {
"date": {
"histogram": {
"key_field": "date",
"value_field": "transactions",
"interval": 100
}
}
}
}
And then the final histogram facet took filtering into count.
So, when I browsed though I found out this is due to using filtered(which can only be used inside query clause and not outside like filter) rather than filter,
but it also mentioned that to have fast search you should use filter. Will searching as I did in second step (when I used filtered instead of filter) effect the performance of elastic search? If so, how can I make my facets honor filters and not effect the performance?
Thanks for you time
filters in Filtered query (filters in query clause) are cached, hence faster. These type of filters affect both search result and facet counts.
Filters outside the query clause are not considered during facet calculations. They are considered only for search results. Facet is calculated only on the query clause. If you want filtered facets then you need to set filters to each of the facet clauses.