Sling Academy
Home/Node.js/How to Set Indexes in Sequelize.js

How to Set Indexes in Sequelize.js

Last updated: December 29, 2023

Overview

Sequelize is a powerful ORM for Node.js, which allows users to manage a database using an object-oriented approach. One of the critical aspects of database optimization is indexing. Indexes in Sequelize can enhance query performance by allowing the database to find records more quickly. This tutorial will guide you through the process of setting up indexes in Sequelize, starting from the basics to more advanced techniques.

Setting Up a Basic Index

To start, you’ll need to define an index in your model. Here’s a simple example:

const User = sequelize.define('user', {
  username: {
    type: Sequelize.STRING
  }
}, {
  indexes: [{
    unique: true,
    fields: ['username']
  }]
});

This code creates a unique index on the ‘username’ field in the ‘user’ table.

Composite Indexes

Now let’s create a composite index that combines multiple fields:

const User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING
  },
  lastName: {
    type: Sequelize.STRING
  }
}, {
  indexes: [{
    fields: ['firstName', 'lastName']
  }]
});

A composite index is now set on both ‘firstName’ and ‘lastName’.

Using Index Options

Sequelize also allows setting various index options like name, type, and unique constraints. Below how we create a named unique index using these options:

const User = sequelize.define('user', {
  emailAddress: {
    type: Sequelize.STRING
  }
}, {
  indexes: [{
    name: 'unique_email_address',
    unique: true,
    fields: ['emailAddress']
  }]
});

We’ve just created a unique index called ‘unique_email_address’ on the ’emailAddress’ field.

Advanced Indexing: Using Index Methods and Operators

For advanced usage, Sequelize supports various indexing methods like B-TREE, HASH, etc. Here’s how to define them:

const User = sequelize.define('user', {
  username: {
    type: Sequelize.STRING
  }
}, {
  indexes: [{
    method: 'BTREE',
    fields: ['username']
  }]
});

This snippet specifies a BTREE method for the ‘username’ index.

Functional/Partial Indexes

In scenarios where you need conditional or functional indexing, Sequelize offers a way to accommodate that as well:

const User = sequelize.define('user', {
  age: {
    type: Sequelize.INTEGER
  }
}, {
  indexes: [{
    where: {
      age: {
        [Sequelize.Op.gt]: 18
      }
    },
    fields: ['age']
  }]
});

The above code creates a partial index where only records with ‘age’ greater than 18 are indexed.

Using Indexes in Queries

After setting up indexes, it’s important to make sure that your queries are actually using them. Here’s a Sequelize query that would likely use the index defined above:

User.findAll({
  where: {
    username: 'john_doe'
  }
});

This query will benefit from the index on the ‘username’ field in the ‘user’ table.

Summary

In this tutorial, we’ve covered the basics of how to set up indexes with Sequelize, including creating single, composite, and functional indexes, as well as utilizing advanced options such as index types and methods. Proper indexing is crucial for optimizing database queries and ensuring efficient application performance.

Remember that while indexes can dramatically improve read operations, they also have a cost on write operations and can increase the storage usage of your database. Therefore, it’s important to analyze and monitor the performance and choose the right index types and fields based on your specific use cases.

Next Article: Sorting by multiple columns in Sequelize.js

Previous Article: How to Prevent SQL Injection in Sequelize.js

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates