Tinydb 简明教程

TinyDB - The test() Query

test() 查询会测试给定参数是否与表中的数据匹配。如果它与数据匹配,它会返回已匹配的数据,否则它会返回一个空值。首先,我们需要定义一个 test 函数及其参数,然后它会搜索给定数据库中的项目。

Syntax

TinyDB test() 的语法如下 -

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.

我们可以创建自定义测试函数,如下 -

object = lambda t: t == 'value'

此处 lamba 关键字对于创建自定义测试函数很重要。

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 表中使用它 -

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

它会提取其中 "mark" 字段具有值 [250, 280] 的行 -

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

Example 2

在此示例中,我们将在测试函数中使用 "subject" 字段 -

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

此查询会提取其中 "subject" 字段具有值 "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"
   }
]