Tinydb 简明教程
TinyDB - Introduction
What is TinyDB?
用纯 Python 编程语言编写的 TinyDB 是一个轻量级文档数据库,没有外部依赖关系。它提供了易于使用的简单 API。我们无需任何配置即可将 TinyDB 数据库用于小型项目应用。
TinyDB, written in pure Python programming language, is a small and lightweight document-orineted database with no external dependencies. It provides simple APIs that makes it easy to use. We can use TinyDB database for small project applications without any configuration.
TinyDB 模块作为 Python 程序的第三方模块提供,可用于存储、检索和修改 JSON 格式的数据。
TinyDB module, available as a third-party module for Python programs, can be used to store, retereive, and modify the data in JSON format.
Features of TinyDB
TinyDB 是一个干净且操作起来轻松的数据库,可操作多种格式的文档。它具有以下特性。
TinyDB is a clean and hustle-free database to operate several formats of documents. It has the following features.
-
Really tiny − TinyDB database is truly tiny in nature with only 1800 lines of code and 1600 lines tests.
-
Easy to use − TinyDB is easy to use because of its simple and clean APIs.
-
Document oriented − In TinyDB, we can store any document. The document will be represented as dict.
-
Independent − The TinyDB database is independent of any external server and external dependencies from PyPI.
-
Compatible with Python 3.6 or latest − TinyDB is tested and compatible with Python 3.6 and latest. It also works fine with PyPY3.
-
Extensible − TinDB is easily extensible either by writing new storages or by modifying the behaviour of storages.
Advantages of TinyDB
TinyDB 为学生、用户和开发人员提供了许多好处。
TinyDB provide various benefits for students, users, and developers.
-
TinyDB is open-sourced database aand it does not require any external configirations.
-
It is quite easy-to-use, and the user can effortlessly handle documents.
-
It automatically stores documents in the database.
-
TinyDB is ideal in case of personal projects where we need to install some data.
-
It is suitable for small applications that would be blown away by large databases like SQL or an external DB server.
-
It uses a simple command line and query to operate data.
-
There is 100% test coverage i.e., no explanation needed.
Limitatations of TinyDB
如果您需要以下内容,TinyDB 不是您项目的正确选择 −
TinyDB will not be the right choice for your project if you need to −
-
create indexes for tables,
-
manage relationships between tables,
-
use an HTTP server, or
-
access from multiple processors.
Comparison with Other Databases
下表重点介绍了 TinyDB 与 MySQL 和 Oracle 数据库的不同之处 −
The following table highlights how TinyDB is different from MySQL and Oracle databases −
Comparison Basis |
MySQL |
Oracle |
TinyDB |
Configurations |
Several Configurations |
Several Configurations |
Less Configurations, lightweight database |
Complicated |
Yes |
Yes |
No, easy-to-use and hustle-free |
Affordable |
No |
No |
Affordable than other databases |
Manageable |
Big database, hence difficult to manage |
Big database, hence difficult to manage |
Small and manageable |
TinyDB - Environmental Setup
Prerequisite for TinyDB setup
要安装 TinyDB,系统中必须安装 Python 3.6 或更高版本。你可以访问链接 www.python.org ,为你的操作系统(例如 Windows 和 Linux/Unix)选择最新版本。我们提供了一个全面的 Python 教程,你可以在 www.tutorialspoint.com 参阅。
To install TinyDB, you must have Python 3.6 or newer installed in your system. You can go to the link www.python.org and select the latest version for your OS, i.e., Windows and Linux/Unix. We have a comprehensive tutorial on Python, which you can refer at www.tutorialspoint.com
Installing TinyDB
你可以使用三种不同的方式安装 TinyDB:使用包管理器、从其源代码或从 GitHub 安装。
You can install TinyDB in three different ways: using the Pack Manager, from its Source, or from GitHub.
Using the Package Manager
最新版本的 TinyDB 可通过包管理器 pip 和 conda 获得。让我们检查一下如何使用它们安装 TinyDB−
The latest release versions of TinyDB are available over both the package managers, pip and conda. Let us check how you can use them to install TinyDB −
要使用 pip 安装 TinyDB,可以使用以下命令−
To install TinyDB using pip, you can use the following command −
pip install tinydb
要通过 conda-forge 安装 TinyDB,可以使用以下命令−
To install TinyDB via conda-forge, you can use the following command −
conda install -c conda-forge tinydb
From Source
你还可以从源码包安装 TinyDB。转到链接 https://pypi.org/project/tinydb/#files 下载文件并从源代码构建。
You can also install TinyDB from source distribution. Go to link https://pypi.org/project/tinydb/#files to download the files and building it from source.
Setting up TinyDB
安装完成后,请使用以下步骤设置 TinyDB 数据库。
Once installed, use the following steps to set up the TinyDB database.
Step 1: Import TinyDB and its Query
首先,我们需要导入 TinyDB 及其 Query。使用以下命令:
First, we need to import TinyDB and its Query. Use the following command −
from tinydb import TinyDB, Query
Step 2: Create a file
TinyDB 数据库可以以多种格式存储数据,如 XML、JSON 等。我们将使用以下文件创建 JSON 文件:
TinyDB database can store data in many formats like XML, JSON, and others. We will be creating a JSON file by using the following file −
db = TinyDB('Leekha.json')
以上命令将创建 TinyDB 类的一个实例,并向其传递文件 Leekha.Json。这是存储我们数据的文件。现在,TinyDB 数据库已经设置好,您可以对其进行操作。我们现在可以向数据库中插入数据并在其中操作值。
The above command will create an instance of TinyDB class and pass the file Leekha.Json to it. This is the file where our data will be stored. Now, the TinyDB database set up is ready, and you can work on it. We can now insert data and operate the value in the database.
TinyDB - Insert Data
我们已经创建了 TinyDB 的实例,并向其传递了一个 JSON 文件,我们的数据将存储在其中。现在是时候向我们的数据库中插入条目了。数据应采用 Python 字典的形式。
We have created the instance of the TinyDB and passed a JSON file to it where our data will be stored. It is now time to insert the items in our database. The data should be in the form of a Python dictionary.
Syntax
要插入条目,您可以使用下面语法所示的方法 insert() :
To insert an item, you can use insert() method whose syntax is given below −
db.insert({'type1': 'value1', 'type2': 'value2', 'typeN': 'valueN'})
我们还可以首先创建一个字典,然后使用 insert() 方法将数据插入到数据库中。
We can also create a dictionary first and then use the insert() method to insert the data into our database.
data_item = {'type1': 'value1', 'type2': 'value2', 'typeN': 'valueN' } db.insert(data_item)
在运行以上命令后,insert() 方法将返回新创建的对象的 ID。此外,我们的 JSON 文件将如下所示:
After running the above command, the insert() method will return the ID of the newly created object. And, our JSON file will look like the one shown below −
{"_default": {"1": {"type1": "value1", "type2": "value2", "typeN": "valueN"}}}
查看以上表中的条目:' default ' 是表的名称,' 1 ' 是新创建的对象的 ID,' values ' 是我们刚刚插入的数据。
Look at the above table entries: 'default' is the name of the table, '1' is the ID of the newly created object, and the values are the data we have just inserted.
Example: Inserting a Single Item
让我们借助示例来理解上述概念。假设我们有一个存储学生信息的数据库,其中包括学号、姓名、成绩、科目和地址。以下是在数据库中存储的信息:
Let’s understand the above concept with the help of examples. Suppose we have a database having student information showing roll numbers, names, marks, subjects, and addresses. Following is the information stored in the database −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"oracle",
"address":"benglore"
}
]
在以上数据库中,如果您想要插入一条新学生记录(即一个条目),请使用以下命令:
In the above database, if you want to insert a new student record (i.e., a single item), use the following command −
db.insert({
'roll_number': 6,
'st_name':'jim',
'mark':300,
'subject':'sql',
'address':'pune'
})
它将返回新创建的对象的 ID:
It will return the ID of the newly created object −
6
让我们输入 one more record :
Let’s enter one more record−
db.insert({
'roll_number': 7,
'st_name':'karan',
'mark':290,
'subject':'NoSQL',
'address':'chennai'
})
它将返回新创建的对象的 ID:
It will return the ID of the newly created object −
7
如果您想要检查数据库中存储的条目,请按如下方式使用 all() 方法:
If you want to check the stored items in the database, use the all() method as follows −
db.all()
它将生成以下 output −
It will produce the following output −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"oracle",
"address":"benglore"
},
{
"roll_number":6,
"st_name":"jim",
"mark":300,
"subject":"sql",
"address":"pune"
},
{
"roll_number":7,
"st_name":"karan",
"mark":290,
"subject":"NoSQL",
"address":"chennai"
}
]
您可以看到,它在 JSON 文件中添加了两个新数据条目。
You can observe that it added two new data items in the JSON file.
Example: Inserting Multiple items at a Time
您还可以在 TinyDB 数据库中一次插入多个条目。为此,您需要使用 insert_multiple() 方法。我们来看一个示例:
You can also insert multiple items at a time in a TinyDB database. For this, you need to use the insert_multiple() method. Let' see an example −
items = [
{'roll_number': 8, 'st_name': 'petter', 'address': 'mumbai'},
{'roll_number': 9, 'st_name': 'sadhana', 'subject': 'SQL'}
]
db.insert_multiple(items)
现在,使用 all() 方法按如下方式检查数据库中存储的条目:
Now, check the stored items in database, using the all() method as follows −
db.all()
它将生成以下 output −
It will produce the following output −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"oracle",
"address":"benglore"
},
{
"roll_number":6,
"st_name":"jim",
"mark":300,
"subject":"sql",
"address":"pune"
},
{
"roll_number":7,
"st_name":"karan",
"mark":290,
"subject":"NoSQL",
"address":"chennai"
},
{
"roll_number":8,
"st_name":"petter",
"address":"mumbai"
},
{
"roll_number":9,
"st_name":"sadhana",
"subject":"SQL"
}
]
您可以观察到,它在 JSON 文件中添加了两个新的数据项。您还可以在添加最后两项时跳过数据项中的一些键值(如我们所做的那样)。我们已经跳过“mark”和“address”。
You can observe that it added two new data items in the JSON file. You can also skip some key values from the dataitems (as we have done) while adding the last two items. We have skipped 'mark' and 'address'.
TinyDB - Retrieve Data
有许多方法可以帮助您从 TinyDB 数据库中检索数据。但是要使用这些方法,您首先需要按如下所示创建 Query 类的实例 −
There are numerous ways with the help of which you can retrieve data from a TinyDB database. But to use those ways, you first need to create an instance of the Query class as follows −
from tinydb import Query
Student = Query()
此处, Student 是数据库的名称。
Here, Student is the name of the database.
让我们探索从 TinyDB 数据库检索信息的各种方式。
Let’s check the various ways to retrieve the information from a TinyDB database.
Data Retrieval Using the Search() Method
search() 方法(顾名思义)返回与我们提供的查询匹配的项目列表,否则它将返回一个空列表。
The search() method, as its name implies, returns the list of items that mathches the query we provided, otherwise it will return an empty list.
对于此示例和其他示例,我们将使用以下 student 数据库数据 -
For this and other examples, we will be using the following student database data −
[
{
"roll_number": 1,
"st_name": "elen",
"mark": 250,
"subject": "TinyDB",
"address": "delhi"
},
{
"roll_number": 2,
"st_name": "Ram",
"mark": [
250,
280
],
"subject": [
"TinyDB",
"MySQL"
],
"address": "delhi"
},
{
"roll_number": 3,
"st_name": "kevin",
"mark": [
180,
200
],
"subject": [
"oracle",
"sql"
],
"address": "keral"
},
{
"roll_number": 4,
"st_name": "lakan",
"mark": 200,
"subject": "MySQL",
"address": "mumbai"
},
{
"roll_number": 5,
"st_name": "karan",
"mark": 275,
"subject": "TinyDB",
"address": "benglore"
}
]
让我们举一个 example 来理解 search() 方法 -
Let’s take an example to understand the search() method −
from tinydb import TinyDB, Query
db = TinyDB("leekha.json")
student = Query()
db.search(student.subject == 'TinyDB' )
上述查询将从 student 数据库中检索以下 output -
The above query will retrieve the the following output from the student database −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
Data Retrieval Using the get() Method
与 search() 方法相反,get() 方法仅返回一个匹配的文档。否则,它将返回 None。例如,让我们采用以下代码 -
As opposed to the search() method, the get() method returns only one matching document. It will return None, otherwise. For example, let’s take the following code −
from tinydb import TinyDB, Query
student = Query()
db.get(student.subject == 'TinyDB' )
上述查询将从 student 数据库中检索以下数据。
The above query will retrieve the following data from the student database.
[{'roll_number': 1, 'st_name': 'elen', 'mark': 250, 'subject': 'TinyDB', 'address': 'delhi'}]
Data Retrieval using the all() Method
all() 方法返回数据库中的所有文档。例如,
The all() method returns all the documents in the database. For example,
db.all()
它将从 student 数据库中检索全部数据。
It will retrieve the entire data from the student database.
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
TinyDB - Update Data
TinyDB 可以以多种格式存储数据,我们可以使用多种方法轻松地重新访问存储的数据。但有时,我们需要更新数据,我们可以使用 update() 方法来更新数据。
TinyDB can store data in many formats and we can easily reterive the stored data using various methods. But sometimes, we need to update the data, for which we can use the update() method.
要更新数据库,我们首先需要创建 Query 类的实例。您可以为此目的使用以下命令-
For updating the database, we first need to create an instance of the Query class. You can use the following command for this purpose −
from tinydb import Query
Student = Query()
这里 Student 是我们数据库的名称。
Here, Student is the name of our database.
The update() Method
下面是 update() 方法的语法版本-
Here is the syntax for the update() method −
db.update({ updated field: updated information… }, stable field: information)
让我们举个例子来理解 update() 方法如何工作。对于此示例,我们将使用以下学生数据库-
Let’s take an example to understand how the update() method works. For this example, we will be using the following student database −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
根据给定的数据,roll_number 为“1”的学生姓名为“elen”。以下查询将把学生姓名更新为“Adam”-
As per the given data, the name of the student with the roll_number "1" is "elen". The following query will update the student name to "Adam" −
from tinydb import TinyDB, Query
student = Query()
db.update({'st_name' : 'Adam'}, student.roll_number == 1 )
它将返回更新对象的 id-
It will return the id of the updated object −
[1]
现在,您可以使用 all() 方法来查看更新的数据库-
Now, you can use the all() method to see the updated database −
db.all()
它将显示更新后的数据-
It will display the updated data −
[
{
"roll_number":1,
"st_name":"Adam",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
有时,我们需要更新数据库中所有文档的一个或多个字段。为此,我们可以直接使用 update() 方法,而不必编写查询参数。以下查询将把所有学生的地址更改为“College_Hostel”-
Sometimes, we need to update one or more fields of all the documents in a database. For this, we can use the update() mehod directly and don’t need to write the query argument. The following query will change the address of all the students to 'College_Hostel'−
db.update({'address': 'College_Hostel'})
它将返回更新对象的 id-
It will return the ids of the updated object −
[1,2,3,4,5]
再一次,您可以使用 all() 方法来查看更新的数据库。
Again, you can use the all() method to see the updated database.
db.all()
它将显示更新后的数据-
It will show the updated data −
[
{
"roll_number":1,
"st_name":"Adam",
"mark":250,
"subject":"TinyDB",
"address":"College_Hostel"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":" College_Hostel "
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":" College_Hostel "
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":" College_Hostel "
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":" College_Hostel "
}
]
观察到所有行的地址字段都有相同的数据,即“College_Hostel”。
Observe that the address fields of all the rows have the same data, i.e., 'College_Hostel'.
TinyDB - Delete Data
如果您需要从 TinyDB 数据库中永久删除特定数据的话,您可以使用 remove() 方法来完成。与返回和更新数据类似,您首先需要创建一个 Query 类的实例来删除数据。您可以为此目的使用以下命令 -
In case you need to delete a particular set of data permanently from a TinyDB database, you can do so by using the remove() method. Like for reteriving and updating the data, you first need to create an instance of the Query class for deleting the data. You can use the following command for this purpose −
from tinydb import Query
Student = Query()
这里 Student 是我们数据库的名称。
Here, Student is the name of our database.
The remove() Method
以下是 remove() 方法的语法 -
Here is the syntax for the remove() method −
db.remove( Query() field regex )
remove() 方法接受可选条件以及可选文档 ID 列表。
The remove() method accepts both an optional condition as well as an optional list of documents IDs.
The student Database
对于本章的示例,我们将使用以下 student 数据库。
We will use the following student database, for the examples in this chapter.
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
Example: Deleting a Single Row of Data
我们举一个例子来了解 remove() 方法。
Let’s take an example to understand the remove() method.
from tinydb import TinyDB, Query
student = Query()
db.remove(student.roll_number == 5)
上面的查询将删除学生学号为 5 的数据。它将返回被删除对象的 ID −
The above query will delete the data where the student’s roll number is 5. It will return the ID of the removed object −
[5]
现在,我们可以使用 all() 方法查看更新后的数据库。
Now, we can use the all() method to see the updated database.
db.all()
它将显示更新后数据库中的数据 −
It will display the data from the updated database −
[
{
"roll_number":1,
"st_name":"Adam",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
}
]
Example: Deleting Multiple Rows of Data
如果您一次想要删除多行,您可以按如下所示使用 remove() 方法 −
If you want to remove more than one row at a time, you can use the remove() method as follows −
from tinydb import TinyDB, Query
student = Query()
db.remove(student.roll_number > 2)
它将返回被删除对象的 ID:
It will return the IDs of the removed object:
[3,4]
使用 all() 方法查看更新后的数据库。
Use the all() method to see the updated database.
db.all()
它将显示更新后数据库中的数据 −
It will display the data from the updated database −
[
{
"roll_number":1,
"st_name":"Adam",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
}
]
Example: Deleting the Entire Data
如果您想要从数据库中删除所有数据,您可以按如下所示使用 truncate() 方法 −
If you want to remove all the data from a database, you can use the truncate() method as follows −
db.truncate()
接下来,使用 all() 方法查看更新后的数据库。
Next, use the all() method to see the updated database.
db.all()
它将显示一个空数据库作为 output −
It will show an empty database as the output −
[]
TinyDB - Querying
TinyDB 有一系列丰富的查询。我们有构造查询的方法:第一种方法类似于 ORM 工具的语法,第二种方法是使用“Where”子句的传统方法。
TinyDB has a rich set of queries. We have ways to construct queries: the first way resembles the syntax of ORM tools and the second is the traditional way of using the 'Where' clause.
在本章节中,我们来理解在 TinyDB 数据库中构造查询的这两种方法。
In this chapter, let’s understand these two ways of constructing a query in a TinyDB database.
The First Method: Importing a Query
第一种方法类似于 ORM 工具的语法,其中我们首先需要在命令提示符中导入查询。导入后,我们可以使用查询对象操作 TinyDB 数据库。 syntax 如下所示 −
The first method resembles the syntax of ORM tools in which first we need to import the query in the command prompt. After importing, we can use the query object to operate the TinyDB database. The syntax is given below −
from tinydb import Query
student = Query()
这里,“student”是我们的数据库名称。对于这些示例,我们将使用以下 student 数据库。
Here, 'student' is the name of our database. For the examples, we will be using the following student database.
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
Example
以下是查询从 student 数据库中获取数据,其中学生的 roll_no 小于 3 −
Following is the query to retereive the data from the student database where the roll_no of the students are less than 3 −
>>> db.search(Query().roll_number < 3)
Or,
Or,
>>> student = Query()
>>> db.search(student.roll_number < 3)
上面的搜索查询将产生以下结果 −
The above search query will produce the following result −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
}
]
有时文件名不是有效的 Python 标识符。在这种情况下,我们将无法访问该字段。对于这种情况,我们需要按如下所示切换到 dict access notation −
Sometimes the file name is not a valid Python identifier. In that case, we would not be able to access that field. For such cases, we need to switch to dict access notation as follows −
student = Query();
# Invalid Python syntax
db.search(student.security-code == 'ABCD')
# Use the following dict access notation
db.search(student['security-code'] == 'ABCD')
TinyDB - Searching
TinyDB 提供了 search() 方法来帮助你从文档中检索任何数据。配合使用 query() 对象,search() 方法可用于在 JSON 文件中查找数据。有好多种方法可以在 TinyDB 数据库上使用 search() 方法。
TinyDB provides the search() method to help you search any data from a document. Along with the query() object, the search() method can be used to find the data in a JSON file. We have various ways in which we can use the search() method on a TinyDB database.
Method 1: TinyDB search() with Existence of a Field
我们可以根据字段的存在情况从数据库中检索数据。我们通过一个例子来理解这一点。对于此示例以及其他示例,我们将使用以下 student 数据库。
We can search the data from a database based on the existence of a field. Let’s understand it with an example. For this and other examples, we will be using the following student database.
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
Example
基于字段的存在情况进行的搜索查询如下所示 −
The search query based on the existence of a field is as follows −
from tinydb import Query
student = Query()
db.search(student.address.exists())
上述查询会从 student 文件中检索以下数据 −
The above query will retrieve the following data from the student file −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
Method 2: TinyDB search() with Regular Expression
我们可以使用正则表达式 (Regex) 从数据库中检索特定的数据。我们通过几个示例来理解它是如何工作的。
We can search for a particular data from a database using regular expression (Regex). Let’s understand how it works with a couple of examples.
Example 1
与正则表达式配对的完整项目搜索 −
Full item search matching the Regular Expression −
from tinydb import Query
student = Query()
db.search(student.st_name.matches('[aZ]*'))
此查询会生成以下 output −
This query will produce the following output −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
Example-2
区分大小写的正则表达式搜索 −
Case-sensitive search with Regular Expression −
from tinydb import Query
import re
student = Query()
db.search(student.st_name.matches('lakan', flags=re.IGNORECASE))
它会生成以下 output −
It wil produce the following output −
[{
'roll_number': 4,
'st_name': 'lakan',
'mark': 200,
'subject': 'MySQL',
'address': 'mumbai'
}]
Example-3
与正则表达式配对的项目部分 −
Any part of the item matching with Regular Expression −
from tinydb import Query
student = Query()
db.search(student.st_name.search('r+'))
此查询会生成以下 output −
This query will produce the following output −
[{
'roll_number': 5,
'st_name': 'karan',
'mark': 275,
'subject': 'TinyDB',
'address': 'benglore'
}]
Method 3: TinyDB search() using a Substring
在从 TinyDB 数据库中检索特定数据时,我们还可以使用子字符串。我们通过几个示例来理解它是如何工作的 −
We can also use a substring while searching for a particular data from a TinyDB database. Let’s understand how it works with a couple of examples −
Example-1
看一下此查询;它将获取 "address" 字段为 "delhi" 的所有行。
Take a look at this query; it will fetch the all the rows where the "address" field is "delhi".
from tinydb import Query
student = Query()
db.search(student['address'] == 'delhi')
它将生成以下 output −
It will produce the following output −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
}
]
Example-2
在此查询中,我们对 search() 方法使用了稍微不同的语法。
In this query, we have used a slightly different syntax for the search() method.
from tinydb import Query
student = Query()
db.search(student.address.search('mumbai'))
它将获取 "address" 字段为 "mumbai" 的所有行。
It will fetch all the rows where the "address" field is "mumbai".
[{
'roll_number': 4,
'st_name': 'lakan',
'mark': 200,
'subject': 'MySQL',
'address': 'mumbai'
}]
TinyDB - The where Clause
TinyDB 提供了 "where" 子句,你可以在检索特定数据时使用它。通过过滤掉不需要数据,"where" 子句能够提供帮助。借助 "where" 子句,你可以快速访问指定数据。
TinyDB provides the "where" clause that you can use while searching for a particular data. The "where" clause helps by filtering the unwanted data out. With the help of the "where" clause, you can access specific data quickly.
在使用 'where' 子句之前,我们需要先导入它。'where' 子句的 syntax 如下所示 −
Before using the 'where' clause, we need to first import it. The syntax of "where" clause is given below −
from tinydb import where
db.search(where('field') == 'value')
我们通过几个示例来理解如何使用 'where' 子句。
Let’s understand the use of 'where' clause with the help of a couple of examples.
The Student Database
对于示例,我们将使用以下 student 数据库。
For the examples, we will use the following student database.
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
Example 1
我们给 subject 字段使用 " where " 子句 -
Let’s use the "where" clause for the subject field −
db.search(where('subject') == 'MySQL')
此查询将获取到所有 "subject" 字段为 "MySQL" 的行。
This query will fetch all the rows where the "subject" field is "MySQL".
[{
'roll_number': 4,
'st_name': 'lakan',
'mark': 200,
'subject': 'MySQL',
'address': 'mumbai'
}]
Example 2
让我们看另一个与 " not equal to " 条件一起使用 " where " 子句的用法 -
Let’s see another use of the "where" clause with the "not equal to" condition −
db.search(where('mark') != 275)
此查询将获取到所有 "mark" 字段不等于 "275" 的行。
This query will fetch all the rows where the "mark" field is not equal to "275" −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
}
]
TinyDB - The exists() Query
TinyDB 提供了一个高级查询,叫做 exists() ,该查询检查 JSON 文件中数据的可用性。 exists() 查询实际测试了来自 JSON 文件的子字段数据的可用性。exists() 查询基于布尔条件工作。如果子字段存在(即布尔 TRUE),它将从 JSON 文件中相应地获取数据,否则它将返回一个空白值。
TinyDB provides an advanced query called exists() that checks the existence of data in a JSON file. The exists() query actually tests the availability of a subfield data from a JSON file. The exists() query works on the basis of a Boolean condition. If the subfield exists (i.e., BOOLEAN TRUE), it will fetch the data accordingly from the JSON file, otherwise it will return a blank value.
Syntax
TinyDB exists() 的语法如下 -
The syntax of TinyDB exists() is as follows −
db.search(Query().field.exists())
此处, field 表示我们要访问的数据部分。 Query() 是由 JSON 表 student 创建的对象。
Here, field represents the part of data that we want to access. Query() is the object created from the JSON table student.
我们将使用我们在所有前一章中都曾使用过的相同的 student 数据库。
We will use the same student database that we have used in all the previous chapters.
Example 1
让我们给名为 ' subject ' 的字段使用 TinyDB exists() 查询 -
Let’s use the TinyDB exists() query for the field named 'subject' −
db.search(student.subject.exists())
此查询将获取到所有行,因为所有行都有 "subject" 字段 -
This query will fetch all the rows because all the rows have the "subject" field −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":" TinyDB ",
"address":"benglore"
}
]
Example 2
现在让我们给 ' address ' 字段使用 exists() 查询 -
Now let’s use the exists() query for the 'address' field −
db.search(student.address.exists())
它将获取到以下行 -
It will fetch the following rows −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":" TinyDB ",
"address":"benglore"
}
]
Example 3
现在,让我们给一个不可用的字段尝试 exists() 查询 -
Now, let’s try the exists() query for a field that is not available −
db.search(student.city.exists())
由于给定表中的任何行都没有名为 "city" 的字段,因此上面的 exists() 查询将返回一个空白值 -
Since none of the rows in the given table has a field called "city", the above exists() query will return a blank value −
[]
TinyDB - The matches() Query
matches() 查询将某个 JSON 文件中的数据与给定条件(正则表达式的形式)匹配,并相应地返回结果。如果条件与文件中的数据不匹配,它将返回一个空白值。
The matches() query matches the data from a JSON file with a given condition (in the form of a regular expression) and returns the results accordingly. It will return a blank value if the condition does not match with the data in the file.
Syntax
TinyDB matches() 的语法如下 -
The syntax of TinyDB matches() is as follows −
db.search(Query().field.matches(regular expression))
此处, 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.
让我们借助几个例子来了解它是如何工作的。我们将使用我们在所有前一章中都曾使用过的相同的 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
让我们看看如何使用 matches() 来进行完整项目搜索。
Let’s see how we can use matches() for full item search.
from tinydb import Query
student = Query()
db.search(student.st_name.matches('[aZ]*'))
此查询会提取所有行 -
This query will fetch all the rows −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
Example 2
让我们看看如何使用 matches() 来进行区分大小写搜索。
Let’s see how we can use matches() for case-sensitive search.
from tinydb import Query
import re
student = Query()
db.search(student.st_name.matches('ram', flags=re.IGNORECASE))
此查询会提取其中学生姓名与字符串 "ram" 匹配的行。注意,我们在匹配字符串时使用了忽略大小写的标记。
This query will fetch the rows where the student name matches the string "ram". Observe that we have used a flag to ignore the case while matching the strings.
[{
'roll_number': 2,
'st_name': 'Ram',
'mark': [250, 280],
'subject': ['TinyDB', 'MySQL'],
'address': 'delhi'
}]
Example 3
让我们看看如何使用 matches() 来匹配特定项目。
Let’s see how we can use matches() for a particular item.
student = Query()
db.search(student.address.matches('keral'))
此查询会提取其中地址与字符串 "keral" 匹配的行。
This query will fetch the rows where the address matches the string "keral".
[{'roll_number': 3, 'st_name': 'kevin', 'mark': [180, 200], 'subject':
['oracle', 'sql'], 'address': 'keral'}]
Example 4
让我们看看 matches() 在未找到特定项目时会返回什么 -
Let’s see what matches() would return when it does not find a particular item −
student = Query()
db.search(student.address.matches('Ratlam'))
没有其中 "address" 字段与字符串 "Ratlam" 匹配的行,因此它会返回一个空值 -
There are no rows where the "address" field matches the string "Ratlam", hence it will return a blank value −
[]
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"
}
]
TinyDB - The any() Query
对于搜索包含列表的字段,TinyDB 提供了一个名为 any() 的方法。此方法至少匹配数据库中的一个给定值。它根据所提供的查询找到一个完整列表或一个最小值。
For searching the fields containing a list, TinyDB provides a method called any(). This method matches at least one given value from the database. It finds either an entire list or a minimum one value as per the query provided.
Syntax
TinyDB any () 的语法如下 -
The syntax of TinyDB any() is as follows −
db.search(Query().field.any(query|list)
此处, 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.
-
If we will provide query as the argument of any() method, it will match all the documents where at least one document in the list field match the given query.
-
On the other hand, if we will provide list as the argument of any() method, it will match all the documents where at least one document in the list field is present in the given list.
让我们借助几个例子来了解它是如何工作的。我们将使用我们在所有前一章中都曾使用过的相同的 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 表中查找 subject 为 TinyDB 或 MySQL 或 SQL 或任意两个或三个组合的字段 −
Let’s see how we can find the fields from our student table where subject is either TinyDB, or MySQL, or SQL or combination of any two or three −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search(Query().subject.any(['TinyDB', 'MySQL', 'oracle']))
上面的查询将获取 "subject" 字段包含以下值的 "TinyDB"、"MySQL" 或 "oracle" 的所有行 −
The above query will fetch all the rows where the "subject" field contains any of the following values: "TinyDB", "MySQL", or "oracle" −
[
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
}
]
Example 2
让我们看看当 any() 方法在给定列表中没有匹配任何内容时如何做出反应 −
Let’s see how the any() method reacts when it doesn’t match anything from the given list −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search(Query().subject.any(['Oracle']))
此查询将返回一个空值,因为没有 "subject" 为 "Oracle" 的行。
This query will return a blank value because there are no rows with its "subject" as "Oracle".
[]
Example 3
请注意,它是区分大小写的。"subject" 字段没有 " Oracle ",但有 " oracle "。尝试以下查询 −
Observe that it is case-sensitive. The "subject" field does not have "Oracle", but it does have "oracle". Try the following query −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search(Query().subject.any(['oracle']))
它将获取以下行 −
It will fetch the following row −
[{
'roll_number': 3,
'st_name': 'kevin',
'mark': [180, 200],
'subject': ['oracle', 'sql'],
'address': 'keral'
}]
由于它是区分大小写的,因此在前面的示例中返回了一个空值,因为没有 "subject" 为 "Oracle" 的行。
As it is case-sensitive, it returned a blank value in the previous example because there are no rows with its "subject" as "Oracle".
TinyDB - The all() Query
TinyDB 提供了一个名为 all() 的方法,它可以根据提供的查询查找整个值列表。让我们举一个例子,了解它是如何工作的。
TinyDB provides a method called all() that finds an entire list of values as per the query provided. Let’s take an example and find out how it works.
Syntax
TinyDB all() 的语法如下 −
The syntax of TinyDB all() is as follows −
db.search(Query().field.all(query|list)
此处, 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.
-
If we will provide a query as the argument of all() method, it will match all the documents where all documents in the list field match the given query.
-
On the other hand, if we will provide a list as the argument of all() method, it will match all the documents where all documents in the list field are present in the given list.
让我们借助几个例子来了解它是如何工作的。我们将使用我们在所有前一章中都曾使用过的相同的 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 表中查找 subject 同时为 TinyDB 和 MySQL 的字段 −
Let’s see how we can find the fields from our student table where the subjects are both TinyDB, and MySQL −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search(Query().subject.all(['TinyDB', 'MySQL']))
此查询将获取以下行 −
This query will fetch the following row −
[{
'roll_number': 2,
'st_name': 'Ram',
'mark': [250, 280],
'subject': ['TinyDB', 'MySQL'],
'address': 'delhi'
}]
Example 2
让我们看看如何使用 all() 获取我们数据库中的全部数据 −
Let’s see how we can use all() to get the entire data from our database −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.all()
它将获取链接数据库中的所有行 −
It will fetch all the rows from the linked database −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
TinyDB - The one_of() Query
为了匹配子字段数据,TinyDB 提供了一个名为 one_of() 的方法。此方法搜索单个类别并获取至少一个相似值。如果字段包含在提供的列表中,它将匹配。
For matching the subfield data, TinyDB provides a method called one_of(). This method searches a single category and gets at least one similar value. It will match if the field is contained in the provided list.
Syntax
TinyDB one_of() 的语法如下 −
The syntax of TinyDB one_of() is as follows −
db.search(Query().field.one_of(list)
此处, field 代表我们要访问的数据部分。 Query() 是我们命名的 JSON 表 student 创建的对象。它将获取一个类别的单个或多个值。
Here, field represents the part of data that we want to access. Query() is the object created of our JSON table named student. It will fetch either single or multiple values of one category.
让我们通过几个示例来了解它的工作原理。我们将使用我们在所有先前章节中使用的 student 数据库。
Let’s understand how it works with the help of a couple examples. We will use the same student database that we have used in all the previous chapters.
Example 1
让我们看看如何从我们的 student 表中查找 address 字段为“德里”或“浦那”的行 −
Let’s see how we can find the fields from our student table where address is either "delhi" or "pune" −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search(Query().address.one_of(['delhi', 'pune']))
它将获取所有“地址”字段包含“德里”或“浦那”的行。
It will fetch all the rows where the "address" field contains either "delhi" or "pune".
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
}
]
Example 2
让我们看另一个带有 ' subject ' 字段的示例 −
Let’s see another example with 'subject' field −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search(Query().subject.one_of(['TinyDB', 'MySQL']))
它将获取所有“主题”字段包含“TinyDB”或“MySQL”的行。
It will fetch all the rows where the "subject" field contains either "TinyDB" or "MySQL".
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":4,
"st_name":"lakhan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
TinyDB - Logical Negate
逻辑否定作为一种反逻辑门起作用。它将匹配与给定查询不匹配的文档。简而言之,它将显示给定命令的相反含义。
Logical Negate works as an inverse logical gate. It will match the documents that don’t match the given query. In simple words, it will display the opposite meaning of the given command.
Syntax
TinyDB Logical Negate 的语法如下 −
The syntax of TinyDB Logical Negate is as follows −
db.search(~(Query().field)
这里, 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. It will fetch the data that represents the opposite meaning of the given command.
让我们举几个例子,看看它是如何工作的。我们将使用我们在所有先前章节中使用的 student 数据库。
Let’s take a couple of examples and see how it works. We will use the same student database that we have used in all the previous chapters.
Example 1
让我们看看如何从我们的 student 表中查找学生姓名不为 ' elen ' 的字段 −
Let’s see how we can find the fields from our student table where the student name is not 'elen' −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search(~(Query().st_name == 'elen'))
上面的查询将获取所有学生姓名不为“elen”的行。
The above query will fetch all the rows where the student name is not "elen".
[
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
Example 2
让我们看看如何使用逻辑否定避免特定地址 −
Let’s see how we can avoid a particular address using logical negate −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search(~(student.address.one_of(['keral', 'delhi'])))
此查询将获取“地址”字段不包含“keral”或“德里”的所有行。
This query will fetch all the rows where the "address" field does not have either "keral" or "delhi".
[
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
TinyDB - Logical AND
“逻辑与”运算符组合多个条件,如果满足所有条件,则求值为真。TinyDB 逻辑与运算符作用于数据库的两个查询。如果两个查询都为真,TinyDB 将获取所需数据。另一方面,如果其中任何一个查询为假,它将返回一个空白。
The "Logical AND" operator combines multiple conditions and evaluates to True if all the conditions are met. TinyDB Logical AND operates on two queries of a database. If both the queries are True, TinyDB will fetch the required data. On the other hand, if any one of the queries is False, it will return a blank.
Syntax
TinyDB Logical AND 的语法如下 −
The syntax of TinyDB Logical AND is as follows −
db.search((Query().(query1) & (Query().(query2)
这里, 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. It will fetch the data if both the conditions met, otherwise it will return a blank.
让我们举几个例子,看看 Logial AND 是如何工作的。我们将使用我们在所有先前章节中使用的 student 数据库。
Let’s take a couple examples and see how Logial AND works. We will use the same student database that we have used in all the previous chapters.
Example 1
让我们看看当我们在 “st_name=lakhan” 和 “subject=MYSQL” 字段上应用逻辑与时,我们的 TinyDB 学生数据库返回了什么 −
Let’s see what our TinyDB Student database returns when we apply Logical AND on "st_name=lakhan" and "subject=MYSQL" field −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search ((Query().st_name == 'lakhan') & (Query().subject == 'MySQL'))
此查询将仅获取学生姓名为“lakhan”且“subject”为“MySQL”的行。
This query will fetch only those rows where the student name is "lakhan" and the "subject" is "MySQL".
[{
'roll_number': 4,
'st_name': 'lakhan',
'mark': 200,
'subject': 'MySQL',
'address': 'mumbai'
}]
Example 2
此示例中,让我们对“subject”和“roll_number”字段应用逻辑 AND −
In this example, let’s apply Logical AND on the "subject" and "roll_number" fields −
from tinydb import TinyDB, Query
student = Query()
db = TinyDB('student.json')
db.search((student.subject.search('M')) & (student.roll_number < 5))
此查询将获取其中“roll_number”小于“4”且“subject”以字母“M”开头的所有行。
This query will fetch all the rows where the roll_number is less than "4" and "subject" starts with the letter "M".
[{
'roll_number': 4,
'st_name': 'lakhan',
'mark': 200,
'subject': 'MySQL',
'address': 'mumbai'
}]
TinyDB - Logical OR
“逻辑 OR”运算符结合多个条件,且仅在满足任一条件时才计算为 True。TinyDB 逻辑 OR 对数据库的两个查询进行操作。如果其中任何一个查询为真,则 TinyDB 将获取所需的数据。另一方面,如果两个查询都为假,则它将返回一个空值。
The "Logical OR" operator combines multiple conditions and evaluates to True only if either of the condition is met. TinyDB Logical OR operates on two queries of a database. If any one of the queries is True, TinyDB will fetch the required data. On the other hand, if both the queries are False, it will return a blank.
Syntax
TinyDB Logical OR 的语法如下所示 −
The syntax of TinyDB Logical OR is as follows −
db.search((Query().(query1) | (Query().(query2)
其中 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. It will fetch the data if any one of the conditions is met, otherwise it will return a blank.
让我们举几个例子,看看它是如何工作的。我们将使用我们在所有先前章节中使用的 student 数据库。
Let’s take a couple of examples and see how it works. We will use the same student database that we have used in all the previous chapters.
Example 1
让我们看看当我们在“st_name”和“subject”字段上应用逻辑 OR 并检查以下条件时,我们的 TinyDB 学生数据库返回什么:st_name=lakhan 和 subject=TinyDB −
Let’s see what our TinyDB Student database returns when we apply Logical OR on the "st_name" and "subject" fields and check the following conditions: "st_name=lakhan" and "subject=TinyDB" −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search ((Query().st_name == 'lakan') | (Query().subject == 'TinyDB'))
此查询将获取以下行 −
This query will fetch the following rows −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":4,
"st_name":"lakhan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
}
]
Example 2
此示例中,让我们对“subject”和“roll_number”字段应用逻辑 AND −
In this example, let’s apply Logical OR on the "subject" and "roll_number" fields −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.search((student.subject.search('M')) | (student.roll_number < 5))
此查询将获取其中“subject”字段以字母“M”开头或“roll_number”小于“5”的所有行。
This query will fetch all the rows where the "subject" field starts with the letter "M" or the "roll_number" is less than "5".
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakhan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
}
]
TinyDB - Handling Data Query
TinyDB - Storing Multiple Data
我们已经讨论了如何使用 ' insert ' 查询将数据存储在数据库中。类似地,可以使用 ' insert_multiple ' 查询同时存储多个数据项。以下是在 TinyDB 中 ' insert_multiple ' 查询的语法:
We have already discussed how you can use the 'insert' query to store data in a database. On a similar note, you can use the 'insert_multiple' query to store multiple data items simultaneously. Here is the syntax of 'insert_multiple' query in TinyDB:
db.insert_multiple ([
{ key1 : value1, key2 : value2, ..., keyN : valueN},
{ key1 : value1, key2 : value2, ..., keyN : valueN }
])
我们来看几个示例,以演示“insert_multiple”查询的工作原理。我们将使用在之前的章节中使用的相同的 student 数据库。
Let’s take a couple of examples to demonstrate how the "insert_multiple" query works. We will use the same student database that we have used in all the previous chapters.
Example 1
让我们看看如何使用 insert_multiple 查询在我们 ' student ' 表中插入两条学生记录 −
Let’s see how we can insert two records of students in our 'student' table using the insert_multiple query −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.insert_multiple([
{
"roll_number":6,
"st_name":"Siya",
"mark":240,
"subject":"NoSQL",
"address":"pune"
},
{
"roll_number":7,
"st_name":"Adam",
"mark":210,
"subject":"oracle",
"address":"Keral"
}
])
它将显示新保存记录的文档 ID −
It will display the document IDs of the newly saved records −
[6, 7]
让我们检查一下新记录是否已保存到数据库中?使用 all() 方法,如下所示 −
Let’s check whether the new records are saved in the database or not? Use the all() method, as shown below −
db.all()
它将显示存储在给定表中的所有记录 −
It will show all the records stored in the given table −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
},
{
"roll_number":6,
"st_name":"Siya",
"mark":240,
"subject":"NoSQL",
"address":"pune"
},
{
"roll_number":7,
"st_name":"Adam",
"mark":210,
"subject":"oracle",
"address":"Keral"
}
]
你可以看到 students 的两条新记录已保存到数据库中。
You can see the two new records of students have been saved in the database.
Example 2
让我们看看如何使用 insert_multiple 和 for 循环一次性在表中插入多个值。使用以下代码 −
Let’s see how we can use insert_multiple with a for loop to insert multiple values simultaneously in a table. Use the following code −
db.insert_multiple({'roll_number': 10, 'numbers': r} for r in range(3))
它将返回新保存记录的文档 ID −
It will return the document IDs of the newly saved records −
[8, 9, 10]
再次使用 all() 方法验证新记录是否已保存到数据库中?
Again, use the all() method to verify whether the new records have been saved in the database or not?
db.all()
它将获取存储在给定 student 表中的所有记录 -
It will fetch all the records stored in the given student table −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"TinyDB",
"address":"benglore"
},
{
"roll_number":6,
"st_name":"Siya",
"mark":240,
"subject":"NoSQL",
"address":"pune"
},
{
"roll_number":7,
"st_name":"Adam",
"mark":210,
"subject":"oracle",
"address":"Keral"
},
{
"roll_number":10,
"numbers":0
},
{
"roll_number":10,
"numbers":1
},
{
"roll_number":10,
"numbers":2
}
]
请注意最后三行。我们已将 insert_multiple 方法与 for 循环配合使用,以插入三个新条目。
Notice the last three rows. We have used the insert_multiple method with a for loop to insert three new entries.
TinyDB - Modifying the Data
我们已经使用 update 查询进行过讨论,借助该查询,我们可以修改值并处理数据库中的数据。但是 update 查询(如 db.update(fields, query) )允许我们通过添加或覆盖它的值来更新文档。
We have already discussed the update query with the help of which we can modify the values as well as handle the data in our database. But the update query such as db.update(fields, query) allows us to update a document by adding or overwriting its values.
但是有时,我们想删除一个字段或需要增加它的值。在这种情况下,我们可以传递一个函数而不是字段。我们可以在更新查询中使用以下操作 -
But sometimes, we would like to remove one field or need to increment its value. In such cases, we can pass a function instead of fields. We can use the following operations with the update query −
The Increment Query
顾名思义,增量查询用于增量数据库中键的值。 syntax 增量查询如下所示 -
The increment query, as its name implies, is used to increment the value of a key in the database. The syntax of increment query is as follows −
from tinydb.operations import increment
db.update(increment('key'))
The Add Query
加法查询用于将值添加到键的值。它也适用于字符串。 syntax 加法查询如下所示 -
The add query is used to add value to the value of a key. It works for the strings as well. The syntax of add query is as follows −
from tinydb.operations import add
db.update(add(key, value))
The Set Query
此查询用于将键设置为数据的值。 syntax 设置查询如下所示 -
This query is used to set the key to the value of the data. The syntax of set query is as follows −
from tinydb.operations import set
db.update(set(key, value))
The Decrement Query
减量查询用于减量键的值。 syntax 减量查询如下所示 -
The decrement query is used to decrement the value of a key. The syntax of decrement query is as follows −
from tinydb.operations import decrement
db.update(decrement(key))
The Subtract Query
减法查询用于从键的值中减去值。 syntax 减法查询如下所示 -
The subtarct query is used to subtract value from the value of a key. The syntax of subtract query is as follows −
from tinydb.operations import subtract
db.update(subtract(key, value))
The Delete Query
删除查询用于从文档中删除键。 syntax 删除查询如下所示 -
The delete query is used to delete a key from a document. The syntax of delete query is as follows −
from tinydb.operations import delete
db.update(delete(key))
让我们举几个示例来演示如何将这些操作与 update 查询一起使用。我们将使用我们在所有以前的章节中使用的相同 student 数据库。
Let’s take a couple of examples to demonstrate how you can use these operations along with the update query. We will use the same student database that we have used in all the previous chapters.
Example 1
让我们看看如何在我们的 student 表中 increment 学生的成绩 -
Let’s see how we can increment the marks of a student in our student table −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
from tinydb.operations import increment
db.update(increment('mark'), Query().mark == 275)
它将生成以下 output −
It will produce the following output −
[5]
以上输出显示它已经更新了文档 ID 为 5 的记录。
The above output shows that it has updated the record whose document ID is 5.
Example 2
让我们看看如何在我们的 student 表中 add 学生的成绩 5 分 -
Let’s see how we can add 5 marks to the marks of a student in our student table −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
from tinydb.operations import add
db.update(add('mark', 5), Query().mark == 200)
它将生成以下 output −
It will produce the following output −
[4]
以上输出显示它已经更新了文档 ID 为 4 的记录。
The above output shows that it has updated the record whose document ID is 4.
Example 3
让我们看看如何在我们的 student 表中将分数 set 为 259 的分数设置为 250 -
Let’s see how we can set the marks to 259 where the marks of a student are 250 in our student table −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
from tinydb.operations import add
db.update(add('mark', 259), Query().mark == 250)
它将生成以下 output −
It will produce the following output −
[1]
以上输出显示它已经更新了文档 ID 为 1 的记录。
The above output shows that it has updated the record whose document ID is 1.
Example 4
让我们看看如何在我们的 student 表中 decrement 学生分数 -
Let’s see how we can decrement the marks of a student in our student table −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
from tinydb.operations import decrement
db.update(decrement('mark'), Query().mark == 205)
它将生成以下 output −
It will produce the following output −
[4]
以上输出显示它已经更新了文档 ID 为 4 的记录。
The above output shows that it has updated the record whose document ID is 4.
Example 5
让我们看看如何在我们的 student 表中 subtract 学生的成绩 5 分 -
Let’s see how we can subtract 5 marks to the marks of a student in our student table −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
from tinydb.operations import add
db.update(add('mark', 5), Query().mark == 204)
它将生成以下 output −
It will produce the following output −
[4]
以上输出显示它已经更新了文档 ID 为 4 的记录。
The above output shows that it has updated the record whose document ID is 4.
Example 6
让我们看看如何向我们学生表中的学生成绩中 subtract 增加 5 分−
Let’s see how we can subtract 5 marks to the marks of a student in our student table −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
from tinydb.operations import delete
db.update(delete('mark'), Query().mark == 209)
它将生成以下 output −
It will produce the following output −
[4]
以上输出显示,它更新了文档 ID 为 4 的记录。它将从数据库中删除值为 209 的分数字段。
The above output shows that it has updated the record whose document ID is 4. It will delete the mark field from the database where the value is 209.
Example 7
让我们看看如何通过单个查询更新表中的多个值 −
Let’s see how we can update multiple values in a table with a single query −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
from tinydb import where
db.update_multiple([
({'st_name':'Eliana'}, where ('roll_number')==1),
({'mark':20}, where ('roll_number') ==2)
])
它将生成以下 output −
It will produce the following output −
[1,2]
以上输出显示,它更新了两个文档 ID 为 1 和 2 的记录。
The above output shows that it has updated two records whose document IDs are 1 and 2.
TinyDB - Upserting Data
我们讨论了 update 和 insert 查询,但有时,我们需要更新和插入的混合。在这种情况下,TinyDB 提供了一个独特的 upsert 查询。此查询有助于我们根据条件一次插入和更新数据。它有两种工作方式 −
We discussed the update and insert queries, but sometimes, we a need a mix of both update and insert. In such cases, TinyDB provides a unique upsert query. This query helps us to insert and update data at a time as per the condition. It works in two ways −
-
If data is available, then it chooses the update operation.
-
If data is not available, then it chooses the insert operation.
Syntax
upsert 查询的语法如下 −
The syntax of upsert query is as follows −
db.upsert({ 'key' : 'value', 'logged - in' : True}, regular expression)
让我们举几个示例来说明如何在 TinyDB 中使用此 upsert 查询。我们将使用与我们在前面所有章节中使用的相同的 student 数据库。
Let’s take a couple of examples to demonstrate how you can use this upsert query in TinyDB. We will use the same student database that we have used in all the previous chapters.
Example 1
让我们看看如何使用 upsert 查询将学号为 2 的学生的地址更改为“surat”。在这种情况下,我们有一个匹配的用户,因此它将使用地址更新为已登录并设置为 True −
Let’s see how we can use the upsert query to change the address of a student to "surat", whose roll numbe is 2. In this case, we we have a matching user, hence it will update with the address to have logged-in set to True −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.upsert({'address':'Surat'}, Query().roll_number==2)
它将生成以下 output ,这意味着记录号“2”已更新。
It will produce the following output, which means record number "2" got updated.
[2]
使用以下代码验证记录号“2”是否已更新 −
Use the following code to verify whether record number "2" got updated or not −
db.get(doc_id=2)
它将显示更新后的数据-
It will show the updated data −
{
'roll_number': 2,
'st_name': 'Ram',
'mark': [250, 280],
'subject': ['TinyDB', 'MySQL'],
'address': 'Surat'
}
Example 2
让我们看看如何将 upsert 查询用于我们表中不可用的数据 −
Let’s see how we can use the upsert query for unavailable data in our table −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.upsert({'E-mail':'ram@gmail.com','logged-in': True},
Query().roll_number==2)
它将显示以下输出,这意味着 ID 为“2”的文档已更新。
It will show the following output, which means the document with the ID "2" got updated.
[2]
使用以下代码验证更新的值 −
Use the following code to verify the updated values −
db.get(doc_id=2)
它将生成如下输出:
It will produce the following output −
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"Surat",
"logged-in":true,
"E-mail":"ram@gmail.com"
}
请注意,我们使用 upsert 查询创建了一个新键( E-mail )(该键不存在),并为其提供了值“ * ram@gmail.com* ”。
Notice that we used the upsert query to create a new key (E-mail) which was non-existent and supplied it with the value "ram@gmail.com".
TinyDB - Retrieving Data
创建数据库后,我们需要经常从该数据库检索数据。以下是我们可以从数据库检索数据的方法 −
After creating a database, we need to frequently retrieve the data from that database. Following are the ways by which we can reterive the data from a database −
The len() Query
借助此查询,我们可以获取数据库中的文档数。它的 syntax 如下 −
With the help of this query, we can get the number of documents in a database. Its syntax is as follows −
len(db)
The get Query
get 查询用于检索与查询匹配的特定文档。它的 syntax 如下 −
The get query is used to reterive specific documents matching a query. Its syntax is as follows −
db.get(query)
The contains Query
contains 查询用于检查数据库是否包含匹配的值。其 syntax 如下 −
The contains query is used to check whether the database contains a matching value or not. Its syntax is as follows −
db.contains(query)
The count Query
count 查询用于检索数据库中匹配文档的数量。其 syntax 如下 −
The count query is used to retrieve the number of matching documents from a database. Its syntax is as follows −
db.count(query)
我们举几个例子来理解如何在 TinyDB 中使用这些查询。我们将使用与前几章中相同的 student 数据库。
Let’s take a few examples to understand how these queries work in TinyDB. We will use the same student database that we have used in all the previous chapters.
Example 1
我们来看看如何使用 len() 查询来获取数据库中的文档数 −
Let’s see how we can use the len() query to get the number of documents in our database −
from tinydb import TinyDB
db = TinyDB('student.json')
print ("Number of documents in student db: ", len(db))
它将显示指定数据库中存在的文档数 −
It will show the number of documents present in the specified database −
Number of documents in student db: 5
Example 2
我们看看如何使用 get() 查询从数据库中获取特定文档 −
Let’s see how we can use the get() query to get a specific document from our database −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.get(Query().address == 'delhi')
此查询将获取 "address" 字段值等于 "delhi" 的行。
This query will fetch the row where the "address" field has the value "delhi".
{
'roll_number': 1,
'st_name': 'elen',
'mark': 250,
'subject': 'TinyDB',
'address': 'delhi'
}
Example 3
我们看看如何使用 contains() 查询来验证我们的数据库是否包含特定值 −
Let’s see how we can use the contains() query to verify if our database contains a specific value −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
db.contains(Query().address == 'delhi')
contains() 查询基于给定数据库中是否存在指定值,返回一个布尔值。在本例中,它将返回 "True",因为我们的数据库具有 "address" 键,其值为 "delhi"。
The contains() query returns a Boolean value, based on the existence of the specified value in the given database. In this case, it will return "True" because our database does have a "address" key with the value "delhi".
True
Example 4
我们来看看如何使用 count() 查询来获取给定条件为 True 的文档数 −
Let’s see how we can use the count() query to get the number of documents for which a given condition is True −
from tinydb import TinyDB, Query
db = TinyDB('student.json')
print (db.count(Query().subject == 'NoSQL'))
它将返回以下 output −
It will return the following output −
3
这意味着数据库中有 3 个文档的 "subject" 键的值为 "NoSQL"。
It means there are 3 documents in the database where the "subject" key has the value "NoSQL".
TinyDB - Document ID
TinyDB 使用文档 ID(由 doc_id 表示)来访问和修改数据库中文档的值。下面我们将看到如何将此 document_id 用于各种操作。
TinyDB uses document ID, represented by doc_id, to access as well as modify the value of documents in a database. Here we will see how we can use this document_id for various operations.
Display Data using Document ID
我们可以在 get() 方法中使用 doc_id 来显示数据库中的数据。其 syntax 如下 −
We can use doc_id in get() method to display the data from a database. Its syntax is as follows −
db.get(doc_id = value)
Check for a Document in a Database
我们可以在 contains() 方法中使用 doc_id 来检查数据库中是否存在文档。其 syntax 如下 −
We can use doc_id in contains() method to check if a document is present in a database or not. Its syntax is given below −
db.contains(doc_id = value)
Update All Documents
我们可以在 update() 方法中使用 doc_id 来使用给定的文档 ID 更新数据库中的所有文档。以下是其 syntax −
We can use doc_id in update() method to update all the documents in a database with the given document IDs. Here is its syntax −
db.update({key : value}, doc_ids = […])
Remove a Document
我们可以在 remove() 方法中使用 doc_id 来使用给定的文档 ID 删除特定文档或数据库中的所有文档。其 syntax 如下 −
We can use doc_id in remove() method to remove a specific document or all the documents in a database with the given document IDs. Its syntax is given below −
db.remove(doc_ids = […])
我们举几个例子来说明如何在 TinyDB 中使用这些方法的 doc_id 。我们将使用与前几章中相同的 student 数据库。
Let’s take a few examples to demonstrate how you can use doc_id in TinyDB with these methods. We will use the same student database that we have used in all the previous chapters.
Example 1
我们来看看如何使用 doc_id 从数据库的特定文档中获取数据 −
Let’s see how we can use doc_id to get the data of a specific document from a database −
from tinydb import TinyDB
db = TinyDB('student.json')
db.get(doc_id = 5)
它会从 doc_id 为“5”的文档中获取数据。
It will fetch the data from the document with the doc_id "5".
{
'roll_number': 5,
'st_name': 'karan',
'mark': 275,
'subject': 'oracle',
'address': 'benglore'
}
Example 2
让我们看看如何使用 doc_id 来检查数据库中是否包含特定 ID 的文档 −
Let’s see how we can use doc_id to check if the database contains a document with a specific ID −
from tinydb import TinyDB
db = TinyDB('student.json')
db.contains(doc_id = 15)
根据文档的可用性,它将返回 True 或 False。在此情况下,我们的数据库中没有 doc_id 为“15”的文档。因此,它返回 False。
Based on the availability of the document, it will return either True or False. In this case, our database does not have a document with the doc_id "15". Hence, it returns False.
False
Example 3
让我们看看如何使用 doc_id 来更新数据库的文档 −
Let’s see how we can use doc_id to update the documents of our database −
from tinydb import TinyDB
db = TinyDB('student.json')
db.update({'mark':'280'}, doc_ids = [4])
在这里,我们更新了 doc_id 为“4”的文档的“marks”字段。若要检查更新后的数据,请使用以下查询 −
Here, we updated the "marks" field of the document with the doc_id "4". To check the updated data, use the following query −
print(db.get(doc_id=4))
它将显示 doc_id 为“4”的文档的更新后数据 −
It will display the updated data of the document with the doc_id "4" −
{
'roll_number': 4,
'st_name': 'lakan',
'mark': '280',
'subject': 'MySQL',
'address': 'mumbai'
}
Example 4
让我们看看如何使用 doc_id 来从数据库中删除特定文档 −
Let’s see how we can use doc_id to remove specific documents from our database −
from tinydb import TinyDB
db = TinyDB('student.json')
db.remove(doc_ids = [3,4])
在这里,我们删除了 doc_id 为“3”和“4”的两个文档。若要验证,请使用以下 get() 查询 −
Here, we removed two documents with doc_ids "3" and "4". To verify, use the following get() queries −
db.get(doc_id=3)
db.get(doc_id=4)
它将显示以下输出 −
It will show the following output −
None
None
这意味着我们已成功删除了 doc_id 为“3”和“4”的文档。
It means that we have successfully removed the documents with doc_ids "3" and "4".
TinyDB - Tables
在 TinyDB 中,我们可以使用多张表。这些表的属性与 TinyDB 类相同。让我们看看如何在 TinyDB 中创建表并在其上应用各种操作 −
In TinyDB, we can work with multiple tables. These tables have the same properties as the TinyDB class. Let’s see how we can create tables in TinyDB and apply various operations on them −
Creating Tables
在 TinyDB 中创建表非常容易。以下是它的语法 −
It’s very easy to create a table in TinyDB. Here’s its syntax −
table_object = db.table('table name')
Inserting Values in a Table
若要在特定表中插入数据,请使用以下语法 −
To insert data in a specific table, use the following syntax −
table_object.insert({ 'key' : value })
Retreiving Values from a Table
若要从表中检索值,请使用以下查询 −
To retrieve values from a table, use the following query −
table_object.all()
Deleting a Table from a Database
若要从数据库中删除表,请使用 drop_table() 查询。以下是其 syntax −
To delete a table from a database, use the drop_table() query. Here is its syntax −
db.drop_table('table name')
Delete Multiple Tables from a Database
若要从数据库中删除多个表,请使用以下查询 −
To delete multiple tables from a database, use the following query −
db.drop_tables()
让我们借助一些示例了解如何使用这些查询。我们将使用我们在所有前几章中使用的相同 student 数据库。
Let’s understand how to use these queries with the help of a few examples. We will use the same student database that we have used in all the previous chapters.
Example 1
使用以下代码创建名为 Student_Detail 的新表 −
Use the following code to create a new table called Student_Detail −
from tinydb import TinyDB, Query
db = TinyDB("student.json")
table_object = db.table('Student_Detail')
Example 2
接下来,让我们在这个新表 Student_Detail 中插入值 −
Next, let’s insert values in this new table Student_Detail −
from tinydb import TinyDB, Query
db = TinyDB("student.json")
table_object = db.table('Student_Detail')
table_object.insert({
'roll_number': 1,
'st_name': 'elen',
'mark': 250,
'subject': 'TinyDB',
'address': 'delhi'
})
它将返回在表中插入的记录的 doc_id。
It will return the doc_id of the record inserted in the table.
[1]
要进行验证,请使用以下代码:
To verify, use the following code −
from tinydb import TinyDB, Query
db = TinyDB("student.json")
table_object = db.table('Student_Detail')
table_object.all()
它将显示 Student_Detail 表包含的数据:
It will show data contained in the Student_Detail table −
{'roll_number': 1, 'st_name': 'elen', 'mark': 250, 'subject': 'TinyDB', 'address': 'delhi'}
Example 3
要查看数据库中存在的所有表,请使用以下查询:
To see all the tables present in the database, use the following query −
from tinydb import TinyDB, Query
db = TinyDB("student.json")
print(db.tables())
"student.json" 中有两个表。它将显示这两个表的名称:
There are two tables inside "student.json". It will show the names of these two tables −
{'Student_Detail', '_default'}
Example 4
让我们看看如何从表中检索所有值:
Let’s see how we can reterive all the values from a table −
from tinydb import TinyDB, Query
db = TinyDB("student.json")
table_object = db.table("Student_Detail")
print(table_object.all())
它将显示以下内容 output :
It will show the following output −
[{
'roll_number': 1,
'st_name': 'elen',
'mark': 250,
'subject': 'TinyDB',
'address': 'delhi'
}]
Example 5
让我们看看如何从数据库中删除一个表:
Let’s see how we can remove a table from a database −
from tinydb import TinyDB, Query
db = TinyDB("student.json")
db.drop_table('Student_Detail')
它将从数据库中删除 "Student_Detail" 表。要从数据库中删除所有表,请使用 "drop_tables()" 查询:
It will remove the "Student_Detail" table from the database. To remove all the tables from a database, use the "drop_tables()" query −
db.drop_tables()
它将从数据库中删除所有表。
It will remove all the tables from the database.
TinyDB - Default Table
TinyDB 提供了一个默认表,用于自动保存和修改数据。我们还可以将一个表设置为默认表。基本查询、方法和操作将针对该默认表执行。在本章中,让我们看看如何查看数据库中的表以及如何将我们选择的一个表设置为默认表:
TinyDB provides a default table in which it automatically saves and modifies the data. We can also set a table as the default table. The basic queries, methods, and operations will work on that default table. In this chapter, let’s see how we can see the tables in a database and how we can set a table of our choice as the default table −
Showing the Tables in a Database
要获取数据库中所有表的列表,请使用以下代码:
To get the list of all the tables in a database, use the following code −
from tinydb import TinyDB, Query
db = TinyDB("student.json")
db.tables()
它将产生以下内容 output :我们有两个表位于 "student.json" 中,因此它将显示这两个表的名称:
It will produce the following output: We have two tables inside "student.json", hence it will show the names of these two tables −
{'Student_Detail', '_default'}
输出显示,我们的数据库中有两个表,一个是 "Student_Detail",另一个是 "_default"。
The output shows that we have two tables in our database, one is "Student_Detail" and the other "_default".
Displaying the Values of the Default Table
如果您使用 all() 查询,它将显示默认表的表述:
If you use the all() query, it will show the contents of the default table −
from tinydb import TinyDB
db = TinyDB("student.json")
db.all()
要显示 "Student_Detail" 表的表述,请使用以下查询:
To show the contents of the "Student_Detail" table, use the following query −
from tinydb import TinyDB
db = TinyDB("student.json")
print(db.table("Student_Detail").all())
它将显示 "Student_Detail" 表的表述:
It will show the contents of the "Student_Detail" table −
[{
'roll_number': 1,
'st_name': 'elen',
'mark': 250,
'subject': 'TinyDB',
'address': 'delhi'
}]
Setting a Default Table
您可以将您选择的表设置为默认表。为此,您需要使用以下代码:
You can set a table of your choice as the default table. For that, you need to use the following code −
from tinydb import TinyDB
db = TinyDB("student.json")
db.default_table_name = "Student_Detail"
它将把 "Student_Detail" 表设置为我们数据库的默认表。
It will set the "Student_Detail" table as the default table for our database.
TinyDB - Caching Query
查询缓存是 TinyDB 的一项高级功能,可以以此将查询结果缓存起来,以便优化性能。通过这种方式,当我们再次运行相同的查询时,TinyDB 不需要从存储中读取数据。我们可以将 cache_size 传递给表函数以优化查询缓存大小。
Catching query is an advanced feature of TinyDB with the help of which it caches the query result for performance optimization. In this way, when we run the same query again, TinyDB doesn’t need to read the data from the storage. We can pass the cache_size to the table function to optimize the query cache size.
Syntax
TinyDB 查询缓存的语法如下所示:
The syntax of TinyDB query caching is shown below −
table = db.table('table_name', cache_size=value)
Example
TinyDB 在给定表中创建缓存大小内存。
TinyDB creates cache size memory in given table.
from tinydb import TinyDB
db = TinyDB('student.json')
objects = db.table('Student_Detail', cache_size = 50)
objects.all()
它将生成以下 output 。请注意,缓存大小不会影响表值。
It will produce the following output. Observe that cache size does not affect the table values.
[{
'roll_number': 1,
'st_name': 'elen',
'mark': 250,
'subject': 'TinyDB',
'address': 'delhi'
}]
我们可通过指定“cache_size = None”来设置无限缓存大小。
We can set unlimited cache size by putting "cache_size = None".
objects = db.table('Student_Detail', cache_size = None)
我们也可以通过指定“cahce_size = 0”来禁用缓存大小。
We can also disable the cache size by putting "cache_size = 0".
objects = db.table('Student_Detail', cache_size = 0)
要清除缓存大小,请使用以下查询:
To clear the cache size, use the following query −
db.clear_cache()
TinyDB - Storage Types
TinyDB 具有两种类型的存储:JSON 和内存中。TinyDB 默认情况下将数据存储在 JSON 文件中。在创建数据库时,您需要指定在计算机上存储 JSON 文件的路径。
TinyDB has two types of storage: JSON and in-memory. TinyDB, by default, stores the data in JSON files. While creating a database, you need to specify the path where to store the JSON file on your computer.
Storing Data in a JSON File
首先,让我们看看如何使用 JSON 文件存储数据 −
First, let’s see how we can use a JSON file to store the data −
from tinydb import TinyDB, where
db = TinyDB('path/to/file_name.json')
Example 1
在此示例中,我们展示了如何将多个文档插入到 JSON 文件中 −
In this example, we are showing how you can insert multiple documents into a JSON file −
from tinydb import TinyDB
db = TinyDB('storage.json')
db.insert_multiple([
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakhan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"oracle",
"address":"benglore"
}
])
此处,我们在“storage.json”中插入了 5 个文档。要验证记录,请使用以下查询 −
Here, we inserted 5 documents inside "storage.json". To verify the records, use the following query −
db.all()
它将显示“storage.json”文件的内容 −
It will show the contents of "storage.json" file −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakhan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"oracle",
"address":"benglore"
}
]
Using in-memory to Store Data
现在,让我们看看如何使用“ in-memory ”存储数据 −
Now, let’s see how we can use "in-memory" to store the data −
from tinydb import TinyDB
from tinydb.storages import MemoryStorage
object = TinyDB(storage = MemoryStorage)
TinyDB.DEFAULT_STORAGE = MemoryStorage
Example 2
以下示例展示了如何将多个文档插入到默认存储内存中 −
The following example shows how you can insert multiple documents in default storage memory −
from tinydb import TinyDB
from tinydb.storages import MemoryStorage
object = TinyDB(storage = MemoryStorage)
TinyDB.DEFAULT_STORAGE = MemoryStorage
object.insert_multiple([
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"oracle",
"address":"benglore"
}
])
要验证是否已插入文档,请使用以下查询 −
To verify whether the documents have been inserted or not, use the following query −
object.all()
以下 output 显示了已插入数据 −
The following output shows the inserted data −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"oracle",
"address":"benglore"
}
]
TinyDB - Middleware
TinyDB 中间件通过在现有存储周围进行封装来帮助我们自定义数据库存储行为。此中间件可提高数据库的性能。
TinyDB middleware helps us to customize database storage behavior by wrapping around the existing storage. This middleware improves the performance of the database.
Caching Middleware
顾名思义,此中间件通过减少磁盘 I/O 来提升数据库速度。CachingMiddleware 的工作原理如下:
This middleware, as its name implies, improves the speed of a database by reducing the disk I/O. The working of CachingMiddleware is as follows −
-
First, it catches all the read operations.
-
Then it writes the data to the disk after a configured number of write operations.
Syntax
使用 CachingMiddleware 的语法如下:
The syntax to use CachingMiddleware is as follows −
from tinydb.storages import JSONStorage
from tinydb.middlewares import CachingMiddleware
db = TinyDB('middleware.json', storage = CachingMiddleware(JSONStorage))
db.close()
Example
以下示例演示了如何在数据库中执行基本的中间件过程。
The following example shows how you can perform a basic middleware procedure in a database.
from tinydb import TinyDB
from tinydb.storages import JSONStorage
from tinydb.middlewares import CachingMiddleware
object = TinyDB('storage.json', storage=CachingMiddleware(JSONStorage))
object.all()
Output
它将生成如下输出:
It will produce the following output −
[
{
"roll_number":1,
"st_name":"elen",
"mark":250,
"subject":"TinyDB",
"address":"delhi"
},
{
"roll_number":2,
"st_name":"Ram",
"mark":[
250,
280
],
"subject":[
"TinyDB",
"MySQL"
],
"address":"delhi"
},
{
"roll_number":3,
"st_name":"kevin",
"mark":[
180,
200
],
"subject":[
"oracle",
"sql"
],
"address":"keral"
},
{
"roll_number":4,
"st_name":"lakan",
"mark":200,
"subject":"MySQL",
"address":"mumbai"
},
{
"roll_number":5,
"st_name":"karan",
"mark":275,
"subject":"oracle",
"address":"benglore"
}
]
关闭数据库以确保安全写入所有数据。
Close the database to make sure that all the data is safely written.
db.close()
TinyDB - Extend TinyDB
可以扩展 TinyDB 并修改其行为。有四种方法可以做到:
It is possible to extend TinyDB and modify its behaviour. There are four ways to do so −
-
Custom middleware
-
Custom storages
-
Hooks and overrides
-
Subclassing TinyDB and table
在本章中,我们将详细了解每种方法。
In this chapter, let’s understand each of these methods in detail.
Custom Middleware
有时用户不想编写新的存储模块。在这种情况下,用户可以修改现有存储模块的行为。让我们来看一个示例,其中我们将构建一个用于过滤空项的自定义中间件:
Sometimes the user does not want to write a new storage module. In such cases, the user can modify the behaviour of an existing storage module. Let’s see an example in which we will build a custom middleware filtering out the empty items −
首先,让我们查看将通过自定义中间件的数据:
First, let’s see the data that will go through the custom middleware −
{
'_default': {
1: {'key1': 'value1'},
2: {'key2': 'value2'},
……………,
N: {'keyN': 'valueN'}
},
现在,让我们看看如何实现自定义中间件:
Now, let’s see how we can implement the custom middleware −
class RemoveEmptyItemsMiddleware(Middleware):
def __init__(self, storage_cls):
super(self).__init__(storage_cls)
def read(self):
data = self.storage.read()
for _default in data:
st_name = data
for doc_id in table:
item = st_name
if item == {}:
del st_name
return data
def close(self):
self.storage.close()
Custom Storage
如前所述,TinyDB 随附两种类型的存储:内存中存储和 JSON 文件存储。除此之外,TinyDB 还提供了一个选项以添加我们自己的自定义存储。在以下示例中,让我们看看如何使用 PyYAML 添加 YAML 存储:
As discussed earlier, TinyDB comes with two types of storages: in-memory and JSON file storage. Along with that, TinyDB also provides an option to add our own custom storage. In the following example, let’s see how we can add a YAML storage using PyYAML −
import yaml
class YAMLStorage(Storage):
def __init__(self, db.json):
self. db.json = db.json
To read the file −
To read the file −
def read(self):
with open(self.db.json) as handle:
try:
info = yaml.safe_load(handle.read())
return info
except yaml.YAMLError:
return None
To write the file −
To write the file −
def write(self, info):
with open(self.db.json, 'w+') as handle:
yaml.dump(info, handle)
To close the file −
To close the file −
def close(self):
pass
Hooks and Overrides
有时,自定义存储和自定义中间件都无法按照您想要的方式工作。在这样的情况下,用户可以使用预定义的挂钩和覆盖来修改 TinyDB 的行为。作为一个示例,我们将配置默认表的名称如下:
Sometimes, both custom storage and custom middleware cannot work in the way you want. In such cases, user can use predefined hooks and overrides to modify the behaviour of TinyDB. As an example, we will be configuring the name of the default table as follows −
TinyDB.default_table_name = 'student_detail'
我们还可以分配缓存容量,如下所示:
We can also assign cache capacity as follows −
TinyDB.table_class.default_query_cache_capacity = 50
Subclassing TinyDB and Table
这是我们可以用来修改 TinyDB 行为的最后一种方法。作为一个示例,我们将创建一个子类,该子类可以与钩子和覆盖一起使用来覆盖默认类。
This is the last way we can use to modify the behaviour of TinyDB. As an example, we will be creating a subclass that can be used with hooks and overrides to override the default classes.
Class ExtendTable(Table):
TinyDB.table_class = student_detail
TinyDB - Extensions
下面给出一组 TinyDB 扩展,可用于各种操作:
Given below is a set of TinyDB extensions that can be used for various operations −
Sr.No. |
Operation & Description |
1 |
*TinyDBTimestamps*It is an experimental extension that can be used to automatically add and update at timestamps to TinyDB documents. |
2 |
*aiotinydb*It is a stable extension that enables us to use TinyDB in asyncio-aware contexts without slowing done the synchromous Input/Output(I/O). |
3 |
*tinydb - smartcache*It is also a stable extension. It provides users with a smart query cache. It automatically updates the query cache so that the cache does not get invalidated after inserting, updating, or removing any documents. |
4 |
*tinydb - serialization*It is a stable extension that provides serialization of the database object. |
5 |
*tinydb - appengine*It provides storage for App Engine. It is also a stable extension. |
6 |
*Tinyrecord*A stable extension that implements experimental atomic transaction support for the TinyDB NoSQL DB. |
7 |
*TinyMP*It is also stable extension used for storage based on the MessagePack. |
8 |
*Tinymongo*It is an experimental extension which is used for the replacement of MongoDB. |
9 |
*Tinyindex*It is also an experimental extension of the database. As name implies, it is used for indexing data of the database. |