Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 2024

Manipulating data

Create and update

To write data to the DataStore, pass an instance of a model to Amplify.DataStore.save():

Post post = Post.builder()
.title("My First Post")
.status(PostStatus.ACTIVE)
.rating(10)
.build();
Amplify.DataStore.save(post,
saved -> Log.i("MyAmplifyApp", "Saved a post."),
failure -> Log.e("MyAmplifyApp", "Save failed.", failure)
);
val post = Post.builder()
.title("My First Post")
.status(PostStatus.ACTIVE)
.rating(10)
.build()
Amplify.DataStore.save(post,
{ Log.i("MyAmplifyApp", "Saved a post") },
{ Log.e("MyAmplifyApp", "Save failed", it) }
)
val post = Post.builder()
.title("My First Post")
.status(PostStatus.ACTIVE)
.rating(10)
.build()
try {
Amplify.DataStore.save(post)
Log.i("MyAmplifyApp", "Saved a post.")
} catch (error: DataStoreException) {
Log.e("MyAmplifyApp", "Save failed.", error)
}
Post post = Post.builder()
.title("My First Post")
.status(PostStatus.ACTIVE)
.rating(10)
.build();
RxAmplify.DataStore.save(post)
.subscribe(
() -> Log.i("MyAmplifyApp", "Saved a post."),
failure -> Log.e("MyAmplifyApp", "Save failed.", failure)
);

The save method creates a new record, or in the event that one already exists in the local store, it updates the record.

QueryOptions queryOptions = null;
try {
queryOptions = Where.identifier(Post.class, "123");
} catch (AmplifyException e) {
Log.e("MyAmplifyApp", "Failed to construct QueryOptions with provided values for Where.identifier", e);
}
if (queryOptions != null) {
Amplify.DataStore.query(Post.class, queryOptions,
matches -> {
if (matches.hasNext()) {
Post original = matches.next();
Post edited = original.copyOfBuilder()
.title("New Title")
.build();
Amplify.DataStore.save(edited,
updated -> Log.i("MyAmplifyApp", "Updated a post."),
failure -> Log.e("MyAmplifyApp", "Update failed.", failure)
);
}
},
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);
}
Amplify.DataStore.query(Post::class.java, Where.identifier(Post::class.java, "123"),
{ matches ->
if (matches.hasNext()) {
val original = matches.next()
val edited = original.copyOfBuilder()
.title("New Title")
.build()
Amplify.DataStore.save(edited,
{ Log.i("MyAmplifyApp", "Updated a post") },
{ Log.e("MyAmplifyApp", "Update failed", it) }
)
}
},
{ Log.e("MyAmplifyApp", "Query failed", it) }
)
Amplify.DataStore.query(Post::class, Where.identifier(Post::class.java, "123"))
.catch { Log.e("MyAmplifyApp", "Query failed", it) }
.map { it.copyOfBuilder().title("New Title").build() }
.onEach { Amplify.DataStore.save(it) }
.catch { Log.e("MyAmplifyApp", "Update failed", it) }
.collect { Log.i("MyAmplifyApp", "Updated a post") }
QueryOptions queryOptions = null;
try {
queryOptions = Where.identifier(Post.class, "123");
} catch (AmplifyException e) {
Log.e("MyAmplifyApp", "Failed to construct QueryOptions with provided values for Where.identifier", e);
}
if (queryOptions != null) {
RxAmplify.DataStore.query(Post.class, queryOptions)
.map(matchingPost -> matchingPost.copyOfBuilder()
.title("New Title")
.build()
)
.flatMapCompletable(RxAmplify.DataStore::save)
.subscribe(
() -> Log.i("MyAmplifyApp", "Query and update succeeded."),
failure -> Log.e("MyAmplifyApp", "Update failed.", failure)
);
}

Models in DataStore are immutable. Instead of directly modifying the fields on a Model, you must use the .copyOfBuilder() method to create a new representation of the model.

Avoid working with stale data!

Model instances which store values, such as those from the results of a DataStore.Query operation, can become stale and outdated when their properties are updated. This can be the result of a manual change or even a side effect of real time data being received by the application. In order to ensure you are performing mutations on the latest committed state to the system, either perform a query directly before the DataStore.save() operation or observe the model to keep the state updated at all times and perform mutations on that latest state referencing the model instance. The preceding example demonstrates one approach. The following example demonstrates the observeQuery approach.

public class ObserveExample {
String tag = "ObserveQuery";
private Post post;
public void observeExample() {
Consumer<DataStoreQuerySnapshot<Post>> onQuerySnapshot = value ->{
System.out.println("value: " + value.getItems());
if (value.getItems().size() > 0) {
post = value.getItems().get(0);
}
};
Consumer<Cancelable> observationStarted = value ->{
Log.d(tag, "success on cancelable");
};
Consumer<DataStoreException> onObservationError = value ->{
Log.d(tag, "error on snapshot$value");
};
Action onObservationComplete = () ->{
Log.d(tag, "complete");
};
ObserveQueryOptions options = new ObserveQueryOptions();
Amplify.DataStore.<Post>observeQuery(
Post.class,
options,
observationStarted,
onQuerySnapshot,
onObservationError,
onObservationComplete
);
}
public void save() {
// called from UI event, for example:
Amplify.DataStore.save(
post.copyOfBuilder()
.title("new post")
.build(),
updated -> Log.i(tag, "updated post"),
failure -> Log.e(tag, "update failed", failure)
);
}
}
class ObserveExampleKt {
val tag = "ObserveQuery"
var post: Post? = null
fun observeExample() {
val onQuerySnapshot: Consumer<DataStoreQuerySnapshot<Post>> =
Consumer<DataStoreQuerySnapshot<Post>> { value: DataStoreQuerySnapshot<Post> ->
Log.d(tag, "Post updated")
post = value.items[0]
}
val observationStarted =
Consumer { _: Cancelable ->
Log.d(tag, "success on cancelable")
}
val onObservationError =
Consumer { value: DataStoreException ->
Log.d(tag, "error on snapshot $value")
}
val onObservationComplete = Action {
Log.d(tag, "complete")
}
val options = ObserveQueryOptions()
Amplify.DataStore.observeQuery(
Post::class.java,
options,
observationStarted,
onQuerySnapshot,
onObservationError,
onObservationComplete
)
}
fun save() {
// called from a UI event, for example:
post?.let {
Amplify.DataStore.save(it.copyOfBuilder()
.title("new title")
.build(),
{ Log.i(tag, "Post saved") },
{ Log.i(tag, "Error saving post") }
)
}
}
}
// For coroutines, remember to `import com.amplifyframework.kotlin.core.Amplify`
// instead of `import com.amplifyframework.core.Amplify`
// and add "implementation 'com.amplifyframework:core-kotlin:0.20.0'" to gradle dependencies
class ObserveExampleCoroutines {
var post: Post? = null
fun observeExample(lifecycleScope: LifecycleCoroutineScope) {
lifecycleScope.async {
Amplify.DataStore.observe(
Post::class
).onStart { Log.i("MyAmplifyApp", "Observation began") }
.catch { Log.e("MyAmplifyApp", "Observation failed", it) }
.onCompletion { Log.i("MyAmplifyApp", "Observation complete") }
.collect {
post = it.item()
Log.i("MyAmplifyApp", "Received post: $it")
}
}
}
fun save(lifecycleScope: LifecycleCoroutineScope) {
lifecycleScope.async {
post?.let {
Amplify.DataStore.save(it)
Log.i("MyAmplifyApp", "Post saved: $it")
}
}
}
}
// Remember to import import com.amplifyframework.rx.RxAmplify;
// and add "implementation 'com.amplifyframework:rxbindings:1.36.1'" to gradle dependencies
public class ObserveExampleRx {
private Post post;
public void observeExample() {
RxAmplify.DataStore.observe(Post.class)
.subscribe(
data -> {
post = data.item();
Log.d("MyAmplifyApp", "Received post: " + post);
},
failure -> Log.d("MyAmplifyApp", "Observe failed"),
() -> Log.d("", "Observe complete")
);
}
public void save() {
RxAmplify.DataStore.save(post.copyOfBuilder().title("New title").build())
.subscribe(
() -> Log.d("MyAmplifyApp", "Save succeeded"),
failure -> Log.d("MyAmplifyApp", "Save failed: " + failure)
);
}
}

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:

QueryOptions queryOptions = null;
try {
queryOptions = Where.identifier(Post.class, "123");
} catch (AmplifyException e) {
Log.e("MyAmplifyApp", "Failed to construct QueryOptions with provided values for Where.identifier", e);
}
if (queryOptions != null) {
Amplify.DataStore.query(Post.class, queryOptions,
matches -> {
if (matches.hasNext()) {
Post post = matches.next();
Amplify.DataStore.delete(post,
deleted -> Log.i("MyAmplifyApp", "Deleted a post."),
failure -> Log.e("MyAmplifyApp", "Delete failed.", failure)
);
}
},
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);
}
Amplify.DataStore.query(Post::class.java, Where.identifier(Post::class.java, "123"),
{ matches ->
if (matches.hasNext()) {
val post = matches.next()
Amplify.DataStore.delete(post,
{ Log.i("MyAmplifyApp", "Deleted a post.") },
{ Log.e("MyAmplifyApp", "Delete failed.", it) }
)
}
},
{ Log.e("MyAmplifyApp", "Query failed.", it) }
)
Amplify.DataStore.query(Post::class, Where.identifier(Post::class.java, "123"))
.catch { Log.e("MyAmplifyApp", "Query failed", it) }
.onEach { Amplify.DataStore.delete(it) }
.catch { Log.e("MyAmplifyApp", "Delete failed", it) }
.collect { Log.i("MyAmplifyApp", "Deleted a post") }
QueryOptions queryOptions = null;
try {
queryOptions = Where.identifier(Post.class, "123");
} catch (AmplifyException e) {
Log.e("MyAmplifyApp", "Failed to construct QueryOptions with provided values for Where.identifier", e);
}
if (queryOptions != null) {
RxAmplify.DataStore.query(Post.class, queryOptions)
.flatMapCompletable(RxAmplify.DataStore::delete)
.subscribe(
() -> Log.i("MyAmplifyApp", "Deleted a post."),
failure -> Log.e("MyAmplifyApp", "Delete failed.", failure)
);
}

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:

Amplify.DataStore.query(Post.class,
matches -> {
if (matches.hasNext()) {
Post post = matches.next();
Amplify.DataStore.delete(post, Where.matches(Post.RATING.gt(4)).getQueryPredicate(),
deleted -> Log.i("MyAmplifyApp", "Deleted a post."),
failure -> Log.e("MyAmplifyApp", "Delete failed.", failure)
);
}
},
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);
Amplify.DataStore.query(Post::class.java,
{ matches ->
if (matches.hasNext()) {
val post = matches.next()
Amplify.DataStore.delete(post, Where.matches(Post.RATING.gt(4)).queryPredicate,
{ Log.i("MyAmplifyApp", "Deleted a post.") },
{ Log.e("MyAmplifyApp", "Delete failed.", it) }
)
}
},
{ Log.e("MyAmplifyApp", "Query failed.", it) }
)
Amplify.DataStore.query(Post::class)
.catch { Log.e("MyAmplifyApp", "Query failed", it) }
.onEach { Amplify.DataStore.delete(it, Where.matches(Post.RATING.gt(4)).queryPredicate) }
.catch { Log.e("MyAmplifyApp", "Delete failed", it) }
.collect { Log.i("MyAmplifyApp", "Deleted a post") }
RxAmplify.DataStore.query(
Post.class,
Where.matches(Post.RATING.gt(4)))
.subscribe(
post -> RxAmplify.DataStore.delete(post, Where.matches(Post.RATING.gt(4)).getQueryPredicate())
.subscribe(
() -> Log.i("MyAmplifyApp", "Deleted a post."),
failure -> Log.e("MyAmplifyApp", "Delete failed.", failure)
),
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);

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.

Amplify.DataStore.query(Post.class,
allPosts -> {
while (allPosts.hasNext()) {
Post post = allPosts.next();
Log.i("MyAmplifyApp", "Title: " + post.getTitle());
}
},
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);
Amplify.DataStore.query(Post::class.java,
{ allPosts ->
while (allPosts.hasNext()) {
val post = allPosts.next()
Log.i("MyAmplifyApp", "Title: ${post.title}")
}
},
{ Log.e("MyAmplifyApp", "Query failed", it) }
)
Amplify.DataStore.query(Post::class)
.catch { Log.e("MyAmplifyApp", "Query failed", it) }
.collect { Log.i("MyAmplifyApp", "Title: ${it.title}") }
RxAmplify.DataStore.query(Post.class).subscribe(
post -> Log.i("MyAmplifyApp", "Title: " + post.getTitle()),
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);

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:

Amplify.DataStore.query(Post.class, Where.matches(Post.RATING.gt(4)),
goodPosts -> {
while (goodPosts.hasNext()) {
Post post = goodPosts.next();
Log.i("MyAmplifyApp", "Post: " + post);
}
},
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);
Amplify.DataStore.query(Post::class.java,
Where.matches(Post.RATING.gt(4)),
{ goodPosts ->
while (goodPosts.hasNext()) {
val post = goodPosts.next()
Log.i("MyAmplifyApp", "Post: $post")
}
},
{ Log.e("MyAmplifyApp", "Query failed", it) }
)
Amplify.DataStore
.query(Post::class, Where.matches(Post.RATING.gt(4)))
.catch { Log.e("MyAmplifyApp", "Query failed", it) }
.collect { Log.i("MyAmplifyApp", "Post: $it") }
RxAmplify.DataStore.query(
Post.class,
Where.matches(Post.RATING.gt(4)))
.subscribe(
post -> Log.i("MyAmplifyApp", "Post: " + post),
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);

Note: when constructing predicates, static QueryField instances such as Post.RATING do not own any information about the model to which the field belongs. In order to avoid any ambiguity between field names which are used across multiple models, it is recommended to construct a custom instance of QueryField in the form of QueryField.field("{model-name}.{field-name}") (i.e. field("post.rating")).

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:

Amplify.DataStore.query(
Post.class,
Where.matches(Post.RATING.gt(4).and(Post.STATUS.eq(PostStatus.ACTIVE))),
goodActivePosts -> {
while (goodActivePosts.hasNext()) {
Post post = goodActivePosts.next();
Log.i("MyAmplifyApp", "Post: " + post);
}
},
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);
Amplify.DataStore.query(
Post::class.java, Where.matches(Post.RATING.gt(4)
.and(Post.STATUS.eq(PostStatus.ACTIVE))
),
{ goodActivePosts ->
while (goodActivePosts.hasNext()) {
val post = goodActivePosts.next()
Log.i("MyAmplifyApp", "Post: $post ")
}
},
{ Log.e("MyAmplifyApp", "Query failed", it) }
)
Amplify.DataStore
.query(Post::class,
Where.matches(Post.RATING.gt(4)
.and(Post.STATUS.eq(PostStatus.ACTIVE)))
)
.catch { Log.e("MyAmplifyApp", "Query failed", it) }
.collect { Log.i("MyAmplifyApp", "Post: $it") }
RxAmplify.DataStore.query(
Post.class,
Where.matches(Post.RATING.gt(4).and(Post.STATUS.eq(PostStatus.ACTIVE))))
.subscribe(
post -> Log.i("MyAmplifyApp", "Post: " + post),
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);

Alternatively, the or logical operator can also be used:

Amplify.DataStore.query(
Post.class,
Where.matches(Post.RATING.gt(4).or(Post.STATUS.eq(PostStatus.ACTIVE))),
posts -> {
while (posts.hasNext()) {
Post post = posts.next();
Log.i("MyAmplifyApp", "Post: " + post);
}
},
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);
Amplify.DataStore.query(
Post::class.java, Where.matches(
Post.RATING.gt(4)
.or(Post.STATUS.eq(PostStatus.ACTIVE))
),
{ posts ->
while (posts.hasNext()) {
val post = posts.next()
Log.i("MyAmplifyApp", "Post: $post")
}
},
{ Log.e("MyAmplifyApp", "Query failed", it) }
)
Amplify.DataStore
.query(Post::class,
Where.matches(Post.RATING.gt(4)
.or(Post.STATUS.eq(PostStatus.ACTIVE)))
)
.catch { Log.e("MyAmplifyApp", "Query failed", it) }
.collect { Log.i("MyAmplifyApp", "Post: $it") }
RxAmplify.DataStore.query(
Post.class,
Where.matches(Post.RATING.gt(4).or(Post.STATUS.eq(PostStatus.ACTIVE))))
.subscribe(
post -> Log.i("MyAmplifyApp", "Post: " + post),
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);

Sort

Query results can also be sorted by one or more fields.

For example, to sort all Post objects by rating in ascending order:

Amplify.DataStore.query(Post.class,
Where.sorted(Post.RATING.ascending()),
posts -> {
while (posts.hasNext()) {
Post post = posts.next();
Log.i("MyAmplifyApp", "Title: " + post.getTitle());
}
},
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);
Amplify.DataStore.query(Post::class.java,
Where.sorted(Post.RATING.ascending()),
{ posts ->
while (posts.hasNext()) {
val post = posts.next()
Log.i("MyAmplifyApp", "Title: ${post.title}")
}
},
{ Log.e("MyAmplifyApp", "Query failed", it) }
)
Amplify.DataStore
.query(Post::class, Where.sorted(Post.RATING.ascending()))
.catch { Log.e("MyAmplifyApp", "Query failed", it) }
.collect { Log.i("MyAmplifyApp", "Title: ${it.title}") }
RxAmplify.DataStore.query(Post.class,
Where.sorted(Post.RATING.ascending())
.subscribe(
post -> Log.i("MyAmplifyApp", "Post: " + post),
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);

To get all Post objects sorted first by rating in ascending order, and then by title in descending order:

Amplify.DataStore.query(Post.class,
Where.sorted(Post.RATING.ascending(), Post.TITLE.descending()),
posts -> {
while (posts.hasNext()) {
Post post = posts.next();
Log.i("MyAmplifyApp", "Title: " + post.getTitle());
}
},
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);
Amplify.DataStore.query(Post::class.java,
Where.sorted(Post.RATING.ascending(), Post.TITLE.descending()),
{ posts ->
while (posts.hasNext()) {
val post = posts.next()
Log.i("MyAmplifyApp", "Title: ${post.title}")
}
},
{ Log.e("MyAmplifyApp", "Query failed", it) }
)
Amplify.DataStore
.query(Post::class,
Where.sorted(Post.RATING.ascending(), Post.TITLE.descending())
)
.catch { Log.e("MyAmplifyApp", "Query failed", it) }
.collect { Log.i("MyAmplifyApp", "Title: ${it.title}") }
RxAmplify.DataStore.query(Post.class,
Where.sorted(Post.RATING.ascending(), Post.TITLE.descending()))
.subscribe(
post -> Log.i("MyAmplifyApp", "Post: " + post),
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);

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:

Amplify.DataStore.query(Post.class,
Where.matchesAll().paginated(Page.startingAt(0).withLimit(100)),
matchingPosts -> {
while (matchingPosts.hasNext()) {
Post post = matchingPosts.next();
Log.i("MyAmplifyApp", "Title: " + post.getTitle());
}
},
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);
Amplify.DataStore.query(Post::class.java,
Where.matchesAll().paginated(Page.startingAt(0).withLimit(100)),
{ posts ->
while (posts.hasNext()) {
val post = posts.next()
Log.i("MyAmplifyApp", "Title: ${post.title}")
}
},
{ Log.e("MyAmplifyApp", "Query failed", it) }
)
Amplify.DataStore
.query(Post::class,
Where.matchesAll()
.paginated(Page.startingAt(0).withLimit(100))
)
.catch { Log.e("MyAmplifyApp", "Query failed", it) }
.collect { Log.i("MyAmplifyApp", "Title: ${it.title}") }
RxAmplify.DataStore.query(
Post.class,
Where.matchesAll().paginated(Page.startingAt(0).withLimit(100)))
.subscribe(
post -> Log.i("MyAmplifyApp", "Title: " + post.getTitle()),
failure -> Log.e("MyAmplifyApp", "Query failed.", failure)
);

Query, then observe changes

To both query and observe subsequent changes to a Model, consider using observeQuery.