DGraph Go client upsert, returning UID

Hi,

I am trying to do a conditional upsert using the go client. Basically I want to check for the existence of a node (B), if exists link it to my node (A), if not exists then create it and link it to node (A).

My code:

	query := `{
		   keyUids as var(func: eq(value, "` + someValue + `")) 
		}`

	var mutations []*api.Mutation
	mutations = append(mutations, &api.Mutation{
		Cond:    `@if(eq(len(keyUids), 0))`, //key does not already exist
		SetJson: []byte(`{"uid":"` + entityUid + `","hardKeys":{"uid":"_:H", "dgraph.type": "HardKey", "value": "` + someValue  + `}}`),
	})
	mutations = append(mutations, &api.Mutation{
		Cond:    `@if(NOT eq(len(keyUids), 0))`,  //key already exists
		SetNquads: []byte(`<` + entityUid + `> <hardKeys> uid(keyUids) .`), // Link Key to entity
	})
	request := &api.Request{
		Query:     query,
		Mutations: mutations,
		CommitNow: true,
	}

	results, err := dgraphClient.NewTxn().Do(context.Background(), request)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(results.Uids)

This works, but i can’t get hold of node (B)'s uid in the case it already exists. Results.Uids is only populated in my “key does not already exist” scenario. I could alternatively try to access the keyUids variable, but that doesnt seem to be possible, e.g. results.Json is empty. Any ideas how to acheive this?

Many thanks,
Rob

1 Like

remove the var block e.g:
keyUids as q(func: eq(value, " + someValue + ")) { uid }

And so you will have the uid through the query result.

3 Likes

Thank you! Now i get output in results.JSON. If it helps, the thing that made me do the var block was the conditional upsert example on GitHub - dgraph-io/dgo: Official Dgraph Go client. Thanks again!