Manipulating data
Create and update
To write data to the DataStore, pass an instance of a model to Amplify.DataStore.save()
:
1Post post = Post.builder()2 .title("My First Post")3 .status(PostStatus.ACTIVE)4 .rating(10)5 .build();6
7Amplify.DataStore.save(post,8 saved -> Log.i("MyAmplifyApp", "Saved a post."),9 failure -> Log.e("MyAmplifyApp", "Save failed.", failure)10);
The save
method creates a new record, or in the event that one already exists in the local store, it updates the record.
1QueryOptions queryOptions = null;2try {3 queryOptions = Where.identifier(Post.class, "123");4} catch (AmplifyException e) {5 Log.e("MyAmplifyApp", "Failed to construct QueryOptions with provided values for Where.identifier", e);6}7
8if (queryOptions != null) {9 Amplify.DataStore.query(Post.class, queryOptions,10 matches -> {11 if (matches.hasNext()) {12 Post original = matches.next();13 Post edited = original.copyOfBuilder()14 .title("New Title")15 .build();16 Amplify.DataStore.save(edited,17 updated -> Log.i("MyAmplifyApp", "Updated a post."),18 failure -> Log.e("MyAmplifyApp", "Update failed.", failure)19 );20 }21 },22 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)23 );24}
1public class ObserveExample {2
3 String tag = "ObserveQuery";4 private Post post;5
6 public void observeExample() {7 Consumer<DataStoreQuerySnapshot<Post>> onQuerySnapshot = value ->{8 System.out.println("value: " + value.getItems());9 if (value.getItems().size() > 0) {10 post = value.getItems().get(0);11 }12 };13 Consumer<Cancelable> observationStarted = value ->{14 Log.d(tag, "success on cancelable");15 };16 Consumer<DataStoreException> onObservationError = value ->{17 Log.d(tag, "error on snapshot$value");18 };19 Action onObservationComplete = () ->{20 Log.d(tag, "complete");21 };22
23 ObserveQueryOptions options = new ObserveQueryOptions();24
25 Amplify.DataStore.<Post>observeQuery(26 Post.class,27 options,28 observationStarted,29 onQuerySnapshot,30 onObservationError,31 onObservationComplete32 );33 }34
35 public void save() {36 // called from UI event, for example:37 Amplify.DataStore.save(38 post.copyOfBuilder()39 .title("new post")40 .build(),41 updated -> Log.i(tag, "updated post"),42 failure -> Log.e(tag, "update failed", failure)43 );44 }45}
Delete
To delete an item, simply pass in an instance.
Below, you query for an instance with an id
of "123"
, and then delete it, if found:
1QueryOptions queryOptions = null;2try {3 queryOptions = Where.identifier(Post.class, "123");4} catch (AmplifyException e) {5 Log.e("MyAmplifyApp", "Failed to construct QueryOptions with provided values for Where.identifier", e);6}7
8if (queryOptions != null) {9 Amplify.DataStore.query(Post.class, queryOptions,10 matches -> {11 if (matches.hasNext()) {12 Post post = matches.next();13 Amplify.DataStore.delete(post,14 deleted -> Log.i("MyAmplifyApp", "Deleted a post."),15 failure -> Log.e("MyAmplifyApp", "Delete failed.", failure)16 );17 }18 },19 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)20 );21}
To conditionally delete an instance, pass an instance and a predicate into Amplify.DataStore.delete()
.
In the example below, posts are deleted only if their rating
is greater than 4
:
1Amplify.DataStore.query(Post.class,2 matches -> {3 if (matches.hasNext()) {4 Post post = matches.next();5 Amplify.DataStore.delete(post, Where.matches(Post.RATING.gt(4)).getQueryPredicate(),6 deleted -> Log.i("MyAmplifyApp", "Deleted a post."),7 failure -> Log.e("MyAmplifyApp", "Delete failed.", failure)8 );9 }10 },11 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)12);
Query Data
Queries are performed against the local store. When cloud synchronization is enabled, the local store is updated in the background by the DataStore Sync Engine.
For more advanced filtering, such as matching arbitrary field values on an object, you can supply a query predicate.
1Amplify.DataStore.query(Post.class,2 allPosts -> {3 while (allPosts.hasNext()) {4 Post post = allPosts.next();5 Log.i("MyAmplifyApp", "Title: " + post.getTitle());6 }7 },8 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)9);
Predicates
Predicates are filters that can be used to match items in the DataStore. When applied to a query(), they constrain the returned results. When applied to a save(), they act as a pre-requisite for updating the data. You can match against fields in your schema by using the following predicates:
Strings: eq | ne | le | lt | ge | gt | contains | notContains | beginsWith | between
Numbers: eq | ne | le | lt | ge | gt | between
Lists: contains | notContains
For example if you wanted a list of all Post
Models that have a rating
greater than 4:
1Amplify.DataStore.query(Post.class, Where.matches(Post.RATING.gt(4)),2 goodPosts -> {3 while (goodPosts.hasNext()) {4 Post post = goodPosts.next();5 Log.i("MyAmplifyApp", "Post: " + post);6 }7 },8 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)9);
Multiple conditions can also be used, like the ones defined in GraphQL Transform condition statements. For example, fetch all posts that have a rating greater than 4
and are ACTIVE
:
1Amplify.DataStore.query(2 Post.class,3 Where.matches(Post.RATING.gt(4).and(Post.STATUS.eq(PostStatus.ACTIVE))),4 goodActivePosts -> {5 while (goodActivePosts.hasNext()) {6 Post post = goodActivePosts.next();7 Log.i("MyAmplifyApp", "Post: " + post);8 }9 },10 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)11);
Alternatively, the or
logical operator can also be used:
1Amplify.DataStore.query(2 Post.class,3 Where.matches(Post.RATING.gt(4).or(Post.STATUS.eq(PostStatus.ACTIVE))),4 posts -> {5 while (posts.hasNext()) {6 Post post = posts.next();7 Log.i("MyAmplifyApp", "Post: " + post);8 }9 },10 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)11);
Sort
Query results can also be sorted by one or more fields.
For example, to sort all Post
objects by rating
in ascending order:
1Amplify.DataStore.query(Post.class,2 Where.sorted(Post.RATING.ascending()),3 posts -> {4 while (posts.hasNext()) {5 Post post = posts.next();6 Log.i("MyAmplifyApp", "Title: " + post.getTitle());7 }8 },9 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)10);
To get all Post
objects sorted first by rating
in ascending order, and then by title
in descending order:
1Amplify.DataStore.query(Post.class,2 Where.sorted(Post.RATING.ascending(), Post.TITLE.descending()),3 posts -> {4 while (posts.hasNext()) {5 Post post = posts.next();6 Log.i("MyAmplifyApp", "Title: " + post.getTitle());7 }8 },9 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)10);
Pagination
Query results can also be paginated by passing in a page
number (starting at 0) and an optional limit
(defaults to 100). This will return a list of the first 100 items:
1Amplify.DataStore.query(Post.class,2 Where.matchesAll().paginated(Page.startingAt(0).withLimit(100)),3 matchingPosts -> {4 while (matchingPosts.hasNext()) {5 Post post = matchingPosts.next();6 Log.i("MyAmplifyApp", "Title: " + post.getTitle());7 }8 },9 failure -> Log.e("MyAmplifyApp", "Query failed.", failure)10);