UPDATE
This article provides an overview of the updating documents using the UPDATE and INSERT DQL operations.
Updating with UPDATE
Update operations ensure that only the minimum data necessary to enforce all peers converge on one view of the data replicates across the mesh:
For complete DQL syntax, see Ditto Query Language (DQL) > UPDATE
Updating Multiple Documents in a Collection
UPDATE operates over a condition that allows multiple documents to be updated at the same time.
In the following example, all the red cars in the cars collection are updated to be blue. The documents updated can be referenced by using the mutatedDocumentIDs method on the result.
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
"UPDATE cars SET color = 'blue' WHERE color = 'red'",
new Continuation<>() {
@NonNull
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resumeWith(@NonNull Object o) {
if (o instanceof Result.Failure) {
// Handle failure
}
}
}
);
for (String id : result.mutatedDocumentIDs()) {
System.out.println(id);
}Updating with INSERT
The INSERT operation provides conflict policy options to override default behavior if a document with the same ID already exists. By using the ON ID CONFLICT DO UPDATE policy, inserted documents automatically apply updates for all provided fields.
Updating data using an INSERT operation may cause performance to degrade. This is because when you use an INSERT operation to modify data, all provided fields update, even if they remain unchanged.
To optimize performance and reduce unnecessary overhead, apply most updates in your app through the UPDATE method instead.
Map<String, String> document = new HashMap<>();
newCar.put("_id", "123");
newCar.put("color", "red");
DittoQueryResult result = (DittoQueryResult) ditto.store.execute(
"INSERT INTO cars DOCUMENTS (:document) ON ID CONFLICT DO UPDATE",
Collections.singletonMap("document", document),
new Continuation<>() {
@NonNull
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
@Override
public void resumeWith(@NonNull Object o) {
if (o instanceof Result.Failure) {
// Handle failure
}
}
}
);For complete DQL syntax, see Ditto Query Language (DQL) > INSERT