2

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/

Rahul
  • 11,129
  • 17
  • 63
  • 76

1 Answers1

3
  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)
Jorge Silva
  • 4,574
  • 1
  • 23
  • 42
  • Note that if you want to have documents that have *only* 'b1' or 'b2' in the `b` field, you can use set_difference in combination with is_empty like this: `...table('business').filter( |row| row['b'].set_difference(['b1', 'b2'].is_empty()))` Any document where b contains items other than b1 and b2 will be filtered out. – Daniel Mewes Apr 14 '15 at 13:15
  • Thanks Daniel . @Jorge Silva, I would really appreciate , if you could add the python equivalent of the same as well. I was trying to execute rql like query in python, I guess the syntax and function calls are a bit different. – Rahul Apr 15 '15 at 19:56
  • Done! Can you explain what you mean by the syntax and function calls being a bit different? Just curious – Jorge Silva Apr 15 '15 at 20:10