jsonfilterrethinkdbsubqueryreql

How to apply filter on array in ReQL in ReThinkDB using JavaScript


In the following JSON, I want to pick the records that have sales > 12500. How do I do that in ReThinkDB and ReQL?

JSON is:

{
 "address": {  
    "address_line1":  "Address Line 1" ,
    "address_line2":  "Address Line 2" ,
    "city":  "Kochin" ,
    "country":  "India" ,
    "state":  "Kerala"
  } ,
  "id":  "bbe6a9c4-ad9d-4a69-9743-d5aff115b280" ,
  "name":  "Dealer 1" ,
  "products": [
         {
           "product_name":  "Stabilizer" ,
           "sales": 12000
         } ,
         {
           "product_name":  "Induction Cooker" ,
           "sales": 14000
         }
    ]
   }, {
    "address": {
          "address_line1":  "Address Line 1" ,
          "address_line2":  "Address Line 2" ,
          "city":  "Kochin" ,
          "country":  "India" ,
          "state":  "Kerala"
     } ,
     "id":  "f033a4c2-959c-4e2f-a07d-d1a688100ed7" ,
     "name":  "Dealer 2" ,
     "products": [
           {
            "product_name":  "Stabilizer" ,
            "sales": 13000
           } ,
           {
            "product_name":  "Induction Cooker" ,
            "sales": 11000
           }
      ]

}


Solution

  • To get all documents that have at least one sales value over 12,500 for any product, you can use the following filter in ReQL:

    r.table('t')
     .filter(r.row('products').contains(function(product) {
       return product('sales').gt(12500);
     }))
    

    This makes use of the fact that you can pass a function into contains. array.contains(fun) returns true exactly if fun returns true for at least one of the elements in array. You can find more examples at http://rethinkdb.com/api/javascript/contains/