Search code examples
arraysrethinkdbrethinkdb-python

How to filter on array size in rethinkdb?


I have a table with a bunch of documents that are updated regularly (in part).

What I'm essentially trying to do is create another table (called changes below) that stores the latest N changes to each of those documents.

I'm thus doing table.changes() to get all changes on the table, calculating the diff information I want (called diffentry below) and prepending that info to an array in the other table:

changes.get(doc_id).update({
    'diffs': R.row['changes'].prepend(diffentry)
}).run()

This tricky bit is how to limit the size of the diffs array?

There's an array method delete_at() that can delete one or many items from an array, which I could just "brute force"-call, like:

delete_at(diff_limit, diff_limit + 10000)

and ignore any error (the insane upper limit is just paranoia). But that feels kind of dirty...

I thought a nicer, and better way would be to filter on arrays that is larger than the limit and remove the exceeding bits. Pseudo:

changes.get(doc_id).filter(R.row['diffs'].length > diff_limit).update({
    'diffs': R.row['diffs'].delete_at(diff_limit, R.row['diffs'].length - 1)
}).run()

But, alas, there is no length, that I've found... Any ideas on how to do this kind of thing in a nice way?


Solution

  • In JS you can use a function with .count() like this:

    update(function(doc){
           return {
              diffs: doc("diffs").deleteAt(diff_limit, doc("diffs").count())
           }
       }
    ).run()
    

    I think in python should be something similar.