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.
export const schema = a.schema({ Customer: a .model({ name: a.string(), phoneNumber: a.phone(), accountRepresentativeId: a.id().required(), }) .secondaryIndexes((index) => [index("accountRepresentativeId")]) .authorization(allow => [allow.publicApiKey()]),});The example client query below creates a custom GraphQL request that allows you to query for "Customer" records based on their accountRepresentativeId:
data class CustomerDetails( val id: String, val name: String?, val phoneNumber: String?, val accountRepresentativeId: String)
data class CustomerConnection( val items: List<CustomerDetails>, val nextToken: String?)
data class ListCustomerByAccountRepresentativeIdResponse( val listCustomerByAccountRepresentativeId: CustomerConnection)
val document = """ query ListCustomerByAccountRepresentativeId(${'$'}accountRepresentativeId: ID!) { listCustomerByAccountRepresentativeId( accountRepresentativeId: ${'$'}accountRepresentativeId ) { items { id name phoneNumber accountRepresentativeId } nextToken } }""".trimIndent()
val request = SimpleGraphQLRequest<String>( document, mapOf("accountRepresentativeId" to "<rep-id>"), String::class.java, GsonVariablesSerializer())
Amplify.API.query( request, { var gson = Gson() val response = gson.fromJson( it.data, ListCustomerByAccountRepresentativeIdResponse::class.java ) Log.i("MyAmplifyApp", "${response.listCustomerByAccountRepresentativeId.items}") }, { Log.e("MyAmplifyApp", "Query failed", it) })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 .secondaryIndexes() 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.
export const schema = a.schema({ Customer: a .model({ name: a.string(), phoneNumber: a.phone(), accountRepresentativeId: a.id().required(), }) .secondaryIndexes((index) => [ index("accountRepresentativeId") .sortKeys(["name"]), ]) .authorization(allow => [allow.owner()]),});On the client side, you can create a custom GraphQL request based on the new listBy... query that's named after hash key and sort keys. You can supply the sort key condition as part of this new list query:
data class CustomerDetails( val id: String, val name: String?, val phoneNumber: String?, val accountRepresentativeId: String)
data class CustomerConnection( val items: List<CustomerDetails>, val nextToken: String?)
data class ListCustomerByAccountRepresentativeIdAndNameResponse( val listCustomerByAccountRepresentativeIdAndName: CustomerConnection)
val document = """ query ListCustomerByAccountRepresentativeIdAndName( ${'$'}accountRepresentativeId: ID! ${'$'}name: ModelStringKeyConditionInput ) { listCustomerByAccountRepresentativeIdAndName( accountRepresentativeId: ${'$'}accountRepresentativeId name: ${'$'}name ) { items { id name phoneNumber accountRepresentativeId } nextToken } }""".trimIndent()
val request = SimpleGraphQLRequest<String>( document, mapOf( "accountRepresentativeId" to "<rep-id>", "name" to mapOf("beginsWith" to "Rene") ), String::class.java, GsonVariablesSerializer())
Amplify.API.query( request, { var gson = Gson() val response = gson.fromJson( it.data, ListCustomerByAccountRepresentativeIdAndNameResponse::class.java ) Log.i("MyAmplifyApp", "${response.listCustomerByAccountRepresentativeIdAndName.items}") }, { Log.e("MyAmplifyApp", "Query failed", it) })Customize the query field for secondary indexes
You can also customize the auto-generated query name by setting the queryField() modifier.
const schema = a.schema({ Customer: a .model({ name: a.string(), phoneNumber: a.phone(), accountRepresentativeId: a.id().required(), }) .secondaryIndexes((index) => [ index("accountRepresentativeId") .queryField("listByRep"), ]) .authorization(allow => [allow.owner()]),});In your client app code, you can use the updated query name.
data class CustomerDetails( val id: String, val name: String?, val phoneNumber: String?, val accountRepresentativeId: String)
data class CustomerConnection( val items: List<CustomerDetails>, val nextToken: String?)
data class ListByRepResponse( val listByRep: CustomerConnection)
val document = """ query ListByRep(${'$'}accountRepresentativeId: ID!) { listByRep( accountRepresentativeId: ${'$'}accountRepresentativeId ) { items { id name phoneNumber accountRepresentativeId } nextToken } }""".trimIndent()
val request = SimpleGraphQLRequest<String>( document, mapOf("accountRepresentativeId" to "<rep-id>"), String::class.java, GsonVariablesSerializer())
Amplify.API.query( request, { var gson = Gson() val response = gson.fromJson(it.data, ListByRepResponse::class.java) Log.i("MyAmplifyApp", "${response.listByRep.items}") }, { Log.e("MyAmplifyApp", "Query failed", it) })Customize the name of secondary indexes
To customize the underlying DynamoDB's index name, you can optionally provide the name() modifier.
const schema = a.schema({ Customer: a .model({ name: a.string(), phoneNumber: a.phone(), accountRepresentativeId: a.id().required(), }) .secondaryIndexes((index) => [ index("accountRepresentativeId") .name("MyCustomIndexName"), ]) .authorization(allow => [allow.owner()]),});Customize the projection type of secondary indexes
You can control which attributes are projected (copied) into your secondary indexes to reduce storage costs and optimize for your query patterns. Use the .projection() modifier to specify a projection type.
const schema = a.schema({ Product: a .model({ id: a.id().required(), name: a.string().required(), category: a.string().required(), price: a.float().required(), description: a.string(), inStock: a.boolean().required(), }) .secondaryIndexes((index) => [ // Project only keys - smallest index size index('category').projection('KEYS_ONLY'), // Project specific attributes you need to query in addition to the keys index('inStock').projection('INCLUDE', ['name', 'price']), // Project all attributes (default) index('name').projection('ALL'), ]) .authorization(allow => [allow.publicApiKey()]),});Review projection types and when to use them
DynamoDB supports three projection types:
- KEYS_ONLY - Projects only index and primary keys. Smallest index size, lowest storage cost.
- INCLUDE - Projects keys plus specified attributes. Balances storage cost with query flexibility.
- ALL - Projects all attributes. Maximum query flexibility but highest storage cost (default).
Choose based on your query patterns and storage cost requirements. For more details, see Projections in DynamoDB.