0
0
DynamodbComparisonBeginner · 4 min read

When to Use GSI vs LSI in DynamoDB: Key Differences and Use Cases

Use a Local Secondary Index (LSI) when you need an alternate sort key for queries on the same partition key and require strong consistency. Use a Global Secondary Index (GSI) when you need to query across different partition keys or want more flexible indexing with eventual consistency.
⚖️

Quick Comparison

This table summarizes the main differences between Global Secondary Indexes (GSI) and Local Secondary Indexes (LSI) in DynamoDB.

FeatureGlobal Secondary Index (GSI)Local Secondary Index (LSI)
Partition KeyCan be different from base table's partition keyMust be same as base table's partition key
Sort KeyOptional, can be different from base table's sort keyMust be different from base table's sort key
ConsistencyEventually consistent reads onlySupports strongly consistent reads
Number per TableUp to 20 GSIsUp to 5 LSIs
StorageIndexed data stored separatelyIndexed data stored with base table data
Creation TimeCan be added after table creationMust be defined at table creation
⚖️

Key Differences

Local Secondary Indexes (LSI) share the same partition key as the base table but allow a different sort key. This means you can query the same partition with multiple sort keys, which is useful for sorting or filtering data differently within the same partition. LSIs support strongly consistent reads, so your queries reflect the latest data immediately.

In contrast, Global Secondary Indexes (GSI) allow you to define a completely different partition key and optional sort key. This flexibility lets you query data across partitions or with different keys than the base table. GSIs only support eventually consistent reads, meaning there might be a slight delay before changes appear in queries. Also, GSIs can be added or removed anytime after table creation, unlike LSIs which must be set up when the table is created.

Storage-wise, LSIs store their data alongside the base table, which can impact table size limits, while GSIs store data separately, allowing more scalability. The number of indexes allowed also differs: up to 5 LSIs and up to 20 GSIs per table.

⚖️

Code Comparison

Here is an example of creating a DynamoDB table with a Local Secondary Index (LSI) to query items by a different sort key within the same partition key.

javascript
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB();

const params = {
  TableName: 'Music',
  KeySchema: [
    { AttributeName: 'Artist', KeyType: 'HASH' },  // Partition key
    { AttributeName: 'SongTitle', KeyType: 'RANGE' } // Sort key
  ],
  AttributeDefinitions: [
    { AttributeName: 'Artist', AttributeType: 'S' },
    { AttributeName: 'SongTitle', AttributeType: 'S' },
    { AttributeName: 'AlbumTitle', AttributeType: 'S' }
  ],
  LocalSecondaryIndexes: [
    {
      IndexName: 'AlbumTitleIndex',
      KeySchema: [
        { AttributeName: 'Artist', KeyType: 'HASH' },
        { AttributeName: 'AlbumTitle', KeyType: 'RANGE' }
      ],
      Projection: {
        ProjectionType: 'ALL'
      }
    }
  ],
  BillingMode: 'PAY_PER_REQUEST'
};

dynamodb.createTable(params, (err, data) => {
  if (err) console.log(err);
  else console.log('Table with LSI created:', data);
});
Output
Table with LSI created: { TableDescription: { TableName: 'Music', TableStatus: 'CREATING', ... } }
↔️

Global Secondary Index Equivalent

Here is how to create a DynamoDB table with a Global Secondary Index (GSI) to query items by a different partition key and sort key.

javascript
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB();

const params = {
  TableName: 'Music',
  KeySchema: [
    { AttributeName: 'Artist', KeyType: 'HASH' },  // Partition key
    { AttributeName: 'SongTitle', KeyType: 'RANGE' } // Sort key
  ],
  AttributeDefinitions: [
    { AttributeName: 'Artist', AttributeType: 'S' },
    { AttributeName: 'SongTitle', AttributeType: 'S' },
    { AttributeName: 'Genre', AttributeType: 'S' }
  ],
  GlobalSecondaryIndexes: [
    {
      IndexName: 'GenreIndex',
      KeySchema: [
        { AttributeName: 'Genre', KeyType: 'HASH' },
        { AttributeName: 'SongTitle', KeyType: 'RANGE' }
      ],
      Projection: {
        ProjectionType: 'ALL'
      }
    }
  ],
  BillingMode: 'PAY_PER_REQUEST'
};

dynamodb.createTable(params, (err, data) => {
  if (err) console.log(err);
  else console.log('Table with GSI created:', data);
});
Output
Table with GSI created: { TableDescription: { TableName: 'Music', TableStatus: 'CREATING', ... } }
🎯

When to Use Which

Choose a Local Secondary Index (LSI) when:

  • You want to query the same partition key with different sort keys.
  • You need strongly consistent reads for your queries.
  • You can define the index only at table creation time.

Choose a Global Secondary Index (GSI) when:

  • You need to query data using a different partition key than the base table.
  • You want to add or remove indexes after the table is created.
  • You can accept eventually consistent reads for better flexibility and scalability.
  • You need more than 5 indexes or want to store indexed data separately.

In summary, use LSIs for alternate sorting within the same partition and strong consistency, and GSIs for flexible querying across partitions and dynamic index management.

Key Takeaways

Use LSI to query the same partition key with different sort keys and get strongly consistent reads.
Use GSI to query with different partition keys and add indexes after table creation.
LSIs are limited to 5 per table and must be defined at creation; GSIs allow up to 20 and can be added later.
GSIs provide eventual consistency and store data separately, improving scalability.
Choose based on your query patterns and consistency needs.