TinyDB get all IDs in list query

7.2k views Asked by At

I'm using TinyDB in my python project. However, in order to make the logic effective, I need to be able to get multiple objects in a query. My preference would be to use a list

listOfIDs = ['123', '456']

I am using the latest Python version and TinyDB implementation.

I have the following implementation:

from tinydb import TinyDB, Query
db = TinyDB('db.json')
myDBQuery= Query()
db.insert({'id': '123', 'name': 'bob'})
db.insert({'id': '456', 'name': 'mary'})
result = db.search(myDBQuery.id.all(['123', '456']))
print(result)

However, I keep getting the following as a result:

[]

I know my implementation is working because when I do the following, I get the expected results:

result = db.search((myDBQuery.id == '123') | myDBQuery.id == '456'))

Anyone know how to query with a list in TinyDB?

Anyone know how to query with a list in TinyDB?

EDIT

For those of you wondering, there isn't a way to do it with the current implementation. My only workaround is to create something like the following

def getAllObjectsMatchingId(listOfIds):

tempList = []

for idMember in tempList:
    result = db.search(myDBQuery.id == idMember)
    tempList.append(result)

return tempList
3

There are 3 answers

6
v.coder On BEST ANSWER

.all returns true only if all the elements of the list match the query

.any might work instead

result = db.search(myDBQuery.id.any(['123', '456']))

EDIT FROM QUESTION OP: Please see my edit above

0
peguerosdc On

If anyone still comes accross with this, an alternative to Reinaldo's implementation:

listOfIds = ['1','2','3']
q = Query()
db.search(q.id.one_of(listOfIds))

Taken from Query's API:

one_of(items: List[Any]) → tinydb.queries.QueryInstance
    Check if the value is contained in a list or generator.

You can also negate the query (which was what I needed) to get the items that are NOT in the list:

listOfIds = ['4','5']
q = Query()
db.search(~q.id.one_of(listOfIds))
0
Reinaldo Gomes On

This seems the best solution to me:

db.search(myDBQuery.id.test(lambda x: x in listOfIDs))

test() Matches any document for which the function returns True