Defining indices in the ORM layer

One of the ways to improve the performance of a relational database such as SQLite is to make join operations faster. The ideal way to do this is to include enough index information so that slow search operations aren't done to find matching rows.

When we define a column that might be used in a query, we should consider building an index for that column. This is a simple process that uses SQLAlchemy. We simply annotate the attribute of the class with index=True.

We can make fairly minor changes to our Post table, for example. We can do this to add indexes:

class Post(Base): 
    __tablename__ = "POST" 
    id = Column(Integer, primary_key=True) 
    title = Column(String, index=True) 
    date = Column(DateTime, index=True) 
    blog_id = Column(Integer, ForeignKey('BLOG.id'), index=True) 

Adding two indexes for the title and date will usually speed up queries for the posts by the title or by the date. There's no guarantee that there will be an improvement in the performance. Relational database performance involves a number of factors. It's important to measure the performance of a realistic workload both with the index and without it.

Adding an index by blog_id, similarly, might speed up the join operation between rows in the Blog and Post tables. It's also possible that the database engine uses an algorithm that doesn't benefit from having this index available.

Indexes involve storage and computational overheads. An index that's rarely used might be so costly to create and maintain that it becomes a problem, not a solution. On the other hand, some indexes are so important that they can have spectacular performance improvements. In all cases, we don't have direct control over the database algorithms being used; the best we can do is create the index and measure the performance impact.

Let's take a look at schema evolution in the next section.

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

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