Search code examples
c#rethinkdb

How to get index of an element on given predicate in RethinkDB


Hello i have a table where i want to get all documents after a given document.

The problem is i have not seen a skipwhile functionality ,you giving a predicate. So i have to resort to first finding the index of my given element.How is that achieveable?

Ex: Given the documents {"a":1 },{"b":2},{"a":33},{"c":44},{"d":33} i want to take all the elements after the last a so i would like to get: [ {"c":44},{"d":33}]

Is this achieveable via the RethinkDB driver or i would need to solve this after i take all the table.


Solution

  • So i have to resort to first finding the index of my given element. How is that achieveable?

    You can use the offsetsOf() function. It returns an array of indices that are matching your searched element. You can get the index of the {"a":33} document as follows:

    r.expr([{"a":1 },{"b":2},{"a":33},{"c":44},{"d":33}])
      .offsetsOf({"a":33}).nth(0)
    

    To go further and iterate over the rest of the elements you can use the r.range() function like this:

    r.expr([{"a":1 },{"b":2},{"a":33},{"c":44},{"d":33}])
        .do(function(docs){
          return docs.offsetsOf({"a":33}).nth(0)
            .do(function(index){
              return r.range(index.add(1), docs.count())
                .map(function(i){
                  return docs.nth(i)
                })
            })
        })