GCP Datastore – CRUD

In my team, my role was primarily to create backend server APIs for my team-mates. I wasn’t particularly blessed with an eye for cosmetic details so writing backend APIs is where I could shine the brightest and it very quickly became my responsibility.

Writing backend APIs other than the application’s routing logic, typically involves dealing with storing, fetching and updating data against a datastore or database – also known as CRUD functions. Here is my journey in creating CRUD functions on GCP’s Datastore.

Creating:

Unlike traditional databases, there wasn’t really a need to define a strong structure. GCP’s Datastore is essentially a NoSQL database that allows you to store anything you want with a key as the unique identifier. As you can see below, we ended up storing arrays, strings, dates. It is pretty flexible (but it also means that the application has to have the logic to maintain the consistency of the data)

Writing the code for insert is not too difficult. You are really just using the library provided by google i.e. google datastore library and performing some simple functions.

Fetching:

Fetching looks like this. The query isn’t difficult, and you can filter by id or any attributes. Most of the coding is really mapping the returned values to an object (my design) before return it.

Updating:

Updating on a NoSQL database is really different from a traditional DB. There is no concept of updating 1 value using an SQL statement. You are really fetching the values that already exists in the database and re-entering them as an entire “document”. See the code below, I had to test if it exists and fetch the old values and re-enter the values if they are not changed.

Deleting:

Deleting is really just passing in an id and calling the delete function provided by the datastore library.

And there you go, it’s not complicated to write data on GCP’s datastore. Most of the functionality is provided by the library but there are some quirks that you have to be familiar with. (the update function). I was researching how to update the data like a traditional database, but ended learning that for NoSQL, it’s a document that you have to re-insert.

Leave a comment

Your email address will not be published. Required fields are marked *