Tinydb 简明教程
TinyDB - The test() Query
test() 查询会测试给定参数是否与表中的数据匹配。如果它与数据匹配,它会返回已匹配的数据,否则它会返回一个空值。首先,我们需要定义一个 test 函数及其参数,然后它会搜索给定数据库中的项目。
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
TinyDB test() 的语法如下 -
The syntax of TinyDB test() is as follows −
db.search(Query().field.test(function or condition, *arguments))
此处, field 表示我们要访问的数据部分。 Query() 是对我们名为 student 的 JSON 表创建的对象。
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'
此处 lamba 关键字对于创建自定义测试函数很重要。
Here the lamba keyword is important to create the custom test function.
让我们借助几个例子来了解它是如何工作的。我们将使用我们在所有前一章中都曾使用过的相同的 student 数据库。
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
我们将首先创建一个测试函数,然后在我们的 student 表中使用它 -
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))
它会提取其中 "mark" 字段具有值 [250, 280] 的行 -
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
在此示例中,我们将在测试函数中使用 "subject" 字段 -
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))
此查询会提取其中 "subject" 字段具有值 "TinyDB" 的所有行 -
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"
}
]