TinyDB – The Test() Query


TinyDB – The test() Query



”;


The test() query will test if the given arguments match with the data in a table. If it matches with the data, it will return the matched data, otherwise it will return blank. First of all, we need to define a test function and its arguments and then it will search the item in a given database.

Syntax

The syntax of TinyDB test() is as follows −


db.search(Query().field.test(function or condition, *arguments))

Here, field represents the part of data that we want to access. Query() is the object created of our JSON table named student.

We can create a custom test function as follows −


object = lambda t: t == ''value''

Here the lamba keyword is important to create the custom test function.

Let”s understand how it works with the help of a couple of examples. We will use the same student database that we have used in all the previous chapters.

Example 1

We will first create a test function and then use it in our student table −


from tinydb import TinyDB, Query
db = TinyDB(''student.json'')
objects = lambda t: t == [250, 280]
db.search(Query().mark.test(objects))

It will fetch the rows where the “mark” field has the values [250, 280] −


[{''roll_number'': 2, ''st_name'': ''Ram'', ''mark'': [250, 280], ''subject'':
[''TinyDB'', ''MySQL''], ''address'': ''delhi''}]

Example 2

In this example, we will use the “subject” field in the test function −


student = Query()
db = TinyDB(''student.json'')
objects = lambda t: t == ''TinyDB''
db.search(student.subject.test(objects))

This query will fetch all the rows where the “subject” field has the value “TinyDB” −


[
   {
      "roll_number":1,
      "st_name":"elen",
      "mark":250,
      "subject":"TinyDB",
      "address":"delhi"
   },
   {
      "roll_number":5,
      "st_name":"karan",
      "mark":275,
      "subject":"TinyDB",
      "address":"benglore"
   }
]

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *