google-cloud-datastorekey-value-store

How do I read and write to the google cloud datastore?


The documentation in google cloud's datastore section is very confusing to me.

I was under the belief datastore may be used as a key-value storage. (Similar to mongoDB) But I guess I misunderstood how its keys work, since I can't use string keys outright, but I need to transform series of strings to a (list) key via some list => dataStore.key(list) transformation.

That's weird, and I don't understand why use a list instead of a string, and I don't understand why I don't use the list outright, and need to use datastore.key first, but I can do that. However, after playing with it a little bit, I discovered that the return value of datastore.key(list) would get me different values for the same list if I run it repeatedly!

So, now I need to somehow remember this key somewhere, but the reason I wanted to use datastore was that I was running in a service with no persistent memory to begin with.

Am I using datastore wrong? Can I use it at all for simple persistent key-value storage?


Solution

  • It appears that the issue was that I used a list that was too short.

    The datastore expects collections, which contain documents, each of which is a key-value mapping. So instead of having my key point at a mapping, I needed to set a collection, and in it have keys mapped to mappings. (In other words, I needed to have one more element in the keys list)

      results = await this.dataStore.get(this.dataStore.key([collectionId, documentId]));
    

    AND

      await this.dataStore.save({ key: this.dataStore.key([collectionId, documentId]), data: someKeyValueObject });