Home > database >  Cloud datastore queries, where is the key?
Cloud datastore queries, where is the key?

Time:12-03

I have stored some data on Google cloud datastore.

Querying the data is not an issue, I can use an iterator and get the properties of the data. example; https://cloud.google.com/datastore/docs/concepts/queries#projection_queries

var priorities []int
var percents []float64
it := client.Run(ctx, query)
for {
    var task Task
    if _, err := it.Next(&task); err == iterator.Done {
            break
    } else if err != nil {
            log.Fatal(err)
    }
    priorities = append(priorities, task.Priority)
    percents = append(percents, task.PercentComplete)
}

I can access the Properties of the entity with no problem but have no idea on how to read/access the keys.

How do I get the keys?

CodePudding user response:

You can see here that the iterator returns the associated key when calling Next. In the example above it is not needed and is therefore discarded by using the blank identifier, i.e. _, err := it.Next(&task). If you want the key then do not discard it:

for {
    var task Task
    key, err := it.Next(&task)
    if err != nil && err != iterator.Done {
         return err
    } else if err == iterator.Done {
         break
    }
    priorities = append(priorities, task.Priority)
    percents = append(percents, task.PercentComplete)

    // do something with key
}
  • Related