Page updated Apr 19, 2024

Customize secondary indexes

You can optimize your list queries based on "secondary indexes". For example, if you have a Customer model, you can query based on the customer's id identifier field by default but you can add a secondary index based on the accountRepresentativeId to get list customers for a given account representative.

A secondary index consists of a "hash key" and, optionally, a "sort key". Use the "hash key" to perform strict equality and the "sort key" for greater than (gt), greater than or equal to (ge), less than (lt), less than or equal to (le), equals (eq), begins with, and between operations.

amplify/data/resource.ts
1export const schema = a.schema({
2 Customer: a
3 .model({
4 name: a.string(),
5 phoneNumber: a.phone(),
6 accountRepresentativeId: a.id().required(),
7 })
8 .secondaryIndexes((index) => [index("accountRepresentativeId")])
9 .authorization(allow => [allow.publicApiKey()]),
10});

The example client query below allows you to query for "Customer" records based on their accountRepresentativeId:

src/App.tsx
1import { type Schema } from '../amplify/data/resource';
2import { generateClient } from 'aws-amplify/data';
3
4const client = generateClient<Schema>();
5
6const { data, errors } =
7 await client.models.Customer.listByAccountRepresentativeId({
8 accountRepresentativeId: "YOUR_REP_ID",
9 });
Review how this works under the hood with Amazon DynamoDB

Amplify uses Amazon DynamoDB tables as the default data source for a.model(). For key-value databases, it is critical to model your access patterns with "secondary indexes". Use the .index() modifier to configure a secondary index.

Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale but making it work for your access patterns requires a bit of forethought. DynamoDB query operations may use at most two attributes to efficiently query data. The first query argument passed to a query (the hash key) must use strict equality and the second attribute (the sort key) may use gt, ge, lt, le, eq, beginsWith, and between. DynamoDB can effectively implement a wide variety of access patterns that are powerful enough for the majority of applications.

Add sort keys to secondary indexes

You can define "sort keys" to add a set of flexible filters to your query, such as "greater than" (gt), "greater than or equal to" (ge), "less than" (lt), "less than or equal to" (le), "equals" (eq), "begins with" (beginsWith), and "between" operations.

amplify/data/resource.ts
1export const schema = a.schema({
2 Customer: a
3 .model({
4 name: a.string(),
5 phoneNumber: a.phone(),
6 accountRepresentativeId: a.id().required(),
7 })
8 .secondaryIndexes((index) => [
9 index("accountRepresentativeId")
10 .sortKeys(["name"]),
11 ])
12 .authorization(allow => [allow.owner()]),
13});

On the client side, you should find a new listBy... query that's named after hash key and sort keys. For example, in this case: listByAccountRepresentativeIdAndName. You can supply the filter as part of this new list query:

src/App.tsx
1const {
2 data,
3 errors
4} =
5 await client.models.Customer.listByAccountRepresentativeIdAndName({
6 accountRepresentativeId: 'YOUR_REP_ID',
7 name: {
8 beginsWith: 'Rene',
9 },
10 });

Customize the query field for secondary indexes

You can also customize the auto-generated query name under client.models.<MODEL_NAME>.listBy... by setting the queryField() modifier.

amplify/data/resource.ts
1const schema = a.schema({
2 Customer: a
3 .model({
4 name: a.string(),
5 phoneNumber: a.phone(),
6 accountRepresentativeId: a.id().required(),
7 })
8 .secondaryIndexes((index) => [
9 index("accountRepresentativeId")
10 .queryField("listByRep"),
11 ])
12 .authorization(allow => [allow.owner()]),
13});

In your client app code, you'll see query updated under the Data client:

src/App.tsx
1const {
2 data,
3 errors
4} = await client.models.Customer.listByRep({
5 accountRepresentativeId: 'YOUR_REP_ID',
6})

Customize the name of secondary indexes

To customize the underlying DynamoDB's index name, you can optionally provide the name() modifier.

amplify/data/resource.ts
1const schema = a.schema({
2 Customer: a
3 .model({
4 name: a.string(),
5 phoneNumber: a.phone(),
6 accountRepresentativeId: a.id().required(),
7 })
8 .secondaryIndexes((index) => [
9 index("accountRepresentativeId")
10 .name("MyCustomIndexName"),
11 ])
12 .authorization(allow => [allow.owner()]),
13});