#What's the right way to get the number of documents in a table in the last 5 minutes?

17 messages · Page 1 of 1 (latest)

misty brook
#

Something like this?

 await ctx.db.query("itineraries").filter(
        (it) => it.gt("_creationTime", new Date(Date.now() - 5 * 60 * 1000))
      )
#

@jagged prairie

jagged prairieBOT
#

Let me check the knowledge base for you. One moment! :books:

#

Sorry @misty brook, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist:

Perhaps try again in 15mins?

misty brook
#

Something like this?

const numCreatedRecently = (
await ctx.db.query("itineraries").filter(
(q) => q.gte("_creationTime", Date.now() - 1000 * 60)
)
.take(10)
).length;

if (numCreatedRecently >= 10) {
  throw new Error("Too many requests, please try again later");
}
ashen frigate
#

ctx.db.query("itineraries").withIndex("by_creation_time", q=>q.gte("_creationTime", Date.now() - 5*60*1000)).take(10)

misty brook
#

hmm but i dont have a schema defined. maybe that's why it's giving type errors?

Argument of type 'string' is not assignable to parameter of type 'never'.ts(2345)

ashen frigate
#

Oh huh. That sounds like a bug. You should be able to do "by_creation_time" as any to get around that

misty brook
#

this at least has no linter errors:

ctx.db.query("itineraries").withIndex("by_creation_time" as never, q=>q.gte("_creationTime" as never, Date.now() - 5*60*1000 as never)).take(10)
ashen frigate
#

huh. I'll look into why this is necessary and we should probably fix it, but that seems like a reasonable workaround.

#

You can also do the filter thing (from your original question) if you're not worried about performance, but note you should use q.field("_creationTime") instead of just "_creationTime"

misty brook
#

ah ic that's helpful, thanks!

#

definitely would rather use an index haha

#

so i wasn't entirely sure, is the creation time a special case, and that's why we can use it indexed? or are other fields the same way (when we don't have a schema defined)?

ashen frigate
#

We haven't explored much the dx of using typescript without a schema, so let us know of any more gaps. Or you can use a schema 🙂

#

Yes, by_creation_time and by_id (i.e. db.get) are the two special indexes created by default on all tables