1

What would be an efficient way to get the last N key-value pairs from an object? Sorted by key name and N being arbitrary integer. Ideally the returned type should also be an object.

user33946
  • 404
  • 6
  • 10

2 Answers2

3

If you want the last n, I would write obj.coerceTo('array').slice(-n).coerceTo('object'). (Objects in RethinkDB implicitly sort their fields by the key.) If you want the first n, I'd write .slice(0, n) instead of .slice(-n).

mlucy
  • 5,249
  • 1
  • 17
  • 21
0

Something like this should work

r.object(r.args(

  a_single_object_return_from_a_reql_or_an_r_dot_expr
  .do(function(doc) {

    return 
      doc.keys().slice(0, THE_NUMBER_OF_KEY)
      .concatMap(function(k) {
          return [k, doc(k)]
      })

  })

))

Assume I have table s1 with this document whose id is: 65e1546a-f23f-4fe6-9cd7-4ba580770123:

{
"created_at":  "2013-10-13 00:58:11" ,
"id":  "65e1546a-f23f-4fe6-9cd7-4ba580770123" ,
"id_tweet":  "389193311908413440" ,
"id_user": 12375562 ,
"name":  "elgabo1" ,
"photo": https://pbs.twimg.com/profile_images/1827710728/45d1be6d2e0f1c710814e098d6f56c12_normal.png, »
"screen_name":  "elgabo1" ,
"status_tweet": 1 ,
"text":  "@profeco Deurope Gran Sur tapa los sellos de suspensión con propaganda"
}

Apply above query I can write sth like this to get first 5 keys, return an object:

r.object(r.args(

  r.table('s1').get('65e1546a-f23f-4fe6-9cd7-4ba580770123')
  .do(function(doc) {

    return 
      doc.keys().slice(0, 5)
      .concatMap(function(k) {
          return [k, doc(k)]
      })

  })

))

Result:

{
"created_at":  "2013-10-13 00:58:11" ,
"id":  "65e1546a-f23f-4fe6-9cd7-4ba580770123" ,
"id_tweet":  "389193311908413440" ,
"id_user": 12375562 ,
"name":  "elgabo1"
}
kureikain
  • 2,304
  • 2
  • 14
  • 9