| 1 |
--- |
| 2 |
title: "Docstore" |
| 3 |
date: 2019-06-08T15:11:57-04:00 |
| 4 |
lastmod: 2019-07-29T12:00:00-07:00 |
| 5 |
showInSidenav: true |
| 6 |
toc: true |
| 7 |
--- |
| 8 |
|
| 9 |
The [`docstore` package][] provides an abstraction layer over common |
| 10 |
[document stores](https://en.wikipedia.org/wiki/Document-oriented_database) like |
| 11 |
Google Cloud Firestore, Amazon DynamoDB and MongoDB. This guide shows how to |
| 12 |
work with document stores in the Go CDK. |
| 13 |
|
| 14 |
<!--more--> |
| 15 |
|
| 16 |
A document store is a service that stores data in semi-structured JSON-like |
| 17 |
documents grouped into collections. Like other NoSQL databases, document stores |
| 18 |
are schemaless. |
| 19 |
|
| 20 |
The [`docstore` package][] supports operations to add, retrieve, modify and |
| 21 |
delete documents. |
| 22 |
|
| 23 |
Subpackages contain driver implementations of docstore for various services, |
| 24 |
including Cloud and on-prem solutions. You can develop your application |
| 25 |
locally using [`memdocstore`][], then deploy it to multiple Cloud providers with |
| 26 |
minimal initialization reconfiguration. |
| 27 |
|
| 28 |
[`docstore` package]: https://godoc.org/gocloud.dev/docstore |
| 29 |
[`memdocstore`]: https://godoc.org/gocloud.dev/docstore/memdocstore |
| 30 |
|
| 31 |
## Opening a Collection {#opening} |
| 32 |
|
| 33 |
The first step in interacting with a document store is to instantiate |
| 34 |
a portable [`*docstore.Collection`][] for your service. |
| 35 |
|
| 36 |
While every docstore service has the concept of a primary key that uniquely |
| 37 |
distinguishes a document in a collection, each one specifies that key in its own |
| 38 |
way. To be portable, Docstore requires that the key be part of the document's |
| 39 |
contents. When you open a collection using one of the functions described here, |
| 40 |
you specify how to find the provider's primary key in the document. |
| 41 |
|
| 42 |
The easiest way to open a collection is using [`docstore.OpenCollection`][] and |
| 43 |
a service-specific URL pointing to it, making sure you ["blank import"][] |
| 44 |
the driver package to link it in. |
| 45 |
|
| 46 |
```go |
| 47 |
import ( |
| 48 |
"gocloud.dev/docstore" |
| 49 |
_ "gocloud.dev/docstore/<driver>" |
| 50 |
) |
| 51 |
... |
| 52 |
coll, err := docstore.OpenCollection(context.Background(), "<driver-url>") |
| 53 |
if err != nil { |
| 54 |
return fmt.Errorf("could not open collection: %v", err) |
| 55 |
} |
| 56 |
defer coll.Close() |
| 57 |
// coll is a *docstore.Collection; see usage below |
| 58 |
... |
| 59 |
``` |
| 60 |
|
| 61 |
See [Concepts: URLs][] for general background and the [guide below][] for |
| 62 |
URL usage for each supported service. |
| 63 |
|
| 64 |
Alternatively, if you need |
| 65 |
fine-grained control over the connection settings, you can call the constructor |
| 66 |
function in the driver package directly (like `mongodocstore.OpenCollection`). |
| 67 |
|
| 68 |
```go |
| 69 |
import "gocloud.dev/docstore/<driver>" |
| 70 |
... |
| 71 |
coll, err := <driver>.OpenCollection(...) |
| 72 |
... |
| 73 |
``` |
| 74 |
|
| 75 |
You may find the [`wire` package][] useful for managing your initialization code |
| 76 |
when switching between different backing services. |
| 77 |
|
| 78 |
See the [guide below][] for constructor usage for each supported service |
| 79 |
|
| 80 |
[`*docstore.Collection`]: https://godoc.org/gocloud.dev/docstore#Collection |
| 81 |
[`docstore.OpenCollection`]: |
| 82 |
https://godoc.org/gocloud.dev/docstore#OpenCollection |
| 83 |
["blank import"]: https://golang.org/doc/effective_go.html#blank_import |
| 84 |
[Concepts: URLs]: {{< ref "/concepts/urls.md" >}} |
| 85 |
[guide below]: {{< ref "#services" >}} |
| 86 |
[`wire` package]: http://github.com/google/wire |
| 87 |
|
| 88 |
## Using a Collection {#using} |
| 89 |
|
| 90 |
### Representing Documents {#rep-doc} |
| 91 |
|
| 92 |
We'll use a collection with documents represented by this Go struct: |
| 93 |
|
| 94 |
```go |
| 95 |
type Player struct { |
| 96 |
Name string |
| 97 |
Score int |
| 98 |
DocstoreRevision interface{} |
| 99 |
} |
| 100 |
``` |
| 101 |
|
| 102 |
We recommend using structs for documents because they impose some structure on |
| 103 |
your data, but Docstore also accepts `map[string]interface{}` values. See |
| 104 |
[the `docstore` package documentation](https://godoc.org/gocloud.dev/docstore#hdr-Documents) |
| 105 |
for more information. |
| 106 |
|
| 107 |
The `DocstoreRevision` field holds information about the latest revision of the |
| 108 |
document. We discuss it [below]({{< ref "#rev" >}}). |
| 109 |
|
| 110 |
### Actions {#actions} |
| 111 |
|
| 112 |
Once you have [opened a collection]( {{< ref "#opening" >}}), you can call |
| 113 |
action methods on it to read, modify and write documents. You can execute a |
| 114 |
single action, or run multiple actions together in an [_action list_]({{ ref |
| 115 |
"act-list" }}). |
| 116 |
|
| 117 |
Docstore supports six kinds of actions on documents: |
| 118 |
|
| 119 |
- `Get` retrieves a document. |
| 120 |
- `Create` creates a new document. |
| 121 |
- `Replace` replaces an existing document. |
| 122 |
- `Put` puts a document whether or not it already exists. |
| 123 |
- `Update` applies a set of modifications to a document. |
| 124 |
- `Delete` deletes a document. |
| 125 |
|
| 126 |
You can create a single document with the `Collection.Create` method, we will |
| 127 |
use `coll` as the variable holding the collection throughout the guide: |
| 128 |
|
| 129 |
```go |
| 130 |
err := coll.Create(ctx, &Player{Name: "Pat", Score: 10}) |
| 131 |
if err != nil { |
| 132 |
return err |
| 133 |
} |
| 134 |
``` |
| 135 |
|
| 136 |
#### Action Lists {#act-list} |
| 137 |
|
| 138 |
When you use an action list to perform multiple actions at once, drivers can |
| 139 |
optimize action lists by using bulk RPCs, running the actions concurrently, |
| 140 |
or employing a provider's special features to improve efficiency and reduce |
| 141 |
cost. Here we create several documents using an action list. |
| 142 |
|
| 143 |
{{< goexample "gocloud.dev/docstore.ExampleCollection_Actions_bulkWrite" >}} |
| 144 |
|
| 145 |
`ActionList` has a fluent API, so you can build and execute a sequence of |
| 146 |
actions in one line of code. Here we `Put` a document and immediately `Get` its |
| 147 |
new contents. |
| 148 |
|
| 149 |
{{< goexample "gocloud.dev/docstore.ExampleCollection_Actions_getAfterWrite" >}} |
| 150 |
|
| 151 |
If the underlying provider is eventually consistent, the result of the `Get` |
| 152 |
might not reflect the `Put`. Docstore only guarantees that it will perform the |
| 153 |
`Get` after the `Put` completes. |
| 154 |
|
| 155 |
See the documentation for [`docstore.ActionList`][] for the semantics of action |
| 156 |
list execution. |
| 157 |
|
| 158 |
[`docstore.ActionList`]: https://godoc.org/gocloud.dev/docstore#ActionList |
| 159 |
|
| 160 |
#### Updates {#act-update} |
| 161 |
|
| 162 |
Use `Update` to modify individual fields of a document. The `Update` action |
| 163 |
takes a set of modifications to document fields, and applies them all |
| 164 |
atomically. You can change the value of a field, increment it, or delete it. |
| 165 |
|
| 166 |
{{< goexample "gocloud.dev/docstore.ExampleCollection_Update" >}} |
| 167 |
|
| 168 |
### Queries {#queries} |
| 169 |
|
| 170 |
Docstore's `Get` action lets you retrieve a single document by its primary key. |
| 171 |
Queries let you retrieve all documents that match some conditions. You can also |
| 172 |
use queries to delete or update all documents that match the conditions. |
| 173 |
|
| 174 |
#### Getting Documents {#qr-get} |
| 175 |
|
| 176 |
Like [actions]({{< ref "#actions" >}}), queries are built up in a fluent |
| 177 |
style. Just as a `Get` action returns one document, the `Query.Get` method |
| 178 |
returns several documents, in the form of an iterator. |
| 179 |
|
| 180 |
```go |
| 181 |
iter := coll.Query().Where("Score", ">", 20).Get(ctx) |
| 182 |
defer iter.Stop() // Always call Stop on an iterator. |
| 183 |
``` |
| 184 |
|
| 185 |
Repeatedly calling `Next` on the iterator will return all the matching |
| 186 |
documents. Like the `Get` action, `Next` will populate an empty document that |
| 187 |
you pass to it: |
| 188 |
|
| 189 |
```go |
| 190 |
doc := &Player{} |
| 191 |
err := iter.Next(ctx, doc) |
| 192 |
``` |
| 193 |
|
| 194 |
The iteration is over when `Next` returns `io.EOF`. |
| 195 |
|
| 196 |
{{< goexample "gocloud.dev/docstore.ExampleQuery_Get" >}} |
| 197 |
|
| 198 |
You can pass a list of fields to `Get` to reduce the amount of data transmitted. |
| 199 |
|
| 200 |
Queries support the following methods: |
| 201 |
|
| 202 |
- `Where` describes a condition on a document. You can ask whether a field is |
| 203 |
equal to, greater than, or less than a value. The "not equals" comparison |
| 204 |
isn't supported, because it isn't portable across providers. |
| 205 |
- `OrderBy` specifies the order of the resulting documents, by field and |
| 206 |
direction. For portability, you can specify at most one `OrderBy`, and its |
| 207 |
field must also be mentioned in a `Where` clause. |
| 208 |
- `Limit` limits the number of documents in the result. |
| 209 |
|
| 210 |
If a query returns an error, the message may help you fix the problem. Some |
| 211 |
features, like full table scans, have to be enabled via constructor options, |
| 212 |
because they can be expensive. Other queries may require that you manually |
| 213 |
create an index on the collection. |
| 214 |
|
| 215 |
### Revisions {#rev} |
| 216 |
|
| 217 |
Docstore maintains a revision for every document. Whenever the document is |
| 218 |
changed, the revision is too. By default, Docstore stores the revision in a |
| 219 |
field named `DocstoreRevision`, but you can change the field name via an option |
| 220 |
to a `Collection` constructor. |
| 221 |
|
| 222 |
You can use revisions to perform _optimistic locking_, a technique for updating |
| 223 |
a document atomically: |
| 224 |
|
| 225 |
1. `Get` a document. This reads the current revision. |
| 226 |
2. Modify the document contents on the client (but do not change the revision). |
| 227 |
3. `Replace` the document. If the document was changed since it was retrieved |
| 228 |
in step 1, the revision will be different, and Docstore will return an error |
| 229 |
instead of overwriting the document. |
| 230 |
4. If the `Replace` failed, start again from step 1. |
| 231 |
|
| 232 |
{{< goexample "gocloud.dev/docstore.Example_optimisticLocking" >}} |
| 233 |
|
| 234 |
See |
| 235 |
[the Revisions section of the package documentation](https://godoc.org/gocloud.dev/docstore#hdr-Revisions) |
| 236 |
for more on revisions. |
| 237 |
|
| 238 |
## Other Usage Samples |
| 239 |
|
| 240 |
* [CLI Sample](https://github.com/google/go-cloud/tree/master/samples/gocdk-docstore) |
| 241 |
* [Order Processor sample](https://gocloud.dev/tutorials/order/) |
| 242 |
* [docstore package examples](https://godoc.org/gocloud.dev/docstore#pkg-examples) |
| 243 |
|
| 244 |
## Supported Docstore Services {#services} |
| 245 |
|
| 246 |
### Google Cloud Firestore {#firestore} |
| 247 |
|
| 248 |
The [`gcpfirestore`](https://godoc.org/gocloud.dev/docstore/gcpfirestore) |
| 249 |
package supports |
| 250 |
[Google Cloud Firestore](https://cloud.google.com/firestore). Firestore |
| 251 |
documents are uniquely named by paths that are not part of the document content. |
| 252 |
In Docstore, these unique names are represented as part of the document. You |
| 253 |
must supply a way to extract a document's name from its contents. This can be |
| 254 |
done by specifying a document field that holds the name, or by providing a |
| 255 |
function to extract the name from a document. |
| 256 |
|
| 257 |
Firestore URLs provide the project and collection, as well as the field that |
| 258 |
holds the document name. |
| 259 |
|
| 260 |
`docstore.OpenCollection` will use Application Default Credentials; if you have |
| 261 |
authenticated via [`gcloud auth application-default login`][], it will use those credentials. See |
| 262 |
[Application Default Credentials][GCP creds] to learn about authentication |
| 263 |
alternatives, including using environment variables. |
| 264 |
|
| 265 |
[GCP creds]: https://cloud.google.com/docs/authentication/production |
| 266 |
[`gcloud auth application-default login`]: https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login |
| 267 |
|
| 268 |
{{< goexample |
| 269 |
"gocloud.dev/docstore/gcpfirestore.Example_openCollectionFromURL" >}} |
| 270 |
|
| 271 |
Full details about acceptable URLs can be found under the API reference for |
| 272 |
[`gcpfirestore.URLOpener`][]. |
| 273 |
|
| 274 |
[`gcpfirestore.URLOpener`]: https://godoc.org/gocloud.dev/docstore/gcpfirestore#URLOpener |
| 275 |
|
| 276 |
#### Firestore Constructors {#firestore-ctor} |
| 277 |
|
| 278 |
The [`gcpfirestore.OpenCollection`][] constructor opens a Cloud Firestore |
| 279 |
collection as a Docstore collection. You must first connect a Firestore client |
| 280 |
using [`gcpfirestore.Dial`][] or the |
| 281 |
[`cloud.google.com/go/firestore/apiv1`](https://godoc.org/cloud.google.com/go/firestore/apiv1) |
| 282 |
package. In addition to a client, `OpenCollection` requires a Google Cloud |
| 283 |
project ID, the path to the Firestore collection, and the name of the field that |
| 284 |
holds the document name. |
| 285 |
|
| 286 |
{{< goexample "gocloud.dev/docstore/gcpfirestore.ExampleOpenCollection" >}} |
| 287 |
|
| 288 |
Instead of mapping the document name to a field, you can supply a function to |
| 289 |
construct the name from the document contents with |
| 290 |
[`gcpfirestore.OpenCollectionWithNameFunc`][]. This can be useful for documents |
| 291 |
whose name is the combination of two or more fields. |
| 292 |
|
| 293 |
{{< goexample |
| 294 |
"gocloud.dev/docstore/gcpfirestore.ExampleOpenCollectionWithNameFunc" >}} |
| 295 |
|
| 296 |
[`gcpfirestore.Dial`]: https://godoc.org/gocloud.dev/docstore/gcpfirestore#Dial |
| 297 |
[`gcpfirestore.OpenCollection`]: https://godoc.org/gocloud.dev/docstore/gcpfirestore#OpenCollection |
| 298 |
[`gcpfirestore.OpenCollectionWithNameFunc`]: https://godoc.org/gocloud.dev/docstore/gcpfirestore#OpenCollectionWithNameFunc |
| 299 |
|
| 300 |
### Amazon DynamoDB {#dynamodb} |
| 301 |
|
| 302 |
The [`awsdynamodb`](https://godoc.org/gocloud.dev/docstore/awsdynamodb) package |
| 303 |
supports [Amazon DynamoDB](https://aws.amazon.com/dynamodb). A Docstore |
| 304 |
collection corresponds to a DynamoDB table. |
| 305 |
|
| 306 |
DynamoDB URLs provide the table, partition key field and optionally the sort key |
| 307 |
field for the collection. |
| 308 |
|
| 309 |
`docstore.OpenCollection` will create a default AWS Session with the |
| 310 |
`SharedConfigEnable` option enabled; if you have authenticated with the AWS CLI, |
| 311 |
it will use those credentials. See [AWS Session][] to learn about authentication |
| 312 |
alternatives, including using environment variables. |
| 313 |
|
| 314 |
[AWS Session]: https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ |
| 315 |
|
| 316 |
{{< goexample |
| 317 |
"gocloud.dev/docstore/awsdynamodb.Example_openCollectionFromURL" >}} |
| 318 |
|
| 319 |
Full details about acceptable URLs can be found under the API reference for |
| 320 |
[`awsdynamodb.URLOpener`][]. |
| 321 |
|
| 322 |
#### DynamoDB Constructor {#dynamodb-ctor} |
| 323 |
|
| 324 |
The [`awsdynamodb.OpenCollection`][] constructor opens a DynamoDB table as a |
| 325 |
Docstore collection. You must first create an [AWS session][] with the same |
| 326 |
region as your collection: |
| 327 |
|
| 328 |
{{< goexample "gocloud.dev/docstore/awsdynamodb.ExampleOpenCollection" >}} |
| 329 |
|
| 330 |
[AWS session]: https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ |
| 331 |
[`awsdynamodb.OpenCollection`]: https://godoc.org/gocloud.dev/docstore/awsdynamodb#OpenCollection |
| 332 |
[`awsdynamodb.URLOpener`]: https://godoc.org/gocloud.dev/docstore/awsdynamodb#URLOpener |
| 333 |
|
| 334 |
### Azure Cosmos DB {#cosmosdb} |
| 335 |
|
| 336 |
[Azure Cosmos DB][] is compatible with the MongoDB API. You can use the |
| 337 |
[`mongodocstore`][] package to connect to Cosmos DB. You must |
| 338 |
[create an Azure Cosmos account][] and get the MongoDB [connection string][]. |
| 339 |
|
| 340 |
When you use MongoDB URLs to connect to Cosmos DB, specify the Mongo server |
| 341 |
URL by setting the `MONGO_SERVER_URL` environment variable to the connection |
| 342 |
string. See the [MongoDB section][] for more details and examples on how to |
| 343 |
use the package. |
| 344 |
|
| 345 |
[Azure Cosmos DB]: https://docs.microsoft.com/en-us/azure/cosmos-db/ |
| 346 |
[create an Azure Cosmos account]: https://docs.microsoft.com/en-us/azure/cosmos-db/create-mongodb-dotnet |
| 347 |
[connection string]: https://docs.microsoft.com/en-us/azure/cosmos-db/connect-mongodb-account#QuickstartConnection |
| 348 |
[MongoDB section]: {{< ref "#mongo" >}} |
| 349 |
|
| 350 |
#### Cosmos DB Constructors {#cosmosdb-ctor} |
| 351 |
|
| 352 |
The [`mongodocstore.OpenCollection`][] constructor can open a Cosmos DB |
| 353 |
collection. You must first obtain a standard MongoDB Go client with your |
| 354 |
Cosmos connections string. See the [MongoDB constructor section][] for more |
| 355 |
details and examples. |
| 356 |
|
| 357 |
[MongoDB constructor section]: {{< ref "#mongo-ctor" >}} |
| 358 |
|
| 359 |
### MongoDB {#mongo} |
| 360 |
|
| 361 |
The [`mongodocstore`][] package supports the popular |
| 362 |
[MongoDB](https://mongodb.org) document store. MongoDB documents are uniquely |
| 363 |
identified by a field called `_id`. In Docstore, you can choose a different |
| 364 |
name for this field, or provide a function to extract the document ID from a |
| 365 |
document. |
| 366 |
|
| 367 |
MongoDB URLs provide the database and collection, and optionally the field that |
| 368 |
holds the document ID. Specify the Mongo server URL by setting the |
| 369 |
`MONGO_SERVER_URL` environment variable. |
| 370 |
|
| 371 |
{{< goexample |
| 372 |
"gocloud.dev/docstore/mongodocstore.Example_openCollectionFromURL" >}} |
| 373 |
|
| 374 |
Full details about acceptable URLs can be found under the API reference for |
| 375 |
[`mongodocstore.URLOpener`][]. |
| 376 |
|
| 377 |
[`mongodocstore.URLOpener`]: https://godoc.org/gocloud.dev/docstore/mongodocstore#URLOpener |
| 378 |
|
| 379 |
#### MongoDB Constructors {#mongo-ctor} |
| 380 |
|
| 381 |
The [`mongodocstore.OpenCollection`][] constructor opens a MongoDB collection. |
| 382 |
You must first obtain a standard MongoDB Go client using |
| 383 |
[`mongodocstore.Dial`][] or the package |
| 384 |
[`go.mongodb.org/mongo-driver/mongo`](https://godoc.org/go.mongodb.org/mongo-driver/mongo). |
| 385 |
Obtain a `*mongo.Collection` from the client with |
| 386 |
`client.Database(dbName).Collection(collName)`. Then pass the result to |
| 387 |
`mongodocstore.OpenCollection` along with the name of the ID field, or `""` to |
| 388 |
use `_id`. |
| 389 |
|
| 390 |
{{< goexample "gocloud.dev/docstore/mongodocstore.ExampleOpenCollection" >}} |
| 391 |
|
| 392 |
Instead of mapping the document ID to a field, you can supply a function to |
| 393 |
construct the ID from the document contents with |
| 394 |
[`mongodocstore.OpenCollectionWithIDFunc`][]. This can be useful for documents |
| 395 |
whose name is the combination of two or more fields. |
| 396 |
|
| 397 |
{{< goexample |
| 398 |
"gocloud.dev/docstore/mongodocstore.ExampleOpenCollectionWithIDFunc" >}} |
| 399 |
|
| 400 |
[`mongodocstore`]: https://godoc.org/gocloud.dev/docstore/mongodocstore |
| 401 |
[`mongodocstore.Dial`]: https://godoc.org/gocloud.dev/docstore/mongodocstore#Dial |
| 402 |
[`mongodocstore.OpenCollection`]: https://godoc.org/gocloud.dev/docstore/mongodocstore#OpenCollection |
| 403 |
[`mongodocstore.OpenCollectionWithIDFunc`]: https://godoc.org/gocloud.dev/docstore/mongodocstore#OpenCollectionWithIDFunc |
| 404 |
|
| 405 |
### In-Memory Document Store {#mem} |
| 406 |
|
| 407 |
The [`memdocstore`](https://godoc.org/gocloud.dev/docstore/memdocstore) |
| 408 |
package implements an in-memory document store suitable for testing and |
| 409 |
development. |
| 410 |
|
| 411 |
URLs for the in-memory store have a `mem:` scheme. The URL host is used as the |
| 412 |
the collection name, and the URL path is used as the name of the document field |
| 413 |
to use as a primary key. |
| 414 |
|
| 415 |
{{< goexample |
| 416 |
"gocloud.dev/docstore/memdocstore.Example_openCollectionFromURL" >}} |
| 417 |
|
| 418 |
Full details about acceptable URLs can be found under the API reference for |
| 419 |
[`memdocstore.URLOpener`][]. |
| 420 |
|
| 421 |
[`memdocstore.URLOpener`]: https://godoc.org/gocloud.dev/docstore/memdocstore#URLOpener |
| 422 |
|
| 423 |
#### Mem Constructors {#mem-ctor} |
| 424 |
|
| 425 |
The [`memdocstore.OpenCollection`][] constructor creates and opens a collection, |
| 426 |
taking the name of the key field. |
| 427 |
|
| 428 |
{{< goexample "gocloud.dev/docstore/memdocstore.ExampleOpenCollection" >}} |
| 429 |
|
| 430 |
You can instead supply a function to construct the primary key from the document |
| 431 |
contents with [`memdocstore.OpenCollectionWithKeyFunc`][]. This can be useful |
| 432 |
for documents whose name is the combination of two or more fields. |
| 433 |
|
| 434 |
{{< goexample |
| 435 |
"gocloud.dev/docstore/memdocstore.ExampleOpenCollectionWithKeyFunc" >}} |
| 436 |
|
| 437 |
[`memdocstore.OpenCollection`]: https://godoc.org/gocloud.dev/docstore/memdocstore#OpenCollection |
| 438 |
[`memdocstore.OpenCollectionWithKeyFunc`]: https://godoc.org/gocloud.dev/docstore/memdocstore#OpenCollectionWithKeyFunc |