Update 6/25/21
So I cannot do nested filters. Hopefully Dgraph will add this, and I don’t want to sort anything on the client side. I probably won’t add anything else, as it pretty much does everything (until Dgraph itself adds new features).
Deep Updates
You can specify your ID, or it will infer it to be id automatically…
const d = new Dgraph('lesson').deep({ field: 'cards', type: 'card' }).update({
me: 1,
cards: {
id: 1,
tommy: 1
}
}).filter({ id: '12345' })
.set({ me: false, cards: [{ tommy: 'son' }, { id: '2', tommy: 'bill' }] })
.build();
This will automatically create a complex mutation with add and update(s).
See here for more examples…
Deep Deletes
Deep deletes simply cannot be done in one query, as I discussed here. While not perfect or feasible if you have thousands of nodes you want to delete, this might work for most situations.
Say I want to delete all lessons when I delete a class type, which has many lessons…
async delete(id: string): Promise<void> {
// get ids of lessons
const ids = await this.dgraph.type('class').filter(id).query({
lessons: { id: 1 }
}).build();
// delete ids && delete lesson
await this.dgraph.type('lesson').filter(ids).delete()
.type('class').filter(id).delete().build();
...
}
You could basically grab ALL ids of lessons by a certain class, then create a mutation which deletes all those lessons by id, then that class.
Keep in mind, Dgraph returns all the ids in a data type, so you may need to map those ids with something like:
build().then((r: any[]) => {
if (r[0].lessons) {
return r[0].lessons.map((r: any) => r.id);
}
});
Either way, you avoid custom dql… yay!
Hope this helps someone,
J