DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Restore a Transaction Log Backup in SQL Server
  • How to Attach SQL Database Without a Transaction Log File
  • A Deep Dive into Apache Doris Indexes
  • Spring Boot Sample Application Part 1: Introduction and Configuration

Trending

  • MCP Servers: The Technical Debt That Is Coming
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Kullback–Leibler Divergence: Theory, Applications, and Implications
  1. DZone
  2. Data Engineering
  3. Databases
  4. Improving Backend Performance Part 2/3: Using Database Indexes

Improving Backend Performance Part 2/3: Using Database Indexes

Part two of this series looks at the impact that a database index has in speeding up filters using a Java web application developed with Spring Boot and Vaadin.

By 
Alejandro Duarte user avatar
Alejandro Duarte
DZone Core CORE ·
Oct. 21, 21 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
24.1K Views

Join the DZone community and get the full member experience.

Join For Free

Database indexes are a concern of the developers. They have the potential to improve the performance of search and filter features that use an SQL query in the backend. In the second part of this series of articles, I'll show the impact that a database index has in speeding up filters using a Java web application developed with Spring Boot and Vaadin.

Read part 1 of this series if you want to learn how the example application that we'll use here works. You can find the code on GitHub. Also, and if you prefer, I recorded a video version of this article:

The Requirement

We have a web page with a grid that shows a list of books from a MariaDB database:

Web page with a grid that shows a list of books from a MariaDB database

We want to add a filter to allow users of this page to see which books were published on a given date.

Implementing the Repository Query and Service

We have to make some changes in the backend to support filtering data by the publish date. In the repository class, we can add the following method:

Java
 
@Repository
public interface BookRepository extends JpaRepository<Book, Integer> {

    Page<Book> findByPublishDate(LocalDate publishDate, Pageable pageable);

}

This uses lazy loading as we saw in part 1 of this series of articles. We don't have to implement this method—Spring Data will create it for us at runtime.

We also have to add a new method to the service class (which is the class that the UI uses to run business logic). Here's how:

Java
 
@Service
public class BookService {

    private final BookRepository repository;

    ...
  
    public Stream<Book> findAll(LocalDate publishDate, int page, int pageSize) {
        return repository.findByPublishDate(publishDate, PageRequest.of(page, pageSize)).stream();
    }

}

Adding a Filter to the Web Page

With the backend supporting filtering of books by publish date, we can add a date picker to the web page (or view) implementation:

Java
 
@Route("")
public class BooksView extends VerticalLayout {

    public BooksView(BookService service) {

        ...
        
        var filter = new DatePicker("Filter by publish date");
        filter.addValueChangeListener(event ->
                grid.setItems(query ->
                        service.findAll(filter.getValue(), query.getPage(), query.getPageSize())
                )
        );

        add(filter, grid);
        setSizeFull();
    }

    ...
}

This code just creates a new DatePicker object that listens to changes in its value (via a value change listener). When the value changes we use the service class to get the books published on the date selected by the user. The matching books are then set as items of the Grid.

Testing the Slow Query

We have implemented the filter; however, it is extremely slow if you have, for example, 200 thousand rows in the table. Try it! I wrote an article that explains how to generate realistic demo data for Java applications. With this number of rows, the application took several seconds to show the data on the web page on my machine (MacBook Pro 2,3 GHz Quad-Core Intel Core i5). This completely ruins the user experience.

Analyzing Queries With “Explain Query”

If you enabled query logging, you can find the query that is generated by Hibernate in the server's log. Copy it, replace the questions marks with actual values, and run it in an SQL database client. In fact, I can save you some time. Here's a simplified version of the query:

MariaDB SQL
 
SELECT id, author, image_data, pages, publish_date, title
FROM book
WHERE publish_date = '2021-09-02';

MariaDB includes the EXPLAIN statement that gives us useful information about how the engine estimates that is going to run the query. To use it, just add EXPLAIN before the query:

MariaDB SQL
 
EXPLAIN SELECT id, author, image_data, pages, publish_date, title
FROM book
WHERE publish_date = '2021-09-02';

Here's the result:

Result 40

The documentation has everything you need to know about it, but the important bit is the value in the type column: ALL. This value tells us that the engine estimates that it will have to fetch or read all the rows in the table. Not a good thing.

Creating an Index

Fortunately, we can easily fix this by creating an index on the column that we are using to filter the data: publish_date. Here's how:

Java
 
CREATE INDEX book_publish_date_index ON book(publish_date);

A database index is a data structure created by the engine, usually a b-tree (b for balanced), and that speeds up the process of finding a certain row in a table, that is, searching for a row given the value in the column on which the index is built. The process is faster thanks to the nature of b-trees—they keep the data ordered reducing the time complexity from O(N) to O(log(N)) and even O(log(1)) in some cases.

Testing the Improvement

With the index built, we can run the EXPLAIN statement again and see that the type column shows the value ref instead of ALL:

Result 42

The ref value means that the engine will use the index when we run the query. It's important that you check this when you add indexes to your more complex queries. Always use the EXPLAIN statement to double-check that you are gaining in performance when you introduce an index.

If you try the web application in the browser and select another date in the date picker (no need to restart the server), you'll see a huge difference! For example, the data is retrieved in less than a second on my machine in contrast to several seconds before we created the index!

Database sql

Opinions expressed by DZone contributors are their own.

Related

  • How to Restore a Transaction Log Backup in SQL Server
  • How to Attach SQL Database Without a Transaction Log File
  • A Deep Dive into Apache Doris Indexes
  • Spring Boot Sample Application Part 1: Introduction and Configuration

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!