How to use Dgraph to automatically increase ID?

Sometimes, we extract some particular log attributes to be target data which would be stored in DB but without specific names. If in RDB, each of logs can be given an auto-increment primary key as their name. However, I’m not sure what the best practice is in Dgraph.

Take an example.
In MySQL, we can automatically give each run a specific ID by setting an auto-increment primary key. However, if in Dgraph, we need to get the latest run ID by querying and increase them by ourselves.

// for RDB (gorm for mysql)
type Run struct {
	ID         uint      `gorm:"primary_key" json:"id"`
	Output     string    `json:"output"`
	Action     string    `json:"action"`
	Status     string    `json:"status"`
	CreatedAt  time.Time `json:"created_at"`
}

// for dgraph (dgraph schema)
type Run {
	run.id:			int
	run.output:		string
	run.action:		string
	run.status:		string
	run.created_at:	datetime
}
run.id:			int @index(int) .
run.output:		string .
run.action:		string .
run.status:		string .
run.created_at:	datetime .

Is there any other way to automatically increase ID instead of querying and increase them?
Thank you for your help

Hi, dgraph can generate an unique UID for each entity node. This web https://docs.dgraph.io/mutations/#blank-nodes-and-uid may be helpful.

You can try Upsert Block

upsert {
  query {
    ## I'm not sure if "first:-1" would work 
    var(func: has(run.id), first:-1) { 
    getLastID as run.id
    Increment as math(getLastID + 1)
}

  }

  mutation {
    set {
       _:New <run.id> val(Increment) .
       _:New <run.output> " "  .
       _:New <run.action > " "  .
       _:New <run.status > " " .
       _:New <run.created_at > " " .
    }
  }
}
1 Like

Great!!! That’s what I want !!!
Temporarily, we would like to maintain MySQL and Dgraph at the same time.
Due to data consistency, we need to consider some special cases which are appropriate for properties of RDB but not for Dgraph’s.

Thank you for your help :smiling_face_with_three_hearts: