You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

231 lines
6.9 KiB

  1. // Copyright 2017 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // DO NOT EDIT doc.go. Modify internal/doc.template, then run make -C internal.
  15. /*
  16. Package firestore provides a client for reading and writing to a Cloud Firestore
  17. database.
  18. NOTE: This package is in beta. It is not stable, and may be subject to changes.
  19. See https://cloud.google.com/firestore/docs for an introduction
  20. to Cloud Firestore and additional help on using the Firestore API.
  21. See https://godoc.org/cloud.google.com/go for authentication, timeouts,
  22. connection pooling and similar aspects of this package.
  23. Note: you can't use both Cloud Firestore and Cloud Datastore in the same
  24. project.
  25. Creating a Client
  26. To start working with this package, create a client with a project ID:
  27. ctx := context.Background()
  28. client, err := firestore.NewClient(ctx, "projectID")
  29. if err != nil {
  30. // TODO: Handle error.
  31. }
  32. CollectionRefs and DocumentRefs
  33. In Firestore, documents are sets of key-value pairs, and collections are groups of
  34. documents. A Firestore database consists of a hierarchy of alternating collections
  35. and documents, referred to by slash-separated paths like
  36. "States/California/Cities/SanFrancisco".
  37. This client is built around references to collections and documents. CollectionRefs
  38. and DocumentRefs are lightweight values that refer to the corresponding database
  39. entities. Creating a ref does not involve any network traffic.
  40. states := client.Collection("States")
  41. ny := states.Doc("NewYork")
  42. // Or, in a single call:
  43. ny = client.Doc("States/NewYork")
  44. Reading
  45. Use DocumentRef.Get to read a document. The result is a DocumentSnapshot.
  46. Call its Data method to obtain the entire document contents as a map.
  47. docsnap, err := ny.Get(ctx)
  48. if err != nil {
  49. // TODO: Handle error.
  50. }
  51. dataMap := docsnap.Data()
  52. fmt.Println(dataMap)
  53. You can also obtain a single field with DataAt, or extract the data into a struct
  54. with DataTo. With the type definition
  55. type State struct {
  56. Capital string `firestore:"capital"`
  57. Population float64 `firestore:"pop"` // in millions
  58. }
  59. we can extract the document's data into a value of type State:
  60. var nyData State
  61. if err := docsnap.DataTo(&nyData); err != nil {
  62. // TODO: Handle error.
  63. }
  64. Note that this client supports struct tags beginning with "firestore:" that work like
  65. the tags of the encoding/json package, letting you rename fields, ignore them, or
  66. omit their values when empty.
  67. To retrieve multiple documents from their references in a single call, use
  68. Client.GetAll.
  69. docsnaps, err := client.GetAll(ctx, []*firestore.DocumentRef{
  70. states.Doc("Wisconsin"), states.Doc("Ohio"),
  71. })
  72. if err != nil {
  73. // TODO: Handle error.
  74. }
  75. for _, ds := range docsnaps {
  76. _ = ds // TODO: Use ds.
  77. }
  78. Writing
  79. For writing individual documents, use the methods on DocumentReference.
  80. Create creates a new document.
  81. wr, err := ny.Create(ctx, State{
  82. Capital: "Albany",
  83. Population: 19.8,
  84. })
  85. if err != nil {
  86. // TODO: Handle error.
  87. }
  88. fmt.Println(wr)
  89. The first return value is a WriteResult, which contains the time
  90. at which the document was updated.
  91. Create fails if the document exists. Another method, Set, either replaces an existing
  92. document or creates a new one.
  93. ca := states.Doc("California")
  94. _, err = ca.Set(ctx, State{
  95. Capital: "Sacramento",
  96. Population: 39.14,
  97. })
  98. To update some fields of an existing document, use Update. It takes a list of
  99. paths to update and their corresponding values.
  100. _, err = ca.Update(ctx, []firestore.Update{{Path: "capital", Value: "Sacramento"}})
  101. Use DocumentRef.Delete to delete a document.
  102. _, err = ny.Delete(ctx)
  103. Preconditions
  104. You can condition Deletes or Updates on when a document was last changed. Specify
  105. these preconditions as an option to a Delete or Update method. The check and the
  106. write happen atomically with a single RPC.
  107. docsnap, err = ca.Get(ctx)
  108. if err != nil {
  109. // TODO: Handle error.
  110. }
  111. _, err = ca.Update(ctx,
  112. []firestore.Update{{Path: "capital", Value: "Sacramento"}},
  113. firestore.LastUpdateTime(docsnap.UpdateTime))
  114. Here we update a doc only if it hasn't changed since we read it.
  115. You could also do this with a transaction.
  116. To perform multiple writes at once, use a WriteBatch. Its methods chain
  117. for convenience.
  118. WriteBatch.Commit sends the collected writes to the server, where they happen
  119. atomically.
  120. writeResults, err := client.Batch().
  121. Create(ny, State{Capital: "Albany"}).
  122. Update(ca, []firestore.Update{{Path: "capital", Value: "Sacramento"}}).
  123. Delete(client.Doc("States/WestDakota")).
  124. Commit(ctx)
  125. Queries
  126. You can use SQL to select documents from a collection. Begin with the collection, and
  127. build up a query using Select, Where and other methods of Query.
  128. q := states.Where("pop", ">", 10).OrderBy("pop", firestore.Desc)
  129. Supported operators include `<`, `<=`, `>`, `>=`, `==`, and 'array-contains'.
  130. Call the Query's Documents method to get an iterator, and use it like
  131. the other Google Cloud Client iterators.
  132. iter := q.Documents(ctx)
  133. defer iter.Stop()
  134. for {
  135. doc, err := iter.Next()
  136. if err == iterator.Done {
  137. break
  138. }
  139. if err != nil {
  140. // TODO: Handle error.
  141. }
  142. fmt.Println(doc.Data())
  143. }
  144. To get all the documents in a collection, you can use the collection itself
  145. as a query.
  146. iter = client.Collection("States").Documents(ctx)
  147. Transactions
  148. Use a transaction to execute reads and writes atomically. All reads must happen
  149. before any writes. Transaction creation, commit, rollback and retry are handled for
  150. you by the Client.RunTransaction method; just provide a function and use the
  151. read and write methods of the Transaction passed to it.
  152. ny := client.Doc("States/NewYork")
  153. err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
  154. doc, err := tx.Get(ny) // tx.Get, NOT ny.Get!
  155. if err != nil {
  156. return err
  157. }
  158. pop, err := doc.DataAt("pop")
  159. if err != nil {
  160. return err
  161. }
  162. return tx.Update(ny, []firestore.Update{{Path: "pop", Value: pop.(float64) + 0.2}})
  163. })
  164. if err != nil {
  165. // TODO: Handle error.
  166. }
  167. Google Cloud Firestore Emulator
  168. This package supports the Cloud Firestore emulator, which is useful for testing and
  169. development. Environment variables are used to indicate that Firestore traffic should be
  170. directed to the emulator instead of the production Firestore service.
  171. To install and run the emulator and its environment variables, see the documentation
  172. at https://cloud.google.com/sdk/gcloud/reference/beta/emulators/firestore/. Once the
  173. emulator is running, set FIRESTORE_EMULATOR_HOST to the API endpoint.
  174. */
  175. package firestore