TinyDB - Caching Query



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

The syntax of TinyDB query caching is shown below −

table = db.table('table_name', cache_size=value)

Example

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()

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'
}]

We can set unlimited cache size by putting "cache_size = None".

objects = db.table('Student_Detail', cache_size = None)

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()
Advertisements