Page updated Feb 9, 2024

Customize your data model

You are currently viewing the new GraphQL transformer v2 docs Looking for legacy docs?

Amplify automatically creates Amazon DynamoDB database tables for GraphQL types annotated with the @model directive in your GraphQL schema. You can create relations between the data models via the @hasOne, @hasMany, @belongsTo, and @manyToMany directives.

Setup database tables

The following GraphQL schema automatically creates a database table for "Todo". @model will also automatically add an id field as a primary key to the database table. See Configure a primary key to learn how to customize the primary key.

1type Todo @model {
2 content: String
3}

Upon amplify push or cdk deploy, Amplify deploys the Todo database table and a corresponding GraphQL API to perform create, read, update, delete, and list operations.

In addition, @model also adds the helper fields createdAt and updatedAt to your type. The values for those fields are read-only by clients unless explicitly overwritten. See Customize creation and update timestamps to learn more.

Try listing all the todos by executing the following query:

1query QueryAllTodos {
2 listTodos() {
3 todos {
4 items {
5 id
6 content
7 createdAt
8 updatedAt
9 }
10 }
11 }
12}

Configure a primary key

Every GraphQL type with the @model directive will automatically have an id field set as the primary key. You can override this behavior by marking another required field with the @primaryKey directive.

In the example below, todoId is the database's primary key and an id field will no longer be created automatically anymore by the @model directive.

1type Todo @model {
2 todoId: ID! @primaryKey
3 content: String
4}

Without any further configuration, you'll only be able to query for a Todo via an exact equality match of its primary key field. In the example above, this is the todoId field.

Note: After a primary key is configured and deployed, you can't change it without deleting and recreating your database table.

You can also specify "sort keys" to use a combination of different fields as a primary key. This also allows you to apply more advanced sorting and filtering conditions on the specified "sort key fields".

1type Inventory @model {
2 productID: ID! @primaryKey(sortKeyFields: ["warehouseID"])
3 warehouseID: ID!
4 InventoryAmount: Int!
5}

The schema above will allow you to pass different conditions to query the correct inventory item:

1query QueryInventoryByProductAndWarehouse($productID: ID!, $warehouseID: ID!) {
2 getInventory(productID: $productID, warehouseID: $warehouseID) {
3 productID
4 warehouseID
5 inventoryAmount
6 }
7}

Configure a secondary index

Amplify uses Amazon DynamoDB tables as the underlying data source for @model types. For key-value databases, it is critical to model your access patterns with "secondary indexes". Use the @index directive 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.

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.

1type Customer @model {
2 id: ID!
3 name: String!
4 phoneNumber: String
5 accountRepresentativeID: ID! @index
6}

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

1query QueryCustomersForAccountRepresentative($accountRepresentativeID: ID!) {
2 customersByAccountRepresentativeID(
3 accountRepresentativeID: $accountRepresentativeID
4 ) {
5 customers {
6 items {
7 id
8 name
9 phoneNumber
10 }
11 }
12 }
13}

You can also overwrite the queryField or name to customize the GraphQL query name, or secondary index name respectively:

1type Customer @model {
2 id: ID!
3 name: String!
4 phoneNumber: String
5 accountRepresentativeID: ID!
6 @index(name: "byRepresentative", queryField: "customerByRepresentative")
7}
1query QueryCustomersForAccountRepresentative($representativeId: ID!) {
2 customerByRepresentative(accountRepresentativeID: $representativeId) {
3 customers {
4 items {
5 id
6 name
7 phoneNumber
8 }
9 }
10 }
11}

To optionally configure sort keys, provide the additional fields in the sortKeyFields parameter:

1type Customer @model @auth(rules: [{ allow: public }]) {
2 id: ID!
3 name: String! @index(name: "byNameAndPhoneNumber", sortKeyFields: ["phoneNumber"], queryField: "customerByNameAndPhone")
4 phoneNumber: String
5 accountRepresentativeID: ID! @index

The example client query below allows you to query for "Customer" based on their name and filter based on phoneNumber:

1query MyQuery {
2 customerByNameAndPhone(phoneNumber: { beginsWith: "+1" }, name: "Rene") {
3 items {
4 id
5 name
6 phoneNumber
7 }
8 }
9}

Advanced

Rename generated queries, mutations, and subscriptions

You can override the names of any @model-generated GraphQL queries, mutations, and subscriptions by supplying the desired name.

1type Todo @model(queries: { get: "queryFor" }) {
2 name: String!
3 description: String
4}

In the example above, you will be able to run a queryForTodo query to get a single Todo element.

Disable generated queries, mutations, and subscriptions

You can disable specific operations by assigning their value to null.

1type Todo @model(queries: { get: null }, mutations: null, subscriptions: null) {
2 name: String!
3 description: String
4}

The example above disables the getTodo query, all mutations, and all subscriptions while allowing the generation of other queries such as listTodo.

Creating a custom query

You can disable the get query and create a custom query that enables us to retrieve a single Todo model.

1type Query {
2 getMyTodo(id: ID!): Todo @function(name: "getmytodofunction-${env}")
3}

The example above creates a custom query that utilizes the @function directive to call a Lambda function for this query.

For the type definitions of queries, mutations, and subscriptions, see Type Definitions of the @model Directive.

Customize creation and update timestamps

The @model directive automatically adds createdAt and updatedAt timestamps to each entity. The timestamp field names can be changed by passing timestamps attribute to the directive.

1type Todo
2 @model(timestamps: { createdAt: "createdOn", updatedAt: "updatedOn" }) {
3 name: String!
4 description: String
5}

For example, the schema above will allow you to query for the following contents:

1type Todo {
2 id: ID!
3 name: String!
4 description: String
5 createdOn: AWSDateTime!
6 updatedOn: AWSDateTime!
7}

Modify subscriptions (real-time updates) access level

By default, real-time updates are on for all @model types, which means customers receive real-time updates and authorization rules are applied during initial connection time. You can also turn off subscriptions for that model or make the real-time updates public, receivable by all subscribers.

1type Todo
2 @model(subscriptions: { level: off }) { # or level: public
3 name: String!
4 description: String
5}

Create multiple relationships between two models

You need to explicitly specify the connection field names if relational directives are used to create two connections of the same type between the two models.

1type Individual @model {
2 id: ID!
3 homeAddress: Address @hasOne
4 shippingAddress: Address @hasOne
5}
6
7type Address @model {
8 id: ID!
9 homeIndividualID: ID
10 shippingIndividualID: ID
11 homeIndividual: Individual @belongsTo(fields: ["homeIndividualID"])
12 shipIndividual: Individual @belongsTo(fields: ["shippingIndividualID"])
13}

Relationships to a model with a composite primary key

When a primary key is defined by a sort key in addition to the hash key, then it's called a composite primary key.

If you explicitly define the fields argument on the @hasOne, @hasMany, or @belongsTo directives and reference a model that has a composite primary key, then you must set the values in the fields argument in a specific order:

  • The first value should always be the primary key of the related model.
  • Remaining values should match the sortKeyFields specified in the @primaryKey directive of the related model.
1type Project @model {
2 projectId: ID! @primaryKey(sortKeyFields: ["name"])
3 name: String!
4 team: Team @hasOne(fields: ["teamId", "teamName"])
5 teamId: ID # customized foreign key for child primary key
6 teamName: String # customized foreign key for child sort key
7}
8
9type Team @model {
10 teamId: ID! @primaryKey(sortKeyFields: ["name"])
11 name: String!
12}
1type Project @model {
2 projectId: ID! @primaryKey(sortKeyFields: ["name"])
3 name: String!
4 team: Team @hasOne(fields: ["teamId", "teamName"])
5 teamId: ID # customized foreign key for child primary key
6 teamName: String # customized foreign key for child sort key
7}
8
9type Team @model {
10 teamId: ID! @primaryKey(sortKeyFields: ["name"])
11 name: String!
12 project: Project @belongsTo(fields: ["projectId", "projectName"])
13 projectId: ID # customized foreign key for parent primary key
14 projectName: String # customized foreign key for parent sort key
15}
1type Post @model {
2 postId: ID! @primaryKey(sortKeyFields: ["title"])
3 title: String!
4 comments: [Comment] @hasMany(indexName: "byPost", fields: ["postId", "title"])
5}
6
7type Comment @model {
8 commentId: ID! @primaryKey(sortKeyFields: ["content"])
9 content: String!
10 postId: ID @index(name: "byPost", sortKeyFields: ["postTitle"]) # customized foreign key for parent primary key
11 postTitle: String # customized foreign key for parent sort key
12}
1type Post @model {
2 postId: ID! @primaryKey(sortKeyFields: ["title"])
3 title: String!
4 comments: [Comment] @hasMany(indexName: "byPost", fields: ["postId", "title"])
5}
6
7type Comment @model {
8 commentId: ID! @primaryKey(sortKeyFields: ["content"])
9 content: String!
10 post: Post @belongsTo(fields: ["postId", "postTitle"])
11 postId: ID @index(name: "byPost", sortKeyFields: ["postTitle"]) # customized foreign key for parent primary key
12 postTitle: String # customized foreign key for parent sort key
13}

Generate a secondary index without a GraphQL query

Because query creation against a secondary index is automatic, if you wish to define a secondary index that does not have a corresponding query in your API, set the queryField parameter to null.

1type Customer @model {
2 id: ID!
3 name: String!
4 phoneNumber: String
5 accountRepresentativeID: ID! @index(queryField: null)
6}

Split GraphQL files

Amplify Studio does not support splitting GraphQL schemas.

If using Amplify Studio, please follow the Limitations section of the Data Modeling documentation for Amplify Studio.

AWS Amplify supports splitting your GraphQL schema into separate .graphql files.

You can start by creating a amplify/backend/api/<api-name>/schema/ directory. As an example, you might split up the schema for a blog site by creating Blog.graphql, Post.graphql, and Comment.graphql files.

You can then run amplify api gql-compile and the output build schema will include all the types declared across your schema files.

As your project grows, you may want to organize your custom queries, mutations, and subscriptions depending on the size and maintenance requirements of your project. You can either consolidate all of them into one file or colocate them with their corresponding models.

Using a Single Query.graphql File

This method involves consolidating all queries into a single Query.graphql file. It is useful for smaller projects or when you want to keep all queries in one place.

  1. In the amplify/backend/api/<api-name>/schema/ directory, create a file named Query.graphql.

  2. Copy all query type definitions from your multiple schema files into the Query.graphql file.

  3. Make sure all your queries are properly formatted and enclosed within a single type Query { ... } block.

Using the extend Keyword

Declaring a Query type in separate schema files will result in schema validation errors similar to the following when running amplify api gql-compile:

1🛑 Schema validation failed.
2
3There can be only one type named "Query".

Amplify GraphQL schemas support the extend keyword, which allows you to extend types with additional fields. In this case, it also allows you to split your custom queries, mutations, and subscriptions into multiple files. This may be more ideal for larger, more complex projects.

  1. Organize your GraphQL schema into multiple files as per your project's architecture.

  2. In one of the files (e.g., schema1.graphql), declare your type normally:

1type Query {
2 # initial custom queries
3}
  1. In other schema files (e.g., schema2.graphql), use the extend keyword to add to the type:
1extend type Query {
2 # additional custom queries
3}

The order in which the Query types are extended does not affect the compilation of separate schema files.

Declaring custom Query, Mutation, and/or Subscription with the same field names in another schema file will result in schema validation errors similar to the following:

🛑 Object type extension 'Query' cannot redeclare field getBlogById

How it works

Model directive

The @model directive will generate:

  • An Amazon DynamoDB table with PAY_PER_REQUEST billing mode enabled by default.
  • An AWS AppSync DataSource configured to access the table above.
  • An AWS IAM role attached to the DataSource that allows AWS AppSync to call the above table on your behalf.
  • Up to 8 resolvers (create, update, delete, get, list, onCreate, onUpdate, onDelete) but this is configurable via the queries, mutations, and subscriptions arguments on the @model directive.
  • Input objects for create, update, and delete mutations.
  • Filter input objects that allow you to filter objects in list queries and relationship fields.
  • For list queries the default number of objects returned is 100. You can override this behavior by setting the limit argument.

Type definition of the @model directive

1directive @model(
2 queries: ModelQueryMap
3 mutations: ModelMutationMap
4 subscriptions: ModelSubscriptionMap
5 timestamps: TimestampConfiguration
6) on OBJECT
7
8input ModelMutationMap {
9 create: String
10 update: String
11 delete: String
12}
13
14input ModelQueryMap {
15 get: String
16 list: String
17}
18
19input ModelSubscriptionMap {
20 onCreate: [String]
21 onUpdate: [String]
22 onDelete: [String]
23 level: ModelSubscriptionLevel
24}
25
26enum ModelSubscriptionLevel {
27 off
28 public
29 on
30}
31
32input TimestampConfiguration {
33 createdAt: String
34 updatedAt: String
35}

Relational directives

The relational directives are @hasOne, @hasMany, @belongsTo and @manyToMany.

The @hasOne will generate:

  • Foreign key fields in parent type that refer to the primary key and sort key fields of the child model.
  • Foreign key fields in parent input object of create and update mutations.

Type definition of the @hasOne directive

1directive @hasOne(fields: [String!]) on FIELD_DEFINITION

The @hasMany will generate:

  • Foreign key fields in child type that refer to the primary key and sort key fields of the parent model.
  • Foreign key fields in child input object of create and update mutations.
  • A global secondary index (GSI) in the child type Amazon DynamoDB table.

Type definition of the @hasMany directive

1directive @hasMany(
2 indexName: String
3 fields: [String!]
4 limit: Int = 100
5) on FIELD_DEFINITION
  • The default number of nested objects returned is 100. You can override this behavior by setting the limit argument.

The @belongsTo will generate:

  • Foreign key fields that refer to the primary key and sort key fields of the related model.
  • Foreign key fields in the input object of create and update mutations.

Type definition of the @belongsTo directive

1directive @belongsTo(fields: [String!]) on FIELD_DEFINITION

The @manyToMany will generate:

  • A joint table defining the intermediate model type with the name of relationName.
  • Foreign key fields in the joint table that refer to the primary key and sort key fields of both models.
  • Foreign key fields in the intermediate model input object of create and update mutations.

Type definition of the @manyToMany directive

1directive @manyToMany(
2 relationName: String!
3 limit: Int = 100
4) on FIELD_DEFINITION
  • The default number of nested objects returned is 100. You can override this behavior by setting the limit argument.