Skip to content

Commit 98119b5

Browse files
Adding conditional upsert docs (#76)
* Adding conditional upsert docs
1 parent b232e29 commit 98119b5

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

README.md

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ and understand how to run and work with Dgraph.
2727
- [Creating a transaction](#creating-a-transaction)
2828
- [Running a mutation](#running-a-mutation)
2929
- [Running a query](#running-a-query)
30-
- [Running an Upsert: Query + Mutation](#running-an-upsert-query--mutation)
30+
- [Running an upsert: query + mutation](#running-an-upsert-query--mutation)
31+
- [Running a conditional upsert](#running-a-conditional-upsert)
3132
- [Committing a transaction](#committing-a-transaction)
3233
- [Cleanup Resources](#cleanup-resources)
3334
- [Debug mode](#debug-mode)
@@ -255,7 +256,7 @@ const res = await txn.doRequest(req);
255256
console.log(JSON.stringify(res.getJson()));
256257
```
257258

258-
### Running an Upsert: Query + Mutation
259+
### Running an upsert: query + mutation
259260

260261
The `txn.doRequest` function allows you to run upserts consisting of one query and one mutation.
261262
Query variables could be defined and can then be used in the mutation. You can also use the
@@ -277,7 +278,33 @@ req.setQuery(query);
277278
req.setMutationsList([mu]);
278279
req.setCommitNow(true);
279280

280-
// Update email only if matching uid found.
281+
// Upsert: If wrong_email found, update the existing data
282+
// or else perform a new mutation.
283+
await dgraphClient.newTxn().doRequest(req);
284+
```
285+
286+
### Running a conditional upsert
287+
288+
The upsert block allows specifying a conditional mutation block using an `@if` directive. The mutation is executed
289+
only when the specified condition is true. If the condition is false, the mutation is silently ignored.
290+
291+
See more about Conditional Upsert [Here](https://docs.dgraph.io/mutations/#conditional-upsert).
292+
293+
```js
294+
const query = `
295+
query {
296+
user as var(func: eq(email, "[email protected]"))
297+
}`
298+
299+
const mu = new dgraph.Mutation();
300+
mu.setSetNquads(`uid(user) <email> "[email protected]" .`);
301+
mu.setCond(`@if(eq(len(user), 1))`);
302+
303+
const req = new dgraph.Request();
304+
req.setQuery(query);
305+
req.addMutations(mu);
306+
req.setCommitNow(true);
307+
281308
await dgraphClient.newTxn().doRequest(req);
282309
```
283310

0 commit comments

Comments
 (0)