Search code examples
python-3.xrethinkdbrethinkdb-python

RethinkDB: matching a string from a list of strings


This is my table in rethinkDB

[{"username": "row1", "some_key": ["str1", "str2"]}, {"username": "row2", "some_key": ["str3", "blah"]}, {"username": "row3", "some_key": ["blah", "blahblah"]}]

The field(column) name can be repeated. I have a list ['row1', 'row2'].

I want to run query and get all the documents(rows) where name is present in the list

So far i have this:

r.db(self.PROJECT_DB).table(self.PROJECT_TABLE_PICWIZ).filter(r.row['username'] == name for name in following).limit(5).run(self.db_connection)

following is the list here.

But this returns all the documents(rows)


Solution

  • Assuming this is Python. I think from what I'm understanding is that you want something like this, considering following is just a list:

    picwiz = r.db(self.PROJECT_DB).table(self.PROJECT_TABLE_PICWIZ)
    picwiz.filter(lambda doc: r.expr(following).contains(doc['username']))\
      .limit(5)\
      .run(self.db_connection)
    

    Here is what is happening:

    This filter takes an anonymous function which takes your list of strings called following and then for every document in the table, checks if the username field is in that list via the contains method and returns True if yes, and False if no, adding or removing it from the final results.

    It is probably also possible to replace the lambda function with the following for maybe something a bit more Pythonic and less ReQL-ish.

    lambda doc: doc['username'] in following