Creating a cache

We added an index to each Blog that locates Posts that belong to the Blog. We can also add a top-level cache to the shelf that is slightly faster to locate all Blog instances. The essential design is similar to what's been shown in the previous section. For each blog to be added or deleted, we must update a cache of valid keys. We must also update the iterators to properly use the index. Here's another class design to mediate the access to our objects:

class Access3(Access2):

def new(self, path: Path) -> None:
super().new(path)
self.database["_Index:Blog"] = list()

def create_blog(self, blog: Blog) -> Blog:
super().create_blog(blog)
self.database["_Index:Blog"] += [blog._id]
return blog

def blog_iter(self) -> Iterator[Blog]:
return (self.database[k] for k in
self.database["_Index:Blog"])

When creating a new database, we add an administrative object and an index, with a key of "_Index:Blog". This index will be a list with the keys to each Blog entry. When we add a new Blog object, we also update this "_Index:Blog" object with the revised list of keys.

When we iterate through Blog posts, we use the index list instead of a brute-force search of keys in the database. This is slightly faster than using the shelf object's built-in keys() method to locate Blog posts.

Here are the results as measured:

Access Layer Access: 33.5 seconds 
Access Layer Access2: 4.0 seconds
Access Layer Access3: 3.9 seconds

In the next section, we will learn how to add more index maintenance.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset