Use below DQL for set auto increment code for database
upsert {
query {
var(func: has(User.code), orderdesc: User.code, first:1) {
lastId as User.code
}
me() {
VD as sum(val(lastId))
Increment as math(VD + 1)
}
}
mutation {
set {
_:user <dgraph.type> "User" .
_:user <User.code> val(Increment) .
_:user <User.name> "John" .
}
}
}
Which is working fine but when there is no record on User
(first time) shown error as while running ToJson: Only aggregated variables allowed within empty block.
Check out the @if directive. Very common use case that it solves.
The upsert block also allows specifying conditional mutation blocks using an @if
directive. The mutation is executed only when the specified condition is true. If the
condition is false, the mutation is silently ignored. The general structure of
Conditional Upsert looks like as follows:
upsert {
query <query block>
[fragment <fragment block>]
mutation [@if(<condition>)] <mutation block 1>
[mutation [@if(<condition>)] <mutation block 2>]
...
}
The @if directive accepts a condition on…
Here @if condition allow on mutation.
Error because of Increment as math(VD + 1)
line where can’t use if condition. also condition can’t use in set value.
On single mutation need to add 1 for code if Increment
not found.
upsert {
query {
var(func: has(User.code), orderdesc: User.code, first:1) {
lastId as User.code
VD as math(lastId + 1)
}
me() {
Increment as sum(val(VD))
}
}
mutation {
set {
_:user <dgraph.type> "User" .
_:user <User.name> "John" .
}
}
mutation @if(gt(len(VD), 0)) {
set {
_:user <User.code> val(Increment) .
}
}
mutation @if(eq(len(VD), 0)) {
set {
_:user <Repair.code> "1" .
}
}
}