amplify-category-api
amplify-category-api copied to clipboard
What is the best way to change a sync query from a scan to a query using an owner field index?
Amplify CLI Version
12.12.4
Question
type Profile @model @auth(rules: [{ allow: owner, ownerField: "owner" }]) {
id: ID!
owner: String @index(name: "profileByOwner")
name: String!
}
I have defined a Profile model in the schema as shown above. And I am using DataStore.
authModeStrategy: AuthModeStrategy.multiAuth,
syncInterval: null,
syncExpressions: []
In this case, the DataStore's syncProfile query performs a Scan on the Profile table and filters the target user profiles using a filterExpression. The resolver for syncProfile is using the default auto-generated one. Below is the CloudTrail log:
{
...
"eventVersion": "1.08",
"userIdentity": { ... },
"eventTime": "2024-07-12T06:22:37Z",
"eventSource": "dynamodb.amazonaws.com",
"eventName": "Scan",
"awsRegion": "ap-northeast-1",
"sourceIPAddress": "appsync.amazonaws.com",
"userAgent": "appsync.amazonaws.com",
"requestParameters": {
"tableName": "Profile",
"filterExpression": "((#owner = :or_0_owner_eq) OR (#owner = :or_1_owner_eq) OR (#owner = :or_2_owner_eq))",
"expressionAttributeNames": { "#owner": "owner" },
"limit": 1000,
"consistentRead": false
},
"responseElements": null,
"resources": [
{
"accountId": "XXXXX",
"type": "AWS::DynamoDB::Table",
"ARN": "arn:aws:dynamodb:ap-northeast-1:XXXX:table/Profile"
}
],
"eventType": "AwsApiCall",
"apiVersion": "2012-08-10",
"managementEvent": false,
"eventCategory": "Data",
...
}
I am having trouble because it's performing a Scan even when retrieving only the owner's data, which is causing unnecessary costs. The same issue applies to other models as well.
I would like to avoid performing a scan using the profileByOwner index on the Profile table in a sync query, how can I solve this?