doc.go 6.8 KB

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