Rahul
Rahul

Reputation: 11669

How to extract / Filter on array objects in JSON using RethinkDB

I have a simple JSON structure, for example

{'a' : 'value' , 'b': ['b1','b2','b3'] , c: 'value'} ,
{ 'a' : 'value' , 'b': ['b5','b6','b7'] , c: 'value'},
and so on . . .

I was wondering on how do I filter json data which only have b1 or b2 . It wasnt very clear in this documentation [1] . I tried running the following query but I am pretty sure, thats not the correct way of doing it.

r.db('mine').table('business')
  .filter([{'categories':'Clothing'}])

[1] http://rethinkdb.com/docs/nested-fields/ruby/

Upvotes: 2

Views: 947

Answers (1)

Jorge Silva
Jorge Silva

Reputation: 4614

  1. If you want all rows with a value in the b property that has a value of b1, you can just use the contains method.

You use the contains method (with the `filter method) in order to do that:

r.db('mine')
 .tables('business')
 .filter(function (row) { return row('b').contains('b1'); })
 .run(conn)

In Ruby, that looks something like this:

r.db('test')
 .table('hello')
 .filter{ |row| row['b'].contains('b1') }
 .run(conn)

In Python, that looks something like this:

r.db('test')
 .table('hello')
 .filter(lambda row: row['b'].contains('b1'))
 .run(conn)
  1. If you want all rows with a value in the b property that has a value of b1 AND a value of b2, you can just use the contains method with the and method.

JavaScript

r.db('mine')
 .tables('business')
 .filter(function (row) { 
   return row('b').contains('b1').and(row('b').contains('b2')); 
 })
 .run(conn);

Python:

r.db('test')
  .table('hello')
  .filter(lambda row: 
     row['b'].contains('b1') & row['b'].contains('b2') 
   )
  .run(conn)
  1. If you want all rows with a an array that only contains the values 'b1' or 'b2', then you can use Daniel's way and use the .setDifference method with the isEmpty method.

JavaScript

r.db('mine')
 .tables('business')
 .filter(function (row) { 
   return row('b').contains('b1').and(row('b').contains('b2')); 
 })
 .run(conn);

Python:

r.db('test')
  .table('hello')
  .filter(lambda row: 
     row['b'].contains('b1') & row['b'].contains('b2') 
   )
  .run(conn)

Upvotes: 3

Related Questions