Package firestore provides a client for reading and writing to a Cloud Firestore database.
See https://cloud.google.com/firestore/docs for an introduction to Cloud Firestore and additional help on using the Firestore API.
See https://godoc.org/cloud.google.com/go for authentication, timeouts, connection pooling and similar aspects of this package.
Note: you can't use both Cloud Firestore and Cloud Datastore in the same project.
Creating a Client
To start working with this package, create a client with a project ID:
ctx := context.Background() client, err := firestore.NewClient(ctx, "projectID") if err != nil { // TODO: Handle error. }
CollectionRefs and DocumentRefs
In Firestore, documents are sets of key-value pairs, and collections are groups of documents. A Firestore database consists of a hierarchy of alternating collections and documents, referred to by slash-separated paths like "States/California/Cities/SanFrancisco".
This client is built around references to collections and documents. CollectionRefs and DocumentRefs are lightweight values that refer to the corresponding database entities. Creating a ref does not involve any network traffic.
states := client.Collection("States") ny := states.Doc("NewYork") // Or, in a single call: ny = client.Doc("States/NewYork")
Reading
Use DocumentRef.Get to read a document. The result is a DocumentSnapshot. Call its Data method to obtain the entire document contents as a map.
docsnap, err := ny.Get(ctx) if err != nil { // TODO: Handle error. } dataMap := docsnap.Data() fmt.Println(dataMap)
You can also obtain a single field with DataAt, or extract the data into a struct with DataTo. With the type definition
type State struct { Capital string `firestore:"capital"` Population float64 `firestore:"pop"` // in millions }
we can extract the document's data into a value of type State:
var nyData State if err := docsnap.DataTo(&nyData); err != nil { // TODO: Handle error. }
Note that this client supports struct tags beginning with "firestore:" that work like the tags of the encoding/json package, letting you rename fields, ignore them, or omit their values when empty.
To retrieve multiple documents from their references in a single call, use Client.GetAll.
docsnaps, err := client.GetAll(ctx, []*firestore.DocumentRef{ states.Doc("Wisconsin"), states.Doc("Ohio"), }) if err != nil { // TODO: Handle error. } for _, ds := range docsnaps { _ = ds // TODO: Use ds. }
Writing
For writing individual documents, use the methods on DocumentReference. Create creates a new document.
wr, err := ny.Create(ctx, State{ Capital: "Albany", Population: 19.8, }) if err != nil { // TODO: Handle error. } fmt.Println(wr)
The first return value is a WriteResult, which contains the time at which the document was updated.
Create fails if the document exists. Another method, Set, either replaces an existing document or creates a new one.
ca := states.Doc("California") _, err = ca.Set(ctx, State{ Capital: "Sacramento", Population: 39.14, })
To update some fields of an existing document, use Update. It takes a list of paths to update and their corresponding values.
_, err = ca.Update(ctx, []firestore.Update{{Path: "capital", Value: "Sacramento"}})
Use DocumentRef.Delete to delete a document.
_, err = ny.Delete(ctx)
Preconditions
You can condition Deletes or Updates on when a document was last changed. Specify these preconditions as an option to a Delete or Update method. The check and the write happen atomically with a single RPC.
docsnap, err = ca.Get(ctx) if err != nil { // TODO: Handle error. } _, err = ca.Update(ctx, []firestore.Update{{Path: "capital", Value: "Sacramento"}}, firestore.LastUpdateTime(docsnap.UpdateTime))
Here we update a doc only if it hasn't changed since we read it. You could also do this with a transaction.
To perform multiple writes at once, use a WriteBatch. Its methods chain for convenience.
WriteBatch.Commit sends the collected writes to the server, where they happen atomically.
writeResults, err := client.Batch(). Create(ny, State{Capital: "Albany"}). Update(ca, []firestore.Update{{Path: "capital", Value: "Sacramento"}}). Delete(client.Doc("States/WestDakota")). Commit(ctx)
Queries
You can use SQL to select documents from a collection. Begin with the collection, and build up a query using Select, Where and other methods of Query.
q := states.Where("pop", ">", 10).OrderBy("pop", firestore.Desc)
Supported operators include '<', '<=', '>', '>=', '==', 'in', 'array-contains', and 'array-contains-any'.
Call the Query's Documents method to get an iterator, and use it like the other Google Cloud Client iterators.
iter := q.Documents(ctx) defer iter.Stop() for { doc, err := iter.Next() if err == iterator.Done { break } if err != nil { // TODO: Handle error. } fmt.Println(doc.Data()) }
To get all the documents in a collection, you can use the collection itself as a query.
iter = client.Collection("States").Documents(ctx)
Firestore supports similarity search over embedding vectors. See Query.FindNearest for details.
Collection Group Partition Queries
You can partition the documents of a Collection Group allowing for smaller subqueries.
collectionGroup = client.CollectionGroup("States") partitions, err = collectionGroup.GetPartitionedQueries(ctx, 20)
You can also Serialize/Deserialize queries making it possible to run/stream the queries elsewhere; another process or machine for instance.
queryProtos := make([][]byte, 0) for _, query := range partitions { protoBytes, err := query.Serialize() // handle err queryProtos = append(queryProtos, protoBytes) ... } for _, protoBytes := range queryProtos { query, err := client.CollectionGroup("").Deserialize(protoBytes) ... }
Transactions
Use a transaction to execute reads and writes atomically. All reads must happen before any writes. Transaction creation, commit, rollback and retry are handled for you by the Client.RunTransaction method; just provide a function and use the read and write methods of the Transaction passed to it.
ny := client.Doc("States/NewYork") err := client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error { doc, err := tx.Get(ny) // tx.Get, NOT ny.Get! if err != nil { return err } pop, err := doc.DataAt("pop") if err != nil { return err } return tx.Update(ny, []firestore.Update{{Path: "pop", Value: pop.(float64) + 0.2}}) }) if err != nil { // TODO: Handle error. }
Google Cloud Firestore Emulator
This package supports the Cloud Firestore emulator, which is useful for testing and development. Environment variables are used to indicate that Firestore traffic should be directed to the emulator instead of the production Firestore service.
To install and run the emulator and its environment variables, see the documentation at https://cloud.google.com/sdk/gcloud/reference/beta/emulators/firestore/. Once the emulator is running, set FIRESTORE_EMULATOR_HOST to the API endpoint.
// Set FIRESTORE_EMULATOR_HOST environment variable. err := os.Setenv("FIRESTORE_EMULATOR_HOST", "localhost:9000") if err != nil { // TODO: Handle error. } // Create client as usual. client, err := firestore.NewClient(ctx, "my-project-id") if err != nil { // TODO: Handle error. } defer client.Close()
Constants
Delete, ServerTimestamp
const (
// Delete is used as a value in a call to Update or Set with merge to indicate
// that the corresponding key should be deleted.
Delete sentinel = iota
// ServerTimestamp is used as a value in a call to Update to indicate that the
// key's value should be set to the time at which the server processed
// the request.
//
// ServerTimestamp must be the value of a field directly; it cannot appear in
// array or struct values, or in any value that is itself inside an array or
// struct.
ServerTimestamp
)DefaultDatabaseID
const DefaultDatabaseID = "(default)"DefaultDatabaseID is name of the default database
DefaultTransactionMaxAttempts
const DefaultTransactionMaxAttempts = 5DefaultTransactionMaxAttempts is the default number of times to attempt a transaction.
DetectProjectID
const DetectProjectID = detect.ProjectIDSentinelDetectProjectID is a sentinel value that instructs NewClient to detect the project ID. It is given in place of the projectID argument. NewClient will use the project ID from the given credentials or the default credentials (https://developers.google.com/accounts/docs/application-default-credentials) if no credentials were provided. When providing credentials, not all options will allow NewClient to extract the project ID. Specifically a JWT does not have the project ID encoded.
DocumentID
const DocumentID = "__name__"DocumentID is the special field name representing the ID of a document in queries.
Variables
LogWatchStreams
var LogWatchStreams = falseLogWatchStreams controls whether watch stream status changes are logged. This feature is EXPERIMENTAL and may disappear at any time.
ReadOnly
var ReadOnly = ro{}ReadOnly is a TransactionOption that makes the transaction read-only. Read-only transactions cannot issue write operations, but are more efficient.
Functions
func ArrayRemove
func ArrayRemove(elems ...interface{}) arrayRemoveArrayRemove specifies elements to be removed from whatever array already exists in the server.
If a value exists and it's an array, values are removed from it. All duplicate values are removed. If a value exists and it's not an array, the value is replaced by an empty array. If a value does not exist, an empty array is created.
ArrayRemove must be the value of a field directly; it cannot appear in array or struct values, or in any value that is itself inside an array or struct.
Example
update
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
co := client.Doc("States/Colorado")
wr, err := co.Update(ctx, []firestore.Update{
{Path: "cities", Value: firestore.ArrayRemove("Denver")},
})
if err != nil {
// TODO: Handle error.
}
fmt.Println(wr.UpdateTime)
}
func ArrayUnion
func ArrayUnion(elems ...interface{}) arrayUnionArrayUnion specifies elements to be added to whatever array already exists in the server, or to create an array if no value exists.
If a value exists and it's an array, values are appended to it. Any duplicate value is ignored. If a value exists and it's not an array, the value is replaced by an array of the values in the ArrayUnion. If a value does not exist, an array of the values in the ArrayUnion is created.
ArrayUnion must be the value of a field directly; it cannot appear in array or struct values, or in any value that is itself inside an array or struct.
Examples
create
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
wr, err := client.Doc("States/Colorado").Create(ctx, map[string]interface{}{
"cities": firestore.ArrayUnion("Denver", "Golden", "Boulder"),
"pop": 5.5,
})
if err != nil {
// TODO: Handle error.
}
fmt.Println(wr.UpdateTime)
}
update
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
co := client.Doc("States/Colorado")
wr, err := co.Update(ctx, []firestore.Update{
{Path: "cities", Value: firestore.ArrayUnion("Broomfield")},
})
if err != nil {
// TODO: Handle error.
}
fmt.Println(wr.UpdateTime)
}
func FieldTransformIncrement
func FieldTransformIncrement(n interface{}) transformFieldTransformIncrement returns a special value that can be used with Set, Create, or Update that tells the server to transform the field's current value by the given value.
The supported values are:
int, int8, int16, int32, int64
uint8, uint16, uint32
float32, float64
If the field does not yet exist, the transformation will set the field to the given value.
func FieldTransformMaximum
func FieldTransformMaximum(n interface{}) transformFieldTransformMaximum returns a special value that can be used with Set, Create, or Update that tells the server to set the field to the maximum of the field's current value and the given value.
The supported values are:
int, int8, int16, int32, int64
uint8, uint16, uint32
float32, float64
If the field is not an integer or double, or if the field does not yet exist, the transformation will set the field to the given value. If a maximum operation is applied where the field and the input value are of mixed types (that is - one is an integer and one is a double) the field takes on the type of the larger operand. If the operands are equivalent (e.g. 3 and 3.0), the field does not change. 0, 0.0, and -0.0 are all zero. The maximum of a zero stored value and zero input value is always the stored value. The maximum of any numeric value x and NaN is NaN.
func FieldTransformMinimum
func FieldTransformMinimum(n interface{}) transformFieldTransformMinimum returns a special value that can be used with Set, Create, or Update that tells the server to set the field to the minimum of the field's current value and the given value.
The supported values are:
int, int8, int16, int32, int64
uint8, uint16, uint32
float32, float64
If the field is not an integer or double, or if the field does not yet exist, the transformation will set the field to the given value. If a minimum operation is applied where the field and the input value are of mixed types (that is - one is an integer and one is a double) the field takes on the type of the smaller operand. If the operands are equivalent (e.g. 3 and 3.0), the field does not change. 0, 0.0, and -0.0 are all zero. The minimum of a zero stored value and zero input value is always the stored value. The minimum of any numeric value x and NaN is NaN.
func Increment
func Increment(n interface{}) transformIncrement is an alias for FieldTransformIncrement.
Examples
create
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
wr, err := client.Doc("States/Colorado").Create(ctx, map[string]interface{}{
"cities": []string{"Denver", "Golden", "Boulder"},
"pop": firestore.Increment(7), // "pop" will be set to 7.
})
if err != nil {
// TODO: Handle error.
}
fmt.Println(wr.UpdateTime)
}
update
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
co := client.Doc("States/Colorado")
wr, err := co.Update(ctx, []firestore.Update{
{Path: "pop", Value: firestore.Increment(7)}, // "pop" will incremented by 7.
})
if err != nil {
// TODO: Handle error.
}
fmt.Println(wr.UpdateTime)
}
func MaxAttempts
func MaxAttempts(n int) maxAttemptsMaxAttempts is a TransactionOption that configures the maximum number of times to try a transaction. In defaults to DefaultTransactionMaxAttempts.
func Ptr
Ptr returns a pointer to its argument. It can be used to initialize pointer fields:
findNearestOptions.DistanceThreshold = firestore.Ptr[float64](0.1)
func WithCommitResponseTo
func WithCommitResponseTo(r *CommitResponse) commitResponseWithCommitResponseTo returns a TransactionOption that specifies where the CommitResponse should be written on successful commit. Nothing is written on a failed commit.
AggregateFunction
type AggregateFunction interface {
As(alias string) *AliasedAggregate
// contains filtered or unexported methods
}AggregateFunction represents an aggregation function in a pipeline.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Average
func Average(fieldOrExpr any) AggregateFunctionAverage creates an aggregation that calculates the average (mean) of values from an expression or a field's values across multiple stage inputs. fieldOrExpr can be a field path string, [FieldPath] or [Expression] Example:
// Calculate the average age of users
Average(FieldOf("info.age")).As("averageAge") // FieldOf returns Expr
Average(FieldOfPath("info.age")).As("averageAge") // FieldOfPath returns Expr
Average("info.age").As("averageAge") // String implicitly becomes FieldOf(...).As(...)
Average(FieldPath([]string{"info", "age"})).As("averageAge")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Count
func Count(fieldOrExpr any) AggregateFunctionCount creates an aggregation that counts the number of stage inputs with valid evaluations of the provided field or expression. fieldOrExpr can be a field path string, [FieldPath] or [Expression] Example:
// Count the number of items where the price is greater than 10
Count(FieldOf("price").Gt(10)).As("expensiveItemCount") // FieldOf("price").Gt(10) is a BooleanExpr
// Count the total number of products
Count("productId").As("totalProducts") // String implicitly becomes FieldOf(...).As(...)
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func CountAll
func CountAll() AggregateFunctionCountAll creates an aggregation that counts the total number of stage inputs.
Example:
// Count the total number of users
CountAll().As("totalUsers")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func CountDistinct
func CountDistinct(fieldOrExpr any) AggregateFunctionCountDistinct creates an aggregation that counts the number of distinct values of the provided field or expression. fieldOrExpr can be a field path string, [FieldPath] or [Expression] Example:
// CountDistinct the number of distinct items where the price is greater than 10
CountDistinct(FieldOf("price").Gt(10)).As("expensiveItemCount") // FieldOf("price").Gt(10) is a BooleanExpr
// CountDistinct the total number of distinct products
CountDistinct("productId").As("totalProducts") // String implicitly becomes FieldOf(...).As(...)
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func CountIf
func CountIf(condition BooleanExpression) AggregateFunctionCountIf creates an aggregation that counts the number of stage inputs where the provided boolean expression evaluates to true. Example:
CountIf(FieldOf("published").Equal(true)).As("publishedCount")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Maximum
func Maximum(fieldOrExpr any) AggregateFunctionMaximum creates an aggregation that calculates the maximum of values from an expression or a field's values across multiple stage inputs.
Example:
// Find the highest order amount
Maximum(FieldOf("orderAmount")).As("maxOrderAmount") // FieldOf returns Expr
Maximum("orderAmount").As("maxOrderAmount") // String implicitly becomes FieldOf(...).As(...)
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Minimum
func Minimum(fieldOrExpr any) AggregateFunctionMinimum creates an aggregation that calculates the minimum of values from an expression or a field's values across multiple stage inputs.
Example:
// Find the lowest order amount
Minimum(FieldOf("orderAmount")).As("minOrderAmount") // FieldOf returns Expr
Minimum("orderAmount").As("minOrderAmount") // String implicitly becomes FieldOf(...).As(...)
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Sum
func Sum(fieldOrExpr any) AggregateFunctionSum creates an aggregation that calculates the sum of values from an expression or a field's values across multiple stage inputs.
Example:
// Calculate the total revenue from a set of orders
Sum(FieldOf("orderAmount")).As("totalRevenue") // FieldOf returns Expr
Sum("orderAmount").As("totalRevenue") // String implicitly becomes FieldOf(...).As(...)
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
AggregateSpec
type AggregateSpec struct {
// contains filtered or unexported fields
}AggregateSpec is used to perform aggregation operations.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func NewAggregateSpec
func NewAggregateSpec(accumulators ...*AliasedAggregate) *AggregateSpecNewAggregateSpec creates a new AggregateSpec with the given accumulator targets.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*AggregateSpec) WithGroups
func (a *AggregateSpec) WithGroups(fieldpathsOrSelectables any) *AggregateSpecWithGroups sets the grouping keys for the aggregation.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
AggregationQuery
type AggregationQuery struct {
// contains filtered or unexported fields
}AggregationQuery allows for generating aggregation results of an underlying basic query. A single AggregationQuery can contain multiple aggregations.
func (*AggregationQuery) Get
func (a *AggregationQuery) Get(ctx context.Context) (AggregationResult, error)Get retrieves the aggregation query results from the service.
func (*AggregationQuery) GetResponse
func (a *AggregationQuery) GetResponse(ctx context.Context) (aro *AggregationResponse, err error)GetResponse runs the aggregation with the options provided in the query
func (*AggregationQuery) Pipeline
func (aq *AggregationQuery) Pipeline() *PipelinePipeline creates a new [Pipeline] from the aggregation query. All of the operations of the underlying query will be converted to pipeline stages, and an aggregate stage will be added for the aggregations.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*AggregationQuery) Transaction
func (a *AggregationQuery) Transaction(tx *Transaction) *AggregationQueryTransaction specifies that aggregation query should run within provided transaction
func (*AggregationQuery) WithAvg
func (a *AggregationQuery) WithAvg(path string, alias string) *AggregationQueryWithAvg specifies that the aggregation query should provide an average of the values of the provided field in the results returned by the underlying Query. The alias argument can be empty or a valid Firestore document field name. It can be used as key in the AggregationResult to get the average value. If alias is empty, Firestore will autogenerate a key.
func (*AggregationQuery) WithAvgPath
func (a *AggregationQuery) WithAvgPath(fp FieldPath, alias string) *AggregationQueryWithAvgPath specifies that the aggregation query should provide an average of the values of the provided field in the results returned by the underlying Query. The path argument can be a single field or a dot-separated sequence of fields, and must not contain any of the runes "˜*/[]". The alias argument can be empty or a valid Firestore document field name. It can be used as key in the AggregationResult to get the average value. If alias is empty, Firestore will autogenerate a key.
func (*AggregationQuery) WithCount
func (a *AggregationQuery) WithCount(alias string) *AggregationQueryWithCount specifies that the aggregation query provide a count of results returned by the underlying Query.
func (*AggregationQuery) WithSum
func (a *AggregationQuery) WithSum(path string, alias string) *AggregationQueryWithSum specifies that the aggregation query should provide a sum of the values of the provided field in the results returned by the underlying Query. The alias argument can be empty or a valid Firestore document field name. It can be used as key in the AggregationResult to get the sum value. If alias is empty, Firestore will autogenerate a key.
func (*AggregationQuery) WithSumPath
func (a *AggregationQuery) WithSumPath(fp FieldPath, alias string) *AggregationQueryWithSumPath specifies that the aggregation query should provide a sum of the values of the provided field in the results returned by the underlying Query. The path argument can be a single field or a dot-separated sequence of fields, and must not contain any of the runes "˜*/[]". The alias argument can be empty or a valid Firestore document field name. It can be used as key in the AggregationResult to get the sum value. If alias is empty, Firestore will autogenerate a key.
AggregationResponse
type AggregationResponse struct {
Result AggregationResult
// Query explain metrics. This is only present when ExplainOptions is provided.
ExplainMetrics *ExplainMetrics
}AggregationResponse contains AggregationResult and response from the run options in the query
AggregationResult
type AggregationResult map[string]interface{}AggregationResult contains the results of an aggregation query.
AliasedAggregate
type AliasedAggregate struct {
// contains filtered or unexported fields
}AliasedAggregate is an aliased [AggregateFunction]. It's used to give a name to the result of an aggregation.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (AliasedAggregate) As
func (b AliasedAggregate) As(alias string) *AliasedAggregateAliasedExpression
type AliasedExpression struct {
// contains filtered or unexported fields
}AliasedExpression represents an expression with an alias.
It implements the [Selectable] interface, allowing it to be used in projection stages like Select and AddFields.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (AliasedExpression) Abs
func (b AliasedExpression) Abs() Expressionfunc (AliasedExpression) Add
func (b AliasedExpression) Add(other any) ExpressionAritmetic functions
func (AliasedExpression) ArrayConcat
func (b AliasedExpression) ArrayConcat(otherArrays any) Expressionfunc (AliasedExpression) ArrayContains
func (b AliasedExpression) ArrayContains(value any) BooleanExpressionArray functions
func (AliasedExpression) ArrayContainsAll
func (b AliasedExpression) ArrayContainsAll(values any) BooleanExpressionfunc (AliasedExpression) ArrayContainsAny
func (b AliasedExpression) ArrayContainsAny(values any) BooleanExpressionfunc (AliasedExpression) ArrayGet
func (b AliasedExpression) ArrayGet(offset any) Expressionfunc (AliasedExpression) ArrayLength
func (b AliasedExpression) ArrayLength() Expressionfunc (AliasedExpression) ArrayMaximum
func (b AliasedExpression) ArrayMaximum() Expressionfunc (AliasedExpression) ArrayMinimum
func (b AliasedExpression) ArrayMinimum() Expressionfunc (AliasedExpression) ArrayReverse
func (b AliasedExpression) ArrayReverse() Expressionfunc (AliasedExpression) ArraySum
func (b AliasedExpression) ArraySum() Expressionfunc (AliasedExpression) As
func (b AliasedExpression) As(alias string) Selectablefunc (AliasedExpression) Ascending
func (b AliasedExpression) Ascending() OrderingOrdering
func (AliasedExpression) Average
func (b AliasedExpression) Average() AggregateFunctionfunc (AliasedExpression) ByteLength
func (b AliasedExpression) ByteLength() ExpressionString functions
func (AliasedExpression) Ceil
func (b AliasedExpression) Ceil() Expressionfunc (AliasedExpression) CharLength
func (b AliasedExpression) CharLength() Expressionfunc (AliasedExpression) Concat
func (b AliasedExpression) Concat(others any) Expressionfunc (AliasedExpression) CosineDistance
func (b AliasedExpression) CosineDistance(other any) ExpressionVector functions
func (AliasedExpression) Count
func (b AliasedExpression) Count() AggregateFunctionfunc (AliasedExpression) CountDistinct
func (b AliasedExpression) CountDistinct() AggregateFunctionfunc (AliasedExpression) Descending
func (b AliasedExpression) Descending() Orderingfunc (AliasedExpression) Divide
func (b AliasedExpression) Divide(other any) Expressionfunc (AliasedExpression) DotProduct
func (b AliasedExpression) DotProduct(other any) Expressionfunc (AliasedExpression) EndsWith
func (b AliasedExpression) EndsWith(suffix any) BooleanExpressionfunc (AliasedExpression) Equal
func (b AliasedExpression) Equal(other any) BooleanExpressionComparison functions
func (AliasedExpression) EqualAny
func (b AliasedExpression) EqualAny(values any) BooleanExpressionfunc (AliasedExpression) EuclideanDistance
func (b AliasedExpression) EuclideanDistance(other any) Expressionfunc (AliasedExpression) Exp
func (b AliasedExpression) Exp() Expressionfunc (AliasedExpression) Floor
func (b AliasedExpression) Floor() Expressionfunc (AliasedExpression) GetCollectionID
func (b AliasedExpression) GetCollectionID() ExpressionKey functions
func (AliasedExpression) GetDocumentID
func (b AliasedExpression) GetDocumentID() Expressionfunc (AliasedExpression) GreaterThan
func (b AliasedExpression) GreaterThan(other any) BooleanExpressionfunc (AliasedExpression) GreaterThanOrEqual
func (b AliasedExpression) GreaterThanOrEqual(other any) BooleanExpressionfunc (AliasedExpression) IfAbsent
func (b AliasedExpression) IfAbsent(catchExprOrValue any) Expressionfunc (AliasedExpression) IfError
func (b AliasedExpression) IfError(catchExprOrValue any) ExpressionLogical functions
func (AliasedExpression) Join
func (b AliasedExpression) Join(delimiter any) Expressionfunc (AliasedExpression) Length
func (b AliasedExpression) Length() ExpressionGeneral functions
func (AliasedExpression) LessThan
func (b AliasedExpression) LessThan(other any) BooleanExpressionfunc (AliasedExpression) LessThanOrEqual
func (b AliasedExpression) LessThanOrEqual(other any) BooleanExpressionfunc (AliasedExpression) Like
func (b AliasedExpression) Like(suffix any) BooleanExpressionfunc (AliasedExpression) Ln
func (b AliasedExpression) Ln() Expressionfunc (AliasedExpression) Log
func (b AliasedExpression) Log(other any) Expressionfunc (AliasedExpression) Log10
func (b AliasedExpression) Log10() Expressionfunc (AliasedExpression) MapGet
func (b AliasedExpression) MapGet(strOrExprkey any) ExpressionObject functions
func (AliasedExpression) MapMerge
func (b AliasedExpression) MapMerge(secondMap Expression, otherMaps ...Expression) Expressionfunc (AliasedExpression) MapRemove
func (b AliasedExpression) MapRemove(strOrExprkey any) Expressionfunc (AliasedExpression) Maximum
func (b AliasedExpression) Maximum() AggregateFunctionfunc (AliasedExpression) Minimum
func (b AliasedExpression) Minimum() AggregateFunctionfunc (AliasedExpression) Mod
func (b AliasedExpression) Mod(other any) Expressionfunc (AliasedExpression) Multiply
func (b AliasedExpression) Multiply(other any) Expressionfunc (AliasedExpression) NotEqual
func (b AliasedExpression) NotEqual(other any) BooleanExpressionfunc (AliasedExpression) NotEqualAny
func (b AliasedExpression) NotEqualAny(values any) BooleanExpressionfunc (AliasedExpression) Pow
func (b AliasedExpression) Pow(other any) Expressionfunc (AliasedExpression) RegexContains
func (b AliasedExpression) RegexContains(pattern any) BooleanExpressionfunc (AliasedExpression) RegexMatch
func (b AliasedExpression) RegexMatch(pattern any) BooleanExpressionfunc (AliasedExpression) Reverse
func (b AliasedExpression) Reverse() Expressionfunc (AliasedExpression) Round
func (b AliasedExpression) Round() Expressionfunc (AliasedExpression) Split
func (b AliasedExpression) Split(delimiter any) Expressionfunc (AliasedExpression) Sqrt
func (b AliasedExpression) Sqrt() Expressionfunc (AliasedExpression) StartsWith
func (b AliasedExpression) StartsWith(prefix any) BooleanExpressionfunc (AliasedExpression) StringConcat
func (b AliasedExpression) StringConcat(otherStrings any) Expressionfunc (AliasedExpression) StringContains
func (b AliasedExpression) StringContains(substring any) BooleanExpressionfunc (AliasedExpression) StringReverse
func (b AliasedExpression) StringReverse() Expressionfunc (AliasedExpression) Substring
func (b AliasedExpression) Substring(index, offset any) Expressionfunc (AliasedExpression) Subtract
func (b AliasedExpression) Subtract(other any) Expressionfunc (AliasedExpression) Sum
func (b AliasedExpression) Sum() AggregateFunctionAggregation operations
func (AliasedExpression) TimestampAdd
func (b AliasedExpression) TimestampAdd(unit, amount any) ExpressionTimestamp functions
func (AliasedExpression) TimestampSubtract
func (b AliasedExpression) TimestampSubtract(unit, amount any) Expressionfunc (AliasedExpression) TimestampToUnixMicros
func (b AliasedExpression) TimestampToUnixMicros() Expressionfunc (AliasedExpression) TimestampToUnixMillis
func (b AliasedExpression) TimestampToUnixMillis() Expressionfunc (AliasedExpression) TimestampToUnixSeconds
func (b AliasedExpression) TimestampToUnixSeconds() Expressionfunc (AliasedExpression) TimestampTruncate
func (b AliasedExpression) TimestampTruncate(granularity any) Expressionfunc (AliasedExpression) TimestampTruncateWithTimezone
func (b AliasedExpression) TimestampTruncateWithTimezone(granularity any, timezone string) Expressionfunc (AliasedExpression) ToLower
func (b AliasedExpression) ToLower() Expressionfunc (AliasedExpression) ToUpper
func (b AliasedExpression) ToUpper() Expressionfunc (AliasedExpression) Trim
func (b AliasedExpression) Trim() Expressionfunc (AliasedExpression) Type
func (b AliasedExpression) Type() ExpressionType functions
func (AliasedExpression) UnixMicrosToTimestamp
func (b AliasedExpression) UnixMicrosToTimestamp() Expressionfunc (AliasedExpression) UnixMillisToTimestamp
func (b AliasedExpression) UnixMillisToTimestamp() Expressionfunc (AliasedExpression) UnixSecondsToTimestamp
func (b AliasedExpression) UnixSecondsToTimestamp() Expressionfunc (AliasedExpression) VectorLength
func (b AliasedExpression) VectorLength() ExpressionAndFilter
type AndFilter struct {
Filters []EntityFilter
}AndFilter represents the intersection of two or more filters.
BooleanExpression
type BooleanExpression interface {
Expression // Embed Expr interface
// Conditional creates an expression that evaluates a condition and returns one of two expressions.
//
// The parameter 'thenVal' is the expression to return if the condition is true.
// The parameter 'elseVal' is the expression to return if the condition is false.
Conditional(thenVal, elseVal any) Expression
// IfErrorBoolean creates a boolean expression that evaluates and returns the receiver expression if it does not produce an error;
// otherwise, it evaluates and returns `catchExpr`.
//
// The parameter 'catchExpr' is the boolean expression to return if the receiver expression errors.
IfErrorBoolean(catchExpr BooleanExpression) BooleanExpression
// Not creates an expression that negates a boolean expression.
Not() BooleanExpression
// CountIf creates an aggregation that counts the number of stage inputs where the this boolean expression
// evaluates to true.
CountIf() AggregateFunction
// contains filtered or unexported methods
}BooleanExpression is an interface that represents a boolean expression in a pipeline.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func And
func And(condition BooleanExpression, right ...BooleanExpression) BooleanExpressionAnd creates an expression that performs a logical 'AND' operation.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArrayContains
func ArrayContains(exprOrFieldPath any, value any) BooleanExpressionArrayContains creates an expression that checks if an array contains a specified element.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to an array.
- value is the element to check for.
Example:
// Check if the 'tags' array contains "Go".
ArrayContains("tags", "Go")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArrayContainsAll
func ArrayContainsAll(exprOrFieldPath any, values any) BooleanExpressionArrayContainsAll creates an expression that checks if an array contains all of the provided values.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to an array.
- values can be an array of values or an expression that evaluates to an array.
Example:
// Check if the 'tags' array contains both "Go" and "Firestore".
ArrayContainsAll("tags", []string{"Go", "Firestore"})
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArrayContainsAny
func ArrayContainsAny(exprOrFieldPath any, values any) BooleanExpressionArrayContainsAny creates an expression that checks if an array contains any of the provided values.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to an array.
- values can be an array of values or an expression that evaluates to an array.
Example:
// Check if the 'tags' array contains either "Go" or "Firestore".
ArrayContainsAny("tags", []string{"Go", "Firestore"})
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func EndsWith
func EndsWith(exprOrFieldPath any, suffix any) BooleanExpressionEndsWith creates an expression that checks if a string field or expression ends with a given suffix.
- exprOrFieldPath can be a field path string, [FieldPath] or [Expression].
- suffix string or [Expression] to check for.
Example:
// Check if the 'filename' field ends with ".go".
EndsWith("filename", ".go")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Equal
func Equal(left, right any) BooleanExpressionEqual creates an expression that checks if field's value or an expression is equal to an expression or a constant value, returning it as a BooleanExpr.
- left: The field path string, [FieldPath] or [Expression] to compare.
- right: The constant value or [Expression] to compare to.
Example:
// Check if the 'age' field is equal to 21
Equal(FieldOf("age"), 21)
// Check if the 'age' field is equal to an expression
Equal(FieldOf("age"), FieldOf("minAge").Add(10))
// Check if the 'age' field is equal to the 'limit' field
Equal("age", FieldOf("limit"))
// Check if the 'city' field is equal to string constant "London"
Equal("city", "London")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func EqualAny
func EqualAny(exprOrFieldPath any, values any) BooleanExpressionEqualAny creates an expression that checks if a field or expression is equal to any of the provided values.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression].
- values can be an array of values or an expression that evaluates to an array.
Example:
// Check if the 'status' field is either "active" or "pending".
EqualAny("status", []string{"active", "pending"})
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func FieldExists
func FieldExists(exprOrField any) BooleanExpressionFieldExists creates an expression that checks if a field exists.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func GreaterThan
func GreaterThan(left, right any) BooleanExpressionGreaterThan creates an expression that checks if field's value or an expression is greater than an expression or a constant value, returning it as a BooleanExpr.
- left: The field path string, [FieldPath] or [Expression] to compare.
- right: The constant value or [Expression] to compare to.
Example:
// Check if the 'age' field is greater than 21
GreaterThan(FieldOf("age"), 21)
// Check if the 'age' field is greater than an expression
GreaterThan(FieldOf("age"), FieldOf("minAge").Add(10))
// Check if the 'age' field is greater than the 'limit' field
GreaterThan("age", FieldOf("limit"))
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func GreaterThanOrEqual
func GreaterThanOrEqual(left, right any) BooleanExpressionGreaterThanOrEqual creates an expression that checks if field's value or an expression is greater than or equal to an expression or a constant value, returning it as a BooleanExpr.
- left: The field path string, [FieldPath] or [Expression] to compare.
- right: The constant value or [Expression] to compare to.
Example:
// Check if the 'age' field is greater than or equal to 21
GreaterThanOrEqual(FieldOf("age"), 21)
// Check if the 'age' field is greater than or equal to an expression
GreaterThanOrEqual(FieldOf("age"), FieldOf("minAge").Add(10))
// Check if the 'age' field is greater than or equal to the 'limit' field
GreaterThanOrEqual("age", FieldOf("limit"))
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func IfErrorBoolean
func IfErrorBoolean(tryExpr BooleanExpression, catchExpr BooleanExpression) BooleanExpressionIfErrorBoolean creates a boolean expression that evaluates and returns tryExpr if it does not produce an error;
otherwise, it evaluates and returns catchExpr. It returns a new [BooleanExpression] representing
the if_error operation.
- tryExpr is the boolean expression to try.
- catchExpr is the boolean expression to return if
tryExprerrors.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func IsAbsent
func IsAbsent(exprOrField any) BooleanExpressionIsAbsent creates an expression that checks if an expression evaluates to an absent value.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func IsError
func IsError(expr Expression) BooleanExpressionIsError creates an expression that checks if an expression evaluates to an error.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func LessThan
func LessThan(left, right any) BooleanExpressionLessThan creates an expression that checks if field's value or an expression is less than an expression or a constant value, returning it as a BooleanExpr.
- left: The field path string, [FieldPath] or [Expression] to compare.
- right: The constant value or [Expression] to compare to.
Example:
// Check if the 'age' field is less than 21
LessThan(FieldOf("age"), 21)
// Check if the 'age' field is less than an expression
LessThan(FieldOf("age"), FieldOf("minAge").Add(10))
// Check if the 'age' field is less than the 'limit' field
LessThan("age", FieldOf("limit"))
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func LessThanOrEqual
func LessThanOrEqual(left, right any) BooleanExpressionLessThanOrEqual creates an expression that checks if field's value or an expression is less than or equal to an expression or a constant value, returning it as a BooleanExpr.
- left: The field path string, [FieldPath] or [Expression] to compare.
- right: The constant value or [Expression] to compare to.
Example:
// Check if the 'age' field is less than or equal to 21
LessThanOrEqual(FieldOf("age"), 21)
// Check if the 'age' field is less than or equal to an expression
LessThanOrEqual(FieldOf("age"), FieldOf("minAge").Add(10))
// Check if the 'age' field is less than or equal to the 'limit' field
LessThanOrEqual("age", FieldOf("limit"))
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Like
func Like(exprOrFieldPath any, pattern any) BooleanExpressionLike creates an expression that performs a case-sensitive wildcard string comparison.
- exprOrFieldPath can be a field path string, [FieldPath] or [Expression].
- pattern string or [Expression] to search for. You can use "%" as a wildcard character.
Example:
// Check if the 'name' field starts with "G".
Like("name", "G%")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Not
func Not(condition BooleanExpression) BooleanExpressionNot creates an expression that negates a boolean expression.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func NotEqual
func NotEqual(left, right any) BooleanExpressionNotEqual creates an expression that checks if field's value or an expression is not equal to an expression or a constant value, returning it as a BooleanExpr.
- left: The field path string, [FieldPath] or [Expression] to compare.
- right: The constant value or [Expression] to compare to.
Example:
// Check if the 'age' field is not equal to 21
NotEqual(FieldOf("age"), 21)
// Check if the 'age' field is not equal to an expression
NotEqual(FieldOf("age"), FieldOf("minAge").Add(10))
// Check if the 'age' field is not equal to the 'limit' field
NotEqual("age", FieldOf("limit"))
// Check if the 'city' field is not equal to string constant "London"
NotEqual("city", "London")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func NotEqualAny
func NotEqualAny(exprOrFieldPath any, values any) BooleanExpressionNotEqualAny creates an expression that checks if a field or expression is not equal to any of the provided values.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression].
- values can be an array of values or an expression that evaluates to an array.
Example:
// Check if the 'status' field is not "archived" or "deleted".
NotEqualAny("status", []string{"archived", "deleted"})
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Or
func Or(condition BooleanExpression, right ...BooleanExpression) BooleanExpressionOr creates an expression that performs a logical 'OR' operation.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func RegexContains
func RegexContains(exprOrFieldPath any, pattern any) BooleanExpressionRegexContains creates an expression that checks if a string contains a match for a regular expression.
- exprOrFieldPath can be a field path string, [FieldPath] or [Expression].
- pattern is the regular expression to search for.
Example:
// Check if the 'email' field contains a gmail address.
RegexContains("email", "@gmail\\.com$")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func RegexMatch
func RegexMatch(exprOrFieldPath any, pattern any) BooleanExpressionRegexMatch creates an expression that checks if a string matches a regular expression.
- exprOrFieldPath can be a field path string, [FieldPath] or [Expression].
- pattern is the regular expression to match against.
Example:
// Check if the 'zip_code' field is a 5-digit number.
RegexMatch("zip_code", "^[0-9]{5}$")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func StartsWith
func StartsWith(exprOrFieldPath any, prefix any) BooleanExpressionStartsWith creates an expression that checks if a string field or expression starts with a given prefix.
- exprOrFieldPath can be a field path string, [FieldPath] or [Expression].
- prefix string or [Expression] to check for.
Example:
// Check if the 'name' field starts with "Mr.".
StartsWith("name", "Mr.")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func StringContains
func StringContains(exprOrFieldPath any, substring any) BooleanExpressionStringContains creates an expression that checks if a string contains a specified substring.
- exprOrFieldPath can be a field path string, [FieldPath] or [Expression].
- substring is the string to search for.
Example:
// Check if the 'description' field contains the word "Firestore".
StringContains("description", "Firestore")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Xor
func Xor(condition BooleanExpression, right ...BooleanExpression) BooleanExpressionXor creates an expression that performs a logical 'XOR' operation.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
BulkWriter
type BulkWriter struct {
// contains filtered or unexported fields
}A BulkWriter supports concurrent writes to multiple documents. The BulkWriter submits document writes in maximum batches of 20 writes per request. Each request can contain many different document writes: create, delete, update, and set are all supported.
Only one operation (create, set, update, delete) per document is allowed. BulkWriter cannot promise atomicity: individual writes can fail or succeed independent of each other. Bulkwriter does not apply writes in any set order; thus a document can't have set on it immediately after creation.
func (*BulkWriter) Create
func (bw *BulkWriter) Create(doc *DocumentRef, datum interface{}) (*BulkWriterJob, error)Create adds a document creation write to the queue of writes to send. Note: You cannot write to (Create, Update, Set, or Delete) the same document more than once.
func (*BulkWriter) Delete
func (bw *BulkWriter) Delete(doc *DocumentRef, preconds ...Precondition) (*BulkWriterJob, error)Delete adds a document deletion write to the queue of writes to send. Note: You cannot write to (Create, Update, Set, or Delete) the same document more than once.
func (*BulkWriter) End
func (bw *BulkWriter) End()End sends all enqueued writes in parallel and closes the BulkWriter to new requests. After calling End(), calling any additional method automatically returns with an error. This method completes when there are no more pending writes in the queue.
func (*BulkWriter) Flush
func (bw *BulkWriter) Flush()Flush commits all writes that have been enqueued up to this point in parallel. This method blocks execution.
func (*BulkWriter) Set
func (bw *BulkWriter) Set(doc *DocumentRef, datum interface{}, opts ...SetOption) (*BulkWriterJob, error)Set adds a document set write to the queue of writes to send. Note: You cannot write to (Create, Update, Set, or Delete) the same document more than once.
func (*BulkWriter) Update
func (bw *BulkWriter) Update(doc *DocumentRef, updates []Update, preconds ...Precondition) (*BulkWriterJob, error)Update adds a document update write to the queue of writes to send. Note: You cannot write to (Create, Update, Set, or Delete) the same document more than once.
BulkWriterJob
type BulkWriterJob struct {
// contains filtered or unexported fields
}BulkWriterJob provides read-only access to the results of a BulkWriter write attempt.
func (*BulkWriterJob) Results
func (j *BulkWriterJob) Results() (*WriteResult, error)Results gets the results of the BulkWriter write attempt. This method blocks if the results for this BulkWriterJob haven't been received.
Client
type Client struct {
UsesEmulator bool // a boolean that indicates if the client is using the emulator
// contains filtered or unexported fields
}A Client provides access to the Firestore service.
func NewClient
NewClient creates a new Firestore client that uses the given project.
Example
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close() // Close client when done.
_ = client // TODO: Use client.
}
func NewClientWithDatabase
func NewClientWithDatabase(ctx context.Context, projectID string, databaseID string, opts ...option.ClientOption) (*Client, error)NewClientWithDatabase creates a new Firestore client that accesses the specified database.
func NewRESTClient
func NewRESTClient(ctx context.Context, projectID string, opts ...option.ClientOption) (*Client, error)NewRESTClient creates a new Firestore client that uses the REST API.
func (*Client) Batch (deprecated)
func (c *Client) Batch() *WriteBatchBatch returns a WriteBatch.
Deprecated: The WriteBatch API has been replaced with the transaction and
the bulk writer API. For atomic transaction operations, use Transaction.
For bulk read and write operations, use BulkWriter.
Example
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
b := client.Batch()
_ = b // TODO: Use batch.
}
func (*Client) BulkWriter
func (c *Client) BulkWriter(ctx context.Context) *BulkWriterBulkWriter returns a BulkWriter instance. The context passed to the BulkWriter remains stored through the lifecycle of the object. This context allows callers to cancel BulkWriter operations.
func (*Client) Close
Close closes any resources held by the client.
Close need not be called at program exit.
func (*Client) Collection
func (c *Client) Collection(path string) *CollectionRefCollection creates a reference to a collection with the given path. A path is a sequence of IDs separated by slashes.
Collection returns nil if path contains an even number of IDs or any ID is empty.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
coll1 := client.Collection("States")
coll2 := client.Collection("States/NewYork/Cities")
fmt.Println(coll1, coll2)
}
func (*Client) CollectionGroup
func (c *Client) CollectionGroup(collectionID string) *CollectionGroupRefCollectionGroup creates a reference to a group of collections that include the given ID, regardless of parent document.
For example, consider: France/Cities/Paris = {population: 100} Canada/Cities/Montreal = {population: 90}
CollectionGroup can be used to query across all "Cities" regardless of its parent "Countries". See ExampleCollectionGroup for a complete example.
Example
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
// Given:
// France/Cities/Paris = {population: 100}
// Canada/Cities/Montreal = {population: 95}
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
// Query for ANY city with >95 pop, regardless of country.
docs, err := client.CollectionGroup("Cities").
Where("pop", ">", 95).
OrderBy("pop", firestore.Desc).
Limit(10).
Documents(ctx).
GetAll()
if err != nil {
// TODO: Handle error.
}
_ = docs // TODO: Use docs.
}
func (*Client) Collections
func (c *Client) Collections(ctx context.Context) *CollectionIteratorCollections returns an iterator over the top-level collections.
func (*Client) Doc
func (c *Client) Doc(path string) *DocumentRefDoc creates a reference to a document with the given path. A path is a sequence of IDs separated by slashes.
Doc returns nil if path contains an odd number of IDs or any ID is empty.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
doc1 := client.Doc("States/NewYork")
doc2 := client.Doc("States/NewYork/Cities/Albany")
fmt.Println(doc1, doc2)
}
func (*Client) DocFromFullPath
func (c *Client) DocFromFullPath(fullPath string) *DocumentRefDocFromFullPath creates a reference to a document from its full, absolute path, also known as its Google Cloud resource name. The path must be in the format: "projects/{projectID}/databases/{databaseID}/documents/{collectionID}/{documentID}/..." This method returns nil if:
- The fullPath is empty.
- The fullPath does not match the expected resource name format (e.g., missing "projects/" or "/documents/").
- The projectID or databaseID in the fullPath do not match the client's configuration.
- The fullPath refers to a collection instead of a document (i.e., has an odd number of segments after "/documents/").
- The fullPath contains any empty path segments.
func (*Client) GetAll
func (c *Client) GetAll(ctx context.Context, docRefs []*DocumentRef) (_ []*DocumentSnapshot, err error)GetAll retrieves multiple documents with a single call. The DocumentSnapshots are returned in the order of the given DocumentRefs. The return value will always contain the same number of DocumentSnapshots as the number of DocumentRefs in the input.
If the same DocumentRef is specified multiple times in the input, the return value will contain the same number of DocumentSnapshots referencing the same document.
If a document is not present, the corresponding DocumentSnapshot's Exists method will return false.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
docs, err := client.GetAll(ctx, []*firestore.DocumentRef{
client.Doc("States/NorthCarolina"),
client.Doc("States/SouthCarolina"),
client.Doc("States/WestCarolina"),
client.Doc("States/EastCarolina"),
})
if err != nil {
// TODO: Handle error.
}
// docs is a slice with four DocumentSnapshots, but the last two are
// nil because there is no West or East Carolina.
fmt.Println(docs)
}
func (*Client) Pipeline
func (c *Client) Pipeline() *PipelineSourcePipeline creates a PipelineSource to start building a Firestore pipeline.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Client) RunTransaction
func (c *Client) RunTransaction(ctx context.Context, f func(context.Context, *Transaction) error, opts ...TransactionOption) (err error)RunTransaction runs f in a transaction. f should use the transaction it is given for all Firestore operations. For any operation requiring a context, f should use the context it is passed, not the first argument to RunTransaction.
f must not call Commit or Rollback on the provided Transaction.
If f returns nil, RunTransaction commits the transaction. If the commit fails due to a conflicting transaction, RunTransaction retries f. It gives up and returns an error after a number of attempts that can be configured with the MaxAttempts option. If the commit succeeds, RunTransaction returns a nil error.
If f returns non-nil, then the transaction will be rolled back and this method will return the same error. The function f is not retried.
Note that when f returns, the transaction is not committed. Calling code must not assume that any of f's changes have been committed until RunTransaction returns nil.
Since f may be called more than once, f should usually be idempotent – that is, it should have the same result when called multiple times.
Example
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
// write the CommitResponse here, via firestore.WithCommitResponse (below)
var cr firestore.CommitResponse
nm := client.Doc("States/NewMexico")
err = client.RunTransaction(ctx, func(ctx context.Context, tx *firestore.Transaction) error {
doc, err := tx.Get(nm) // tx.Get, NOT nm.Get!
if err != nil {
return err
}
pop, err := doc.DataAt("pop")
if err != nil {
return err
}
return tx.Update(nm, []firestore.Update{{Path: "pop", Value: pop.(float64) + 0.2}})
}, firestore.WithCommitResponseTo(&cr))
if err != nil {
// TODO: Handle error.
}
// CommitResponse can be accessed here
}
func (*Client) WithReadOptions
func (c *Client) WithReadOptions(opts ...ReadOption) *ClientWithReadOptions specifies constraints for accessing documents from the database, e.g. at what time snapshot to read the documents.
CollectionGroupOption
type CollectionGroupOption interface {
// contains filtered or unexported methods
}CollectionGroupOption is an option for a CollectionGroup pipeline stage.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func WithCollectionGroupHints
func WithCollectionGroupHints(hints CollectionHints) CollectionGroupOptionWithCollectionGroupHints specifies hints for the query planner.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
CollectionGroupRef
type CollectionGroupRef struct {
// Use the methods of Query on a CollectionGroupRef to create and run queries.
Query
// contains filtered or unexported fields
}A CollectionGroupRef is a reference to a group of collections sharing the same ID.
func (CollectionGroupRef) GetPartitionedQueries
func (cgr CollectionGroupRef) GetPartitionedQueries(ctx context.Context, partitionCount int) ([]Query, error)GetPartitionedQueries returns a slice of Query objects, each containing a partition of a collection group. partitionCount must be a positive value and the number of returned partitions may be less than the requested number if providing the desired number would result in partitions with very few documents.
If a Collection Group Query would return a large number of documents, this can help to subdivide the query to smaller working units that can be distributed.
If the goal is to run the queries across processes or workers, it may be useful to use
Query.Serialize and Query.Deserialize to serialize the query.
CollectionHints
CollectionHints provides hints to the query planner.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (CollectionHints) WithForceIndex
func (ch CollectionHints) WithForceIndex(index string) CollectionHintsWithForceIndex specifies an index to force the query to use.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (CollectionHints) WithIgnoreIndexFields
func (ch CollectionHints) WithIgnoreIndexFields(fields string) CollectionHintsWithIgnoreIndexFields specifies fields to ignore when selecting an index.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
CollectionIterator
type CollectionIterator struct {
// contains filtered or unexported fields
}CollectionIterator is an iterator over sub-collections of a document.
func (*CollectionIterator) GetAll
func (it *CollectionIterator) GetAll() ([]*CollectionRef, error)GetAll returns all the collections remaining from the iterator.
func (*CollectionIterator) Next
func (it *CollectionIterator) Next() (*CollectionRef, error)Next returns the next result. Its second return value is iterator.Done if there are no more results. Once Next returns Done, all subsequent calls will return Done.
func (*CollectionIterator) PageInfo
func (it *CollectionIterator) PageInfo() *iterator.PageInfoPageInfo supports pagination. See the google.golang.org/api/iterator package for details.
CollectionOption
type CollectionOption interface {
// contains filtered or unexported methods
}CollectionOption is an option for a Collection pipeline stage.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func WithCollectionHints
func WithCollectionHints(hints CollectionHints) CollectionOptionWithCollectionHints specifies hints for the query planner.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
CollectionRef
type CollectionRef struct {
// Parent is the document of which this collection is a part. It is
// nil for top-level collections.
Parent *DocumentRef
// The full resource path of the collection: "projects/P/databases/D/documents..."
Path string
// ID is the collection identifier.
ID string
// Use the methods of Query on a CollectionRef to create and run queries.
Query
// contains filtered or unexported fields
}A CollectionRef is a reference to Firestore collection.
func (*CollectionRef) Add
func (c *CollectionRef) Add(ctx context.Context, data interface{}) (*DocumentRef, *WriteResult, error)Add generates a DocumentRef with a unique ID. It then creates the document with the given data, which can be a map[string]interface{}, a struct or a pointer to a struct.
Add returns an error in the unlikely event that a document with the same ID already exists.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
doc, wr, err := client.Collection("Users").Add(ctx, map[string]interface{}{
"name": "Alice",
"email": "aj@example.com",
})
if err != nil {
// TODO: Handle error.
}
fmt.Println(doc, wr)
}
func (*CollectionRef) Doc
func (c *CollectionRef) Doc(id string) *DocumentRefDoc returns a DocumentRef that refers to the document in the collection with the given identifier.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
fl := client.Collection("States").Doc("Florida")
ta := client.Collection("States").Doc("Florida/Cities/Tampa")
fmt.Println(fl, ta)
}
func (*CollectionRef) DocumentRefs
func (c *CollectionRef) DocumentRefs(ctx context.Context) *DocumentRefIteratorDocumentRefs returns references to all the documents in the collection, including missing documents. A missing document is a document that does not exist but has sub-documents.
func (*CollectionRef) NewDoc
func (c *CollectionRef) NewDoc() *DocumentRefNewDoc returns a DocumentRef with a uniquely generated ID.
NewDoc will panic if crypto/rand cannot generate enough bytes to make a new doc ID.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
doc := client.Collection("Users").NewDoc()
fmt.Println(doc)
}
func (*CollectionRef) WithReadOptions
func (c *CollectionRef) WithReadOptions(opts ...ReadOption) *CollectionRefWithReadOptions specifies constraints for accessing documents from the database, e.g. at what time snapshot to read the documents.
CommitResponse
type CommitResponse struct {
// contains filtered or unexported fields
}CommitResponse exposes information about a committed transaction.
func (*CommitResponse) CommitTime
func (r *CommitResponse) CommitTime() time.TimeCommitTime returns the commit time from the commit response.
CompositeFilter
type CompositeFilter interface {
EntityFilter
// contains filtered or unexported methods
}CompositeFilter represents a composite Firestore filter.
Direction
type Direction int32Direction is the sort direction for result ordering.
Asc, Desc
const (
// Asc sorts results from smallest to largest.
Asc Direction = Direction(pb.StructuredQuery_ASCENDING)
// Desc sorts results from largest to smallest.
Desc Direction = Direction(pb.StructuredQuery_DESCENDING)
)DistanceMeasure
type DistanceMeasure int32DistanceMeasure is the distance measure to use when comparing vectors with [Query.FindNearest] or [Query.FindNearestPath].
DistanceMeasureEuclidean, DistanceMeasureCosine, DistanceMeasureDotProduct
const (
// DistanceMeasureEuclidean is used to measures the Euclidean distance between the vectors. See
// [Euclidean] to learn more.
//
// [Euclidean]: https://en.wikipedia.org/wiki/Euclidean_distance
DistanceMeasureEuclidean DistanceMeasure = DistanceMeasure(pb.StructuredQuery_FindNearest_EUCLIDEAN)
// DistanceMeasureCosine compares vectors based on the angle between them, which allows you to
// measure similarity that isn't based on the vectors magnitude.
// We recommend using dot product with unit normalized vectors instead of
// cosine distance, which is mathematically equivalent with better
// performance. See [Cosine Similarity] to learn more.
//
// [Cosine Similarity]: https://en.wikipedia.org/wiki/Cosine_similarity
DistanceMeasureCosine DistanceMeasure = DistanceMeasure(pb.StructuredQuery_FindNearest_COSINE)
// DistanceMeasureDotProduct is similar to cosine but is affected by the magnitude of the vectors. See
// [Dot Product] to learn more.
//
// [Dot Product]: https://en.wikipedia.org/wiki/Dot_product
DistanceMeasureDotProduct DistanceMeasure = DistanceMeasure(pb.StructuredQuery_FindNearest_DOT_PRODUCT)
)DocumentChange
type DocumentChange struct {
Kind DocumentChangeKind
Doc *DocumentSnapshot
// The document snapshot before the change.
// This will be nil for DocumentAdded events.
// For DocumentRemoved events, this will be the same as Doc.
// For DocumentModified events, this will be the document before the modification.
OldDoc *DocumentSnapshot
// The zero-based index of the document in the sequence of query results prior to this change,
// or -1 if the document was not present.
OldIndex int
// The zero-based index of the document in the sequence of query results after this change,
// or -1 if the document is no longer present.
NewIndex int
}A DocumentChange describes the change to a document from one query snapshot to the next.
DocumentChangeKind
type DocumentChangeKind intDocumentChangeKind describes the kind of change to a document between query snapshots.
DocumentAdded, DocumentRemoved, DocumentModified
const (
// DocumentAdded indicates that the document was added for the first time.
DocumentAdded DocumentChangeKind = iota
// DocumentRemoved indicates that the document was removed.
DocumentRemoved
// DocumentModified indicates that the document was modified.
DocumentModified
)func (DocumentChangeKind) String
func (k DocumentChangeKind) String() stringString returns the string representation of the DocumentChangeKind.
DocumentIterator
type DocumentIterator struct {
// contains filtered or unexported fields
}DocumentIterator is an iterator over documents returned by a query.
func (*DocumentIterator) ExplainMetrics
func (it *DocumentIterator) ExplainMetrics() (*ExplainMetrics, error)ExplainMetrics returns query explain metrics. This is only present when [ExplainOptions] is added to the query (see [Query.WithRunOptions]), and after the iterator reaches the end. An error is returned if either of those conditions does not hold.
func (*DocumentIterator) GetAll
func (it *DocumentIterator) GetAll() ([]*DocumentSnapshot, error)GetAll returns all the documents remaining from the iterator. It is not necessary to call Stop on the iterator after calling GetAll.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
q := client.Collection("States").
Where("pop", ">", 10).
OrderBy("pop", firestore.Desc).
Limit(10) // a good idea with GetAll, to avoid filling memory
docs, err := q.Documents(ctx).GetAll()
if err != nil {
// TODO: Handle error.
}
for _, doc := range docs {
fmt.Println(doc.Data())
}
}
func (*DocumentIterator) Next
func (it *DocumentIterator) Next() (*DocumentSnapshot, error)Next returns the next result. Its second return value is iterator.Done if there are no more results. Once Next returns Done, all subsequent calls will return Done.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
"google.golang.org/api/iterator"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
q := client.Collection("States").
Where("pop", ">", 10).
OrderBy("pop", firestore.Desc)
iter := q.Documents(ctx)
defer iter.Stop()
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
// TODO: Handle error.
}
fmt.Println(doc.Data())
}
}
func (*DocumentIterator) Stop
func (it *DocumentIterator) Stop()Stop stops the iterator, freeing its resources. Always call Stop when you are done with a DocumentIterator. It is not safe to call Stop concurrently with Next.
DocumentRef
type DocumentRef struct {
// The CollectionRef that this document is a part of. Never nil.
Parent *CollectionRef
// The full resource path of the document. A document "doc-1" in collection
// "coll-1" would be: "projects/P/databases/D/documents/coll-1/doc-1".
Path string
// The ID of the document: the last component of the resource path.
ID string
// contains filtered or unexported fields
}A DocumentRef is a reference to a Firestore document.
func (*DocumentRef) Collection
func (d *DocumentRef) Collection(id string) *CollectionRefCollection returns a reference to sub-collection of this document.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
mi := client.Collection("States").Doc("Michigan")
cities := mi.Collection("Cities")
fmt.Println(cities)
}
func (*DocumentRef) Collections
func (d *DocumentRef) Collections(ctx context.Context) *CollectionIteratorCollections returns an iterator over the immediate sub-collections of the document.
func (*DocumentRef) Create
func (d *DocumentRef) Create(ctx context.Context, data interface{}) (_ *WriteResult, err error)Create creates the document with the given data. It returns an error if a document with the same ID already exists.
The data argument can be a map with string keys, a struct, or a pointer to a struct. The map keys or exported struct fields become the fields of the firestore document. The values of data are converted to Firestore values as follows:
- bool converts to Bool.
- string converts to String.
- int, int8, int16, int32 and int64 convert to Integer.
- uint8, uint16 and uint32 convert to Integer. uint, uint64 and uintptr are disallowed, because they may be able to represent values that cannot be represented in an int64, which is the underlying type of a Integer.
- float32 and float64 convert to Double.
- []byte converts to Bytes.
- time.Time and *ts.Timestamp convert to Timestamp. ts is the package "google.golang.org/protobuf/types/known/timestamppb".
- *latlng.LatLng converts to GeoPoint. latlng is the package "google.golang.org/genproto/googleapis/type/latlng". You should always use a pointer to a LatLng.
- Slices convert to Array.
- *firestore.DocumentRef converts to Reference.
- Maps and structs convert to Map.
- nils of any type convert to Null.
Pointers and interface{} are also permitted, and their elements processed recursively.
Struct fields can have tags like those used by the encoding/json package. Tags begin with "firestore:" and are followed by "-", meaning "ignore this field," or an alternative name for the field. Following the name, these comma-separated options may be provided:
- omitempty: Do not encode this field if it is empty. A value is empty if it is a zero value, or an array, slice or map of length zero.
- serverTimestamp: The field must be of type time.Time. serverTimestamp is a sentinel token that tells Firestore to substitute the server time into that field. When writing, if the field has the zero value, the server will populate the stored document with the time that the request is processed. However, if the field value is non-zero it won't be saved.
Examples
map
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
wr, err := client.Doc("States/Colorado").Create(ctx, map[string]interface{}{
"capital": "Denver",
"pop": 5.5,
})
if err != nil {
// TODO: Handle error.
}
fmt.Println(wr.UpdateTime)
}
struct
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
type State struct {
Capital string `firestore:"capital"`
Population float64 `firestore:"pop"` // in millions
}
wr, err := client.Doc("States/Colorado").Create(ctx, State{
Capital: "Denver",
Population: 5.5,
})
if err != nil {
// TODO: Handle error.
}
fmt.Println(wr.UpdateTime)
}
func (*DocumentRef) Delete
func (d *DocumentRef) Delete(ctx context.Context, preconds ...Precondition) (_ *WriteResult, err error)Delete deletes the document. If the document doesn't exist, it does nothing and returns no error.
Example
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
// Oops, Ontario is a Canadian province...
if _, err = client.Doc("States/Ontario").Delete(ctx); err != nil {
// TODO: Handle error.
}
}
func (*DocumentRef) Get
func (d *DocumentRef) Get(ctx context.Context) (_ *DocumentSnapshot, err error)Get retrieves the document. If the document does not exist, Get return a NotFound error, which can be checked with
status.Code(err) == codes.NotFound
In that case, Get returns a non-nil DocumentSnapshot whose Exists method return false and whose ReadTime is the time of the failed read operation.
Example
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
docsnap, err := client.Doc("States/Ohio").Get(ctx)
if err != nil {
// TODO: Handle error.
}
_ = docsnap // TODO: Use DocumentSnapshot.
}
func (*DocumentRef) Set
func (d *DocumentRef) Set(ctx context.Context, data interface{}, opts ...SetOption) (_ *WriteResult, err error)Set creates or overwrites the document with the given data. See DocumentRef.Create for the acceptable values of data. Without options, Set overwrites the document completely. Specify one of the Merge options to preserve an existing document's fields. To delete some fields, use a Merge option with firestore.Delete as the field value.
Examples
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
// Overwrite the document with the given data. Any other fields currently
// in the document will be removed.
wr, err := client.Doc("States/Alabama").Set(ctx, map[string]interface{}{
"capital": "Montgomery",
"pop": 4.9,
})
if err != nil {
// TODO: Handle error.
}
fmt.Println(wr.UpdateTime)
}
merge
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
// Overwrite only the fields in the map; preserve all others.
_, err = client.Doc("States/Alabama").Set(ctx, map[string]interface{}{
"pop": 5.2,
}, firestore.MergeAll)
if err != nil {
// TODO: Handle error.
}
type State struct {
Capital string `firestore:"capital"`
Population float64 `firestore:"pop"` // in millions
}
// To do a merging Set with struct data, specify the exact fields to overwrite.
// MergeAll is disallowed here, because it would probably be a mistake: the "capital"
// field would be overwritten with the empty string.
_, err = client.Doc("States/Alabama").Set(ctx, State{Population: 5.2}, firestore.Merge([]string{"pop"}))
if err != nil {
// TODO: Handle error.
}
}
func (*DocumentRef) Snapshots
func (d *DocumentRef) Snapshots(ctx context.Context) *DocumentSnapshotIteratorSnapshots returns an iterator over snapshots of the document. Each time the document changes or is added or deleted, a new snapshot will be generated.
Example
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
iter := client.Doc("States/Idaho").Snapshots(ctx)
defer iter.Stop()
for {
docsnap, err := iter.Next()
if err != nil {
// TODO: Handle error.
}
_ = docsnap // TODO: Use DocumentSnapshot.
}
}
func (*DocumentRef) Update
func (d *DocumentRef) Update(ctx context.Context, updates []Update, preconds ...Precondition) (_ *WriteResult, err error)Update updates the document. The values at the given field paths are replaced, but other fields of the stored document are untouched.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
tenn := client.Doc("States/Tennessee")
wr, err := tenn.Update(ctx, []firestore.Update{
{Path: "pop", Value: 6.6},
{FieldPath: []string{".", "*", "/"}, Value: "odd"},
})
if err != nil {
// TODO: Handle error.
}
fmt.Println(wr.UpdateTime)
}
func (*DocumentRef) WithReadOptions
func (d *DocumentRef) WithReadOptions(opts ...ReadOption) *DocumentRefWithReadOptions specifies constraints for accessing documents from the database, e.g. at what time snapshot to read the documents.
DocumentRefIterator
type DocumentRefIterator struct {
// contains filtered or unexported fields
}DocumentRefIterator is an iterator over DocumentRefs.
func (*DocumentRefIterator) GetAll
func (it *DocumentRefIterator) GetAll() ([]*DocumentRef, error)GetAll returns all the DocumentRefs remaining from the iterator.
func (*DocumentRefIterator) Next
func (it *DocumentRefIterator) Next() (*DocumentRef, error)Next returns the next result. Its second return value is iterator.Done if there are no more results. Once Next returns Done, all subsequent calls will return Done.
func (*DocumentRefIterator) PageInfo
func (it *DocumentRefIterator) PageInfo() *iterator.PageInfoPageInfo supports pagination. See the google.golang.org/api/iterator package for details.
DocumentSnapshot
type DocumentSnapshot struct {
// The DocumentRef for this document.
Ref *DocumentRef
// Read-only. The time at which the document was created.
// Increases monotonically when a document is deleted then
// recreated. It can also be compared to values from other documents and
// the read time of a query.
CreateTime time.Time
// Read-only. The time at which the document was last changed. This value
// is initially set to CreateTime then increases monotonically with each
// change to the document. It can also be compared to values from other
// documents and the read time of a query.
UpdateTime time.Time
// Read-only. The time at which the document was read.
ReadTime time.Time
// contains filtered or unexported fields
}A DocumentSnapshot contains document data and metadata.
func (*DocumentSnapshot) Data
func (d *DocumentSnapshot) Data() map[string]interface{}Data returns the DocumentSnapshot's fields as a map. It is equivalent to
var m map[string]interface{}
d.DataTo(&m)
except that it returns nil if the document does not exist.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
docsnap, err := client.Doc("States/Ohio").Get(ctx)
if err != nil {
// TODO: Handle error.
}
ohioMap := docsnap.Data()
fmt.Println(ohioMap["capital"])
}
func (*DocumentSnapshot) DataAt
func (d *DocumentSnapshot) DataAt(path string) (interface{}, error)DataAt returns the data value denoted by path.
The path argument can be a single field or a dot-separated sequence of fields, and must not contain any of the runes "˜*/[]". Use DataAtPath instead for such a path.
See DocumentSnapshot.DataTo for how Firestore values are converted to Go values.
If the document does not exist, DataAt returns a NotFound error.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
docsnap, err := client.Doc("States/Ohio").Get(ctx)
if err != nil {
// TODO: Handle error.
}
cap, err := docsnap.DataAt("capital")
if err != nil {
// TODO: Handle error.
}
fmt.Println(cap)
}
func (*DocumentSnapshot) DataAtPath
func (d *DocumentSnapshot) DataAtPath(fp FieldPath) (interface{}, error)DataAtPath returns the data value denoted by the FieldPath fp. If the document does not exist, DataAtPath returns a NotFound error.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
docsnap, err := client.Doc("States/Ohio").Get(ctx)
if err != nil {
// TODO: Handle error.
}
pop, err := docsnap.DataAtPath([]string{"capital", "population"})
if err != nil {
// TODO: Handle error.
}
fmt.Println(pop)
}
func (*DocumentSnapshot) DataTo
func (d *DocumentSnapshot) DataTo(p interface{}) errorDataTo uses the document's fields to populate p, which can be a pointer to a map[string]interface{} or a pointer to a struct.
Firestore field values are converted to Go values as follows:
- Null converts to nil.
- Bool converts to bool.
- String converts to string.
- Integer converts int64. When setting a struct field, any signed or unsigned integer type is permitted except uint, uint64 or uintptr. Overflow is detected and results in an error.
- Double converts to float64. When setting a struct field, float32 is permitted. Overflow is detected and results in an error.
- Bytes is converted to []byte.
- Timestamp converts to time.Time.
- GeoPoint converts to *latlng.LatLng, where latlng is the package "google.golang.org/genproto/googleapis/type/latlng".
- Arrays convert to []interface{}. When setting a struct field, the field may be a slice or array of any type and is populated recursively. Slices are resized to the incoming value's size, while arrays that are too long have excess elements filled with zero values. If the array is too short, excess incoming values will be dropped.
- Vectors convert to []float64
- Maps convert to map[string]interface{}. When setting a struct field, maps of key type string and any value type are permitted, and are populated recursively.
- References are converted to *firestore.DocumentRefs.
Field names given by struct field tags are observed, as described in DocumentRef.Create.
Only the fields actually present in the document are used to populate p. Other fields of p are left unchanged.
If the document does not exist, DataTo returns a NotFound error.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
docsnap, err := client.Doc("States/Ohio").Get(ctx)
if err != nil {
// TODO: Handle error.
}
type State struct {
Capital string `firestore:"capital"`
Population float64 `firestore:"pop"` // in millions
}
var s State
if err := docsnap.DataTo(&s); err != nil {
// TODO: Handle error.
}
fmt.Println(s)
}
func (*DocumentSnapshot) Exists
func (d *DocumentSnapshot) Exists() boolExists reports whether the DocumentSnapshot represents an existing document. Even if Exists returns false, the Ref and ReadTime fields of the DocumentSnapshot are valid.
DocumentSnapshotIterator
type DocumentSnapshotIterator struct {
// contains filtered or unexported fields
}DocumentSnapshotIterator is an iterator over snapshots of a document. Call Next on the iterator to get a snapshot of the document each time it changes. Call Stop on the iterator when done.
For an example, see DocumentRef.Snapshots.
func (*DocumentSnapshotIterator) Next
func (it *DocumentSnapshotIterator) Next() (*DocumentSnapshot, error)Next blocks until the document changes, then returns the DocumentSnapshot for the current state of the document. If the document has been deleted, Next returns a DocumentSnapshot whose Exists method returns false.
Next is not expected to return iterator.Done unless it is called after Stop. Rarely, networking issues may also cause iterator.Done to be returned.
func (*DocumentSnapshotIterator) Stop
func (it *DocumentSnapshotIterator) Stop()Stop stops receiving snapshots. You should always call Stop when you are done with a DocumentSnapshotIterator, to free up resources. It is not safe to call Stop concurrently with Next.
EntityFilter
type EntityFilter interface {
// contains filtered or unexported methods
}EntityFilter represents a Firestore filter.
ExecuteOption
type ExecuteOption interface {
// contains filtered or unexported methods
}ExecuteOption is an option for executing a pipeline query.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func WithExplainMode
func WithExplainMode(mode ExplainMode) ExecuteOptionWithExplainMode sets the execution mode for pipeline explain.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
ExecutionStats
type ExecutionStats struct {
// Total number of results returned, including documents, projections,
// aggregation results, keys.
ResultsReturned int64
// Total time to execute the query in the backend.
ExecutionDuration *time.Duration
// Total billable read operations.
ReadOperations int64
// Debugging statistics from the execution of the query. Note that the
// debugging stats are subject to change as Firestore evolves. It could
// include:
//
// {
// "indexes_entries_scanned": "1000",
// "documents_scanned": "20",
// "billing_details" : {
// "documents_billable": "20",
// "index_entries_billable": "1000",
// "min_query_cost": "0"
// }
// }
DebugStats *map[string]any
}ExecutionStats represents execution statistics for the query.
ExplainMetrics
type ExplainMetrics struct {
// Planning phase information for the query.
PlanSummary *PlanSummary
// Aggregated stats from the execution of the query. Only present when
// ExplainOptions.analyze is set to true
ExecutionStats *ExecutionStats
}ExplainMetrics represents explain metrics for the query.
ExplainMode
type ExplainMode stringExplainMode is the execution mode for pipeline explain.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
ExplainModeAnalyze
const (
// ExplainModeAnalyze both plans and executes the query.
ExplainModeAnalyze ExplainMode = "analyze"
)ExplainOptions
type ExplainOptions struct {
// When false (the default), Query Explain plans the query, but skips over the
// execution stage. This will return planner stage information.
//
// When true, Query Explain both plans and executes the query. This returns all
// the planner information along with statistics from the query execution runtime.
// This will include the billing information of the query along with system-level
// insights into the query execution.
Analyze bool
}ExplainOptions are Query Explain options. Query Explain allows you to submit Cloud Firestore queries to the backend and receive detailed performance statistics on backend query execution in return.
ExplainStats
type ExplainStats struct {
// contains filtered or unexported fields
}ExplainStats is query explain stats.
Contains all metadata related to pipeline planning and execution, specific contents depend on the supplied pipeline options.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*ExplainStats) RawData
func (es *ExplainStats) RawData() (*anypb.Any, error)RawData returns the explain stats in an encoded proto format, as returned from the Firestore backend. The caller is responsible for unpacking this proto message.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*ExplainStats) Text
func (es *ExplainStats) Text() (string, error)Text returns the explain stats as a string from the Firestore backend.
If explain stats were requested with outputFormat = 'text', the string is
returned verbatim. If outputFormat = 'json', this returns the explain stats
as stringified JSON.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
Expression
type Expression interface {
// Add creates an expression that adds two expressions together, returning it as an Expr.
//
// The parameter 'other' can be a numeric constant or a numeric [Expression].
Add(other any) Expression
// Subtract creates an expression that subtracts the right expression from the left expression, returning it as an Expr.
//
// The parameter 'other' can be a numeric constant or a numeric [Expression].
Subtract(other any) Expression
// Multiply creates an expression that multiplies the left and right expressions, returning it as an Expr.
//
// The parameter 'other' can be a numeric constant or a numeric [Expression].
Multiply(other any) Expression
// Divide creates an expression that divides the left expression by the right expression, returning it as an Expr.
//
// The parameter 'other' can be a numeric constant or a numeric [Expression].
Divide(other any) Expression
// Abs creates an expression that is the absolute value of the input field or expression.
Abs() Expression
// Floor creates an expression that is the largest integer that isn't less than the input field or expression.
Floor() Expression
// Ceil creates an expression that is the smallest integer that isn't less than the input field or expression.
Ceil() Expression
// Exp creates an expression that is the Euler's number e raised to the power of the input field or expression.
Exp() Expression
// Log creates an expression that is logarithm of the left expression to base as the right expression, returning it as an Expr.
//
// The parameter 'other' can be a numeric constant or a numeric [Expression].
Log(other any) Expression
// Log10 creates an expression that is the base 10 logarithm of the input field or expression.
Log10() Expression
// Ln creates an expression that is the natural logarithm (base e) of the input field or expression.
Ln() Expression
// Mod creates an expression that computes the modulo of the left expression by the right expression, returning it as an Expr.
//
// The parameter 'other' can be a numeric constant or a numeric [Expression].
Mod(other any) Expression
// Pow creates an expression that computes the left expression raised to the power of the right expression, returning it as an Expr.
//
// The parameter 'other' can be a numeric constant or a numeric [Expression].
Pow(other any) Expression
// Round creates an expression that rounds the input field or expression to nearest integer.
Round() Expression
// Sqrt creates an expression that is the square root of the input field or expression.
Sqrt() Expression
// Array operations
// ArrayContains creates a boolean expression that checks if an array contains a specific value.
//
// The parameter 'value' can be a constant (e.g., string, int, bool) or an [Expression].
ArrayContains(value any) BooleanExpression
// ArrayContainsAll creates a boolean expression that checks if an array contains all the specified values.
//
// The parameter 'values' can be a slice of constants (e.g., []string, []int) or an [Expression] that evaluates to an array.
ArrayContainsAll(values any) BooleanExpression
// ArrayContainsAny creates a boolean expression that checks if an array contains any of the specified values.
//
// The parameter 'values' can be a slice of constants (e.g., []string, []int) or an [Expression] that evaluates to an array.
ArrayContainsAny(values any) BooleanExpression
// ArrayLength creates an expression that calculates the length of an array.
ArrayLength() Expression
// EqualAny creates a boolean expression that checks if the expression is equal to any of the specified values.
//
// The parameter 'values' can be a slice of constants (e.g., []string, []int) or an [Expression] that evaluates to an array.
EqualAny(values any) BooleanExpression
// NotEqualAny creates a boolean expression that checks if the expression is not equal to any of the specified values.
//
// The parameter 'values' can be a slice of constants (e.g., []string, []int) or an [Expression] that evaluates to an array.
NotEqualAny(values any) BooleanExpression
// ArrayGet creates an expression that retrieves an element from an array at a specified index.
//
// The parameter 'offset' is the 0-based index of the element to retrieve.
// It can be an integer constant or an [Expression] that evaluates to an integer.
ArrayGet(offset any) Expression
// ArrayReverse creates an expression that reverses the order of elements in an array.
ArrayReverse() Expression
// ArrayConcat creates an expression that concatenates multiple arrays into a single array.
//
// The parameter 'otherArrays' can be a mix of array constants (e.g., []string, []int) or [Expression]s that evaluate to arrays.
ArrayConcat(otherArrays ...any) Expression
// ArraySum creates an expression that calculates the sum of all elements in a numeric array.
ArraySum() Expression
// ArrayMaximum creates an expression that finds the maximum element in a numeric array.
ArrayMaximum() Expression
// ArrayMinimum creates an expression that finds the minimum element in a numeric array.
ArrayMinimum() Expression
// Timestamp operations
// TimestampAdd creates an expression that adds a specified amount of time to a timestamp.
//
// The parameter 'unit' can be a string constant (e.g., "day") or an [Expression] that evaluates to a valid unit string.
// Valid units include "microsecond", "millisecond", "second", "minute", "hour" and "day".
// The parameter 'amount' can be an integer constant or an [Expression] that evaluates to an integer.
TimestampAdd(unit, amount any) Expression
// TimestampSubtract creates an expression that subtracts a specified amount of time from a timestamp.
//
// The parameter 'unit' can be a string constant (e.g., "hour") or an [Expression] that evaluates to a valid unit string.
// Valid units include "microsecond", "millisecond", "second", "minute", "hour" and "day".
// The parameter 'amount' can be an integer constant or an [Expression] that evaluates to an integer.
TimestampSubtract(unit, amount any) Expression
// TimestampTruncate creates an expression that truncates a timestamp to a specified granularity.
//
// The parameter 'granularity' can be a string constant (e.g., "month") or an [Expression] that evaluates to a valid granularity string.
// Valid values are "microsecond", "millisecond", "second", "minute", "hour", "day", "week", "week(monday)", "week(tuesday)",
// "week(wednesday)", "week(thursday)", "week(friday)", "week(saturday)", "week(sunday)", "isoweek", "month", "quarter", "year", and "isoyear".
TimestampTruncate(granularity any) Expression
// TimestampTruncateWithTimezone creates an expression that truncates a timestamp to a specified granularity in a given timezone.
//
// The parameter 'granularity' can be a string constant (e.g., "week") or an [Expression] that evaluates to a valid granularity string.
// Valid values are "microsecond", "millisecond", "second", "minute", "hour", "day", "week", "week(monday)", "week(tuesday)",
// "week(wednesday)", "week(thursday)", "week(friday)", "week(saturday)", "week(sunday)", "isoweek", "month", "quarter", "year", and "isoyear".
// The parameter 'timezone' can be a string constant (e.g., "America/Los_Angeles") or an [Expression] that evaluates to a valid timezone string.
// Valid values are from the TZ database or in the format "Etc/GMT-1".
TimestampTruncateWithTimezone(granularity any, timezone string) Expression
// TimestampToUnixMicros creates an expression that converts a timestamp expression to the number of microseconds since
// the Unix epoch (1970-01-01 00:00:00 UTC).
TimestampToUnixMicros() Expression
// TimestampToUnixMillis creates an expression that converts a timestamp expression to the number of milliseconds since
// the Unix epoch (1970-01-01 00:00:00 UTC).
TimestampToUnixMillis() Expression
// TimestampToUnixSeconds creates an expression that converts a timestamp expression to the number of seconds since
// the Unix epoch (1970-01-01 00:00:00 UTC).
TimestampToUnixSeconds() Expression
// UnixMicrosToTimestamp creates an expression that converts a Unix timestamp in microseconds to a Firestore timestamp.
UnixMicrosToTimestamp() Expression
// UnixMillisToTimestamp creates an expression that converts a Unix timestamp in milliseconds to a Firestore timestamp.
UnixMillisToTimestamp() Expression
// UnixSecondsToTimestamp creates an expression that converts a Unix timestamp in seconds to a Firestore timestamp.
UnixSecondsToTimestamp() Expression
// Comparison operations
// Equal creates a boolean expression that checks if the expression is equal to the other value.
//
// The parameter 'other' can be a constant (e.g., string, int, bool) or an [Expression].
Equal(other any) BooleanExpression
// NotEqual creates a boolean expression that checks if the expression is not equal to the other value.
//
// The parameter 'other' can be a constant (e.g., string, int, bool) or an [Expression].
NotEqual(other any) BooleanExpression
// GreaterThan creates a boolean expression that checks if the expression is greater than the other value.
//
// The parameter 'other' can be a constant (e.g., string, int, bool) or an [Expression].
GreaterThan(other any) BooleanExpression
// GreaterThanOrEqual creates a boolean expression that checks if the expression is greater than or equal to the other value.
//
// The parameter 'other' can be a constant (e.g., string, int, bool) or an [Expression].
GreaterThanOrEqual(other any) BooleanExpression
// LessThan creates a boolean expression that checks if the expression is less than the other value.
//
// The parameter 'other' can be a constant (e.g., string, int, bool) or an [Expression].
LessThan(other any) BooleanExpression
// LessThanOrEqual creates a boolean expression that checks if the expression is less than or equal to the other value.
//
// The parameter 'other' can be a constant (e.g., string, int, bool) or an [Expression].
LessThanOrEqual(other any) BooleanExpression
// General functions
// Length creates an expression that calculates the length of string, array, map or vector.
Length() Expression
// Reverse creates an expression that reverses a string, or array.
Reverse() Expression
// Concat creates an expression that concatenates expressions together.
//
// The parameter 'others' can be a list of constants (e.g., string, int) or [Expression].
Concat(others ...any) Expression
// Key functions
// GetCollectionID creates an expression that returns the ID of the collection that contains the document.
GetCollectionID() Expression
// GetDocumentID creates an expression that returns the ID of the document.
GetDocumentID() Expression
// Logical functions
// IfError creates an expression that evaluates and returns the receiver expression if it does not produce an error;
// otherwise, it evaluates and returns `catchExprOrValue`.
//
// The parameter 'catchExprOrValue' is the expression or value to return if the receiver expression errors.
IfError(catchExprOrValue any) Expression
// IfAbsent creates an expression that returns a default value if an expression evaluates to an absent value.
//
// The parameter 'catchExprOrValue' is the value to return if the expression is absent.
// It can be a constant or an [Expression].
IfAbsent(catchExprOrValue any) Expression
// Object functions
// MapGet creates an expression that accesses a value from a map (object) field using the provided key.
//
// The parameter 'strOrExprkey' is the key to access in the map.
// It can be a string constant or an [Expression] that evaluates to a string.
MapGet(strOrExprkey any) Expression
// MapMerge creates an expression that merges multiple maps into a single map.
// If multiple maps have the same key, the later value is used.
//
// The parameter 'secondMap' is an [Expression] representing the second map.
// The parameter 'otherMaps' is a list of additional [Expression]s representing maps to merge.
MapMerge(secondMap Expression, otherMaps ...Expression) Expression
// MapRemove creates an expression that removes a key from a map.
//
// The parameter 'strOrExprkey' is the key to remove from the map.
// It can be a string constant or an [Expression] that evaluates to a string.
MapRemove(strOrExprkey any) Expression
// Aggregators
// Sum creates an aggregate function that calculates the sum of the expression.
Sum() AggregateFunction
// Average creates an aggregate function that calculates the average of the expression.
Average() AggregateFunction
// Count creates an aggregate function that counts the number of documents.
Count() AggregateFunction
// String functions
// ByteLength creates an expression that calculates the length of a string represented by a field or [Expression] in UTF-8
// bytes.
ByteLength() Expression
// CharLength creates an expression that calculates the character length of a string field or expression in UTF8.
CharLength() Expression
// EndsWith creates a boolean expression that checks if the string expression ends with the specified suffix.
//
// The parameter 'suffix' can be a string constant or an [Expression] that evaluates to a string.
EndsWith(suffix any) BooleanExpression
// Like creates a boolean expression that checks if the string expression matches the specified pattern.
//
// The parameter 'suffix' can be a string constant or an [Expression] that evaluates to a string.
Like(suffix any) BooleanExpression
// RegexContains creates a boolean expression that checks if the string expression contains a match for the specified regex pattern.
//
// The parameter 'pattern' can be a string constant or an [Expression] that evaluates to a string.
RegexContains(pattern any) BooleanExpression
// RegexMatch creates a boolean expression that checks if the string expression matches the specified regex pattern.
//
// The parameter 'pattern' can be a string constant or an [Expression] that evaluates to a string.
RegexMatch(pattern any) BooleanExpression
// StartsWith creates a boolean expression that checks if the string expression starts with the specified prefix.
//
// The parameter 'prefix' can be a string constant or an [Expression] that evaluates to a string.
StartsWith(prefix any) BooleanExpression
// StringConcat creates an expression that concatenates multiple strings into a single string.
//
// The parameter 'otherStrings' can be a mix of string constants or [Expression]s that evaluate to strings.
StringConcat(otherStrings ...any) Expression
// StringContains creates a boolean expression that checks if the string expression contains the specified substring.
//
// The parameter 'substring' can be a string constant or an [Expression] that evaluates to a string.
StringContains(substring any) BooleanExpression
// StringReverse creates an expression that reverses a string.
StringReverse() Expression
// Join creates an expression that joins the elements of a string array into a single string.
//
// The parameter 'delimiter' can be a string constant or an [Expression] that evaluates to a string.
Join(delimiter any) Expression
// Substring creates an expression that returns a substring of a string.
//
// The parameter 'index' is the starting index of the substring.
// It can be an integer constant or an [Expression] that evaluates to an integer.
// The parameter 'offset' is the length of the substring.
// It can be an integer constant or an [Expression] that evaluates to an integer.
Substring(index, offset any) Expression
// ToLower creates an expression that converts a string to lowercase.
ToLower() Expression
// ToUpper creates an expression that converts a string to uppercase.
ToUpper() Expression
// Trim creates an expression that removes leading and trailing whitespace from a string.
Trim() Expression
// Split creates an expression that splits a string by a delimiter.
//
// The parameter 'delimiter' can be a string constant or an [Expression] that evaluates to a string.
Split(delimiter any) Expression
// Type creates an expression that returns the type of the expression.
Type() Expression
// Vector functions
// CosineDistance creates an expression that calculates the cosine distance between two vectors.
//
// The parameter 'other' can be [Vector32], [Vector64], []float32, []float64 or an [Expression] that evaluates to a vector.
CosineDistance(other any) Expression
// DotProduct creates an expression that calculates the dot product of two vectors.
//
// The parameter 'other' can be [Vector32], [Vector64], []float32, []float64 or an [Expression] that evaluates to a vector.
DotProduct(other any) Expression
// EuclideanDistance creates an expression that calculates the euclidean distance between two vectors.
//
// The parameter 'other' can be [Vector32], [Vector64], []float32, []float64 or an [Expression] that evaluates to a vector.
EuclideanDistance(other any) Expression
// VectorLength creates an expression that calculates the length of a vector.
VectorLength() Expression
// Ordering
// Ascending creates an ordering expression for ascending order.
Ascending() Ordering
// Descending creates an ordering expression for descending order.
Descending() Ordering
// As assigns an alias to an expression.
// Aliases are useful for renaming fields in the output of a stage.
As(alias string) Selectable
// contains filtered or unexported methods
}Expression represents an expression that can be evaluated to a value within the execution of a [Pipeline].
Expressions are the building blocks for creating complex queries and transformations in Firestore pipelines. They can represent:
- Field references: Access values from document fields.
- Literals: Represent constant values (strings, numbers, booleans).
- Function calls: Apply functions to one or more expressions.
- Aggregations: Calculate aggregate values (e.g., sum, average) using [AggregateFunction] instances.
The [Expression] interface provides a fluent API for building expressions. You can chain together method calls to create complex expressions.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Abs
func Abs(numericExprOrFieldPath any) ExpressionAbs creates an expression that is the absolute value of the input field or expression.
- numericExprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that returns a number when evaluated.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Add
func Add(left, right any) ExpressionAdd creates an expression that adds two expressions together, returning it as an Expr.
- left can be a field path string, [FieldPath] or [Expression].
- right can be a numeric constant or a numeric [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Array
func Array(elements any) ExpressionArray creates an expression that represents a Firestore array.
- elements can be any number of values or expressions that will form the elements of the array.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArrayConcat
func ArrayConcat(exprOrFieldPath any, otherArrays any) ExpressionArrayConcat creates an expression that concatenates multiple arrays into a single array.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to an array.
- otherArrays are the other arrays to concatenate.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArrayFromSlice
func ArrayFromSlice(elements []T) ExpressionArrayFromSlice creates a new array expression from a slice of elements.
This function is necessary for creating an array from an existing typed slice (e.g., []int),
as the [Array] function (which takes variadic arguments) cannot directly accept a typed slice
using the spread operator (...). It handles the conversion of each element to any internally.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArrayGet
func ArrayGet(exprOrFieldPath any, offset any) ExpressionArrayGet creates an expression that retrieves an element from an array at a specified index.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to an array.
- offset is the 0-based index of the element to retrieve.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArrayLength
func ArrayLength(exprOrFieldPath any) ExpressionArrayLength creates an expression that calculates the length of an array.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to an array.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArrayMaximum
func ArrayMaximum(exprOrFieldPath any) ExpressionArrayMaximum creates an expression that finds the maximum element in a numeric array.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a numeric array.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArrayMinimum
func ArrayMinimum(exprOrFieldPath any) ExpressionArrayMinimum creates an expression that finds the minimum element in a numeric array.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a numeric array.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArrayReverse
func ArrayReverse(exprOrFieldPath any) ExpressionArrayReverse creates an expression that reverses the order of elements in an array.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to an array.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ArraySum
func ArraySum(exprOrFieldPath any) ExpressionArraySum creates an expression that calculates the sum of all elements in a numeric array.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a numeric array.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ByteLength
func ByteLength(exprOrFieldPath any) ExpressionByteLength creates an expression that calculates the length of a string represented by a field or [Expression] in UTF-8 bytes.
- exprOrFieldPath can be a field path string, [FieldPath] or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Ceil
func Ceil(numericExprOrFieldPath any) ExpressionCeil creates an expression that is the smallest integer that isn't less than the input field or expression.
- numericExprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that returns a number when evaluated.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func CharLength
func CharLength(exprOrFieldPath any) ExpressionCharLength creates an expression that calculates the character length of a string field or expression in UTF8.
- exprOrFieldPath can be a field path string, [FieldPath] or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Concat
func Concat(exprOrField any, others any) ExpressionConcat creates an expression that concatenates expressions together.
- exprOrField can be a field path string, [FieldPath] or an [Expression].
- others can be a list of constants or [Expression].
Example:
// Concat the 'name' field with a constant string.
Concat("name", "-suffix")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Conditional
func Conditional(condition BooleanExpression, thenVal, elseVal any) ExpressionConditional creates an expression that evaluates a condition and returns one of two expressions.
- condition is the boolean expression to evaluate.
- thenVal is the expression to return if the condition is true.
- elseVal is the expression to return if the condition is false.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ConstantOf
func ConstantOf(value any) ExpressionConstantOf creates a new constant [Expression] from a Go value.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ConstantOfNull
func ConstantOfNull() ExpressionConstantOfNull creates a new constant [Expression] representing a null value.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ConstantOfVector32
func ConstantOfVector32(value []float32) ExpressionConstantOfVector32 creates a new [Vector32] constant [Expression] from a slice of float32s.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ConstantOfVector64
func ConstantOfVector64(value []float64) ExpressionConstantOfVector64 creates a new [Vector64] constant [Expression] from a slice of float64s.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func CosineDistance
func CosineDistance(vector1 any, vector2 any) ExpressionCosineDistance creates an expression that calculates the cosine distance between two vectors.
- vector1 can be a field path string, [FieldPath] or [Expression].
- vector2 can be [Vector32], [Vector64], []float32, []float64 or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func CurrentTimestamp
func CurrentTimestamp() ExpressionCurrentTimestamp creates an expression that returns the current timestamp.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Divide
func Divide(left, right any) ExpressionDivide creates an expression that divides the left expression by the right expression, returning it as an Expr.
- left can be a field path string, [FieldPath] or [Expression].
- right can be a constant or an [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func DotProduct
func DotProduct(vector1 any, vector2 any) ExpressionDotProduct creates an expression that calculates the dot product of two vectors.
- vector1 can be a field path string, [FieldPath] or [Expression].
- vector2 can be [Vector32], [Vector64], []float32, []float64 or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func EuclideanDistance
func EuclideanDistance(vector1 any, vector2 any) ExpressionEuclideanDistance creates an expression that calculates the euclidean distance between two vectors.
- vector1 can be a field path string, [FieldPath] or [Expression].
- vector2 can be [Vector32], [Vector64], []float32, []float64 or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Exp
func Exp(numericExprOrFieldPath any) ExpressionExp creates an expression that is the Euler's number e raised to the power of the input field or expression.
- numericExprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that returns a number when evaluated.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func FieldOf
func FieldOf(path T) ExpressionFieldOf creates a new field [Expression] from a dot separated field path string or [FieldPath].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Floor
func Floor(numericExprOrFieldPath any) ExpressionFloor creates an expression that is the largest integer that isn't less than the input field or expression.
- numericExprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that returns a number when evaluated.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func GetCollectionID
func GetCollectionID(exprOrField any) ExpressionGetCollectionID creates an expression that returns the ID of the collection that contains the document.
- exprOrField can be a field path string, [FieldPath] or an [Expression] that evaluates to a field path.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func GetDocumentID
func GetDocumentID(exprStringOrDocRef any) ExpressionGetDocumentID creates an expression that returns the ID of the document.
- exprStringOrDocRef can be a string, a [DocumentRef], or an [Expression] that evaluates to a document reference.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func IfAbsent
func IfAbsent(exprOrField any, elseValue any) ExpressionIfAbsent creates an expression that returns a default value if an expression evaluates to an absent value.
- exprOrField can be a field path string, [FieldPath] or an [Expression].
- elseValue is the value to return if the expression is absent.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func IfError
func IfError(tryExpr Expression, catchExprOrValue any) ExpressionIfError creates an expression that evaluates and returns tryExpr if it does not produce an error;
otherwise, it evaluates and returns catchExprOrValue. It returns a new [Expression] representing
the if_error operation.
- tryExpr is the expression to try.
- catchExprOrValue is the expression or value to return if
tryExprerrors.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Join
func Join(exprOrFieldPath any, delimiter any) ExpressionJoin creates an expression that joins the elements of a string array into a single string.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a string array.
- delimiter is the string to use as a separator between elements.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Length
func Length(exprOrField any) ExpressionLength creates an expression that calculates the length of string, array, map or vector.
- exprOrField can be a field path string, [FieldPath] or an [Expression] that returns a string, array, map or vector when evaluated.
Example:
// Length of the 'name' field.
Length("name")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Ln
func Ln(numericExprOrFieldPath any) ExpressionLn creates an expression that is the natural logarithm (base e) of the input field or expression.
- numericExprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that returns a number when evaluated.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Log
func Log(left, right any) ExpressionLog creates an expression that is logarithm of the left expression to base as the right expression, returning it as an Expr.
- left can be a field path string, [FieldPath] or [Expression].
- right can be a constant or an [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Log10
func Log10(numericExprOrFieldPath any) ExpressionLog10 creates an expression that is the base 10 logarithm of the input field or expression.
- numericExprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that returns a number when evaluated.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func LogicalMaximum
func LogicalMaximum(exprOrField any, others any) ExpressionLogicalMaximum creates an expression that evaluates to the maximum value in a list of expressions.
- exprOrField can be a field path string, [FieldPath] or an [Expression].
- others can be a list of constants or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func LogicalMinimum
func LogicalMinimum(exprOrField any, others any) ExpressionLogicalMinimum creates an expression that evaluates to the minimum value in a list of expressions.
- exprOrField can be a field path string, [FieldPath] or an [Expression].
- others can be a list of constants or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Map
func Map(elements map[string]any) ExpressionMap creates an expression that creates a Firestore map value from an input object.
- elements: The input map to evaluate in the expression.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func MapGet
func MapGet(exprOrField any, strOrExprkey any) ExpressionMapGet creates an expression that accesses a value from a map (object) field using the provided key.
- exprOrField: The expression representing the map.
- strOrExprkey: The key to access in the map.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func MapMerge
func MapMerge(exprOrField any, secondMap Expression, otherMaps ...Expression) ExpressionMapMerge creates an expression that merges multiple maps into a single map. If multiple maps have the same key, the later value is used.
- exprOrField: First map expression that will be merged.
- secondMap: Second map expression that will be merged.
- otherMaps: Additional maps to merge.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func MapRemove
func MapRemove(exprOrField any, strOrExprkey any) ExpressionMapRemove creates an expression that removes a key from a map.
- exprOrField: The expression representing the map.
- strOrExprkey: The key to remove from the map.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Mod
func Mod(left, right any) ExpressionMod creates an expression that computes the modulo of the left expression by the right expression, returning it as an Expr.
- left can be a field path string, [FieldPath] or [Expression].
- right can be a constant or an [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Multiply
func Multiply(left, right any) ExpressionMultiply creates an expression that multiplies the left and right expressions, returning it as an Expr.
- left can be a field path string, [FieldPath] or [Expression].
- right can be a constant or an [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Pow
func Pow(left, right any) ExpressionPow creates an expression that computes the left expression raised to the power of the right expression, returning it as an Expr.
- left can be a field path string, [FieldPath] or [Expression].
- right can be a constant or an [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Reverse
func Reverse(exprOrField any) ExpressionReverse creates an expression that reverses a string, or array.
- exprOrField can be a field path string, [FieldPath] or an [Expression] that returns a string, or array when evaluated.
Example:
// Reverse the 'name' field.
Reverse("name")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Round
func Round(numericExprOrFieldPath any) ExpressionRound creates an expression that rounds the input field or expression to nearest integer.
- numericExprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that returns a number when evaluated.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Split
func Split(exprOrFieldPath any, delimiter any) ExpressionSplit creates an expression that splits a string by a delimiter.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a string.
- delimiter is the string to use to split by.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Sqrt
func Sqrt(numericExprOrFieldPath any) ExpressionSqrt creates an expression that is the square root of the input field or expression.
- numericExprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that returns a number when evaluated.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func StringConcat
func StringConcat(exprOrFieldPath any, otherStrings any) ExpressionStringConcat creates an expression that concatenates multiple strings into a single string.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a string.
- otherStrings are the other strings to concatenate.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func StringReverse
func StringReverse(exprOrFieldPath any) ExpressionStringReverse creates an expression that reverses a string.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a string.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Substring
func Substring(exprOrFieldPath any, index any, offset any) ExpressionSubstring creates an expression that returns a substring of a string.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a string.
- index is the starting index of the substring.
- offset is the length of the substring.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Subtract
func Subtract(left, right any) ExpressionSubtract creates an expression that subtracts the right expression from the left expression, returning it as an Expr.
- left can be a field path string, [FieldPath] or [Expression].
- right can be a constant or an [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func TimestampAdd
func TimestampAdd(timestamp, unit, amount any) ExpressionTimestampAdd creates an expression that adds a specified amount of time to a timestamp.
- timestamp can be a field path string, [FieldPath] or [Expression].
- unit can be a string or an [Expression]. Valid units include "microsecond", "millisecond", "second", "minute", "hour" and "day".
- amount can be an int, int32, int64 or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func TimestampSubtract
func TimestampSubtract(timestamp, unit, amount any) ExpressionTimestampSubtract creates an expression that subtracts a specified amount of time from a timestamp.
- timestamp can be a field path string, [FieldPath] or [Expression].
- unit can be a string or an [Expression]. Valid units include "microsecond", "millisecond", "second", "minute", "hour" and "day".
- amount can be an int, int32, int64 or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func TimestampToUnixMicros
func TimestampToUnixMicros(timestamp any) ExpressionTimestampToUnixMicros creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
- timestamp can be a field path string, [FieldPath] or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func TimestampToUnixMillis
func TimestampToUnixMillis(timestamp any) ExpressionTimestampToUnixMillis creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
- timestamp can be a field path string, [FieldPath] or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func TimestampToUnixSeconds
func TimestampToUnixSeconds(timestamp any) ExpressionTimestampToUnixSeconds creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).
- timestamp can be a field path string, [FieldPath] or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func TimestampTruncate
func TimestampTruncate(timestamp, granularity any) ExpressionTimestampTruncate creates an expression that truncates a timestamp to a specified granularity.
- timestamp can be a field path string, [FieldPath] or [Expression].
- granularity can be a string or an [Expression]. Valid values are "microsecond", "millisecond", "second", "minute", "hour", "day", "week", "week(monday)", "week(tuesday)", "week(wednesday)", "week(thursday)", "week(friday)", "week(saturday)", "week(sunday)", "isoweek", "month", "quarter", "year", and "isoyear".
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func TimestampTruncateWithTimezone
func TimestampTruncateWithTimezone(timestamp, granularity any, timezone string) ExpressionTimestampTruncateWithTimezone creates an expression that truncates a timestamp to a specified granularity in a given timezone.
- timestamp can be a field path string, [FieldPath] or [Expression].
- granularity can be a string or an [Expression]. Valid values are "microsecond", "millisecond", "second", "minute", "hour", "day", "week", "week(monday)", "week(tuesday)", "week(wednesday)", "week(thursday)", "week(friday)", "week(saturday)", "week(sunday)", "isoweek", "month", "quarter", "year", and "isoyear".
- timezone can be a string or an [Expression]. Valid values are from the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1".
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ToLower
func ToLower(exprOrFieldPath any) ExpressionToLower creates an expression that converts a string to lowercase.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a string.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func ToUpper
func ToUpper(exprOrFieldPath any) ExpressionToUpper creates an expression that converts a string to uppercase.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a string.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Trim
func Trim(exprOrFieldPath any) ExpressionTrim creates an expression that removes leading and trailing whitespace from a string.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression] that evaluates to a string.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Type
func Type(exprOrFieldPath any) ExpressionType creates an expression that returns the type of the expression.
- exprOrFieldPath can be a field path string, [FieldPath] or an [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func UnixMicrosToTimestamp
func UnixMicrosToTimestamp(micros any) ExpressionUnixMicrosToTimestamp creates an expression that converts a Unix timestamp in microseconds to a Firestore timestamp.
- micros can be a field path string, [FieldPath] or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func UnixMillisToTimestamp
func UnixMillisToTimestamp(millis any) ExpressionUnixMillisToTimestamp creates an expression that converts a Unix timestamp in milliseconds to a Firestore timestamp.
- millis can be a field path string, [FieldPath] or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func UnixSecondsToTimestamp
func UnixSecondsToTimestamp(seconds any) ExpressionUnixSecondsToTimestamp creates an expression that converts a Unix timestamp in seconds to a Firestore timestamp.
- seconds can be a field path string, [FieldPath] or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func VectorLength
func VectorLength(exprOrFieldPath any) ExpressionVectorLength creates an expression that calculates the length of a vector.
- exprOrFieldPath can be a field path string, [FieldPath] or [Expression].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
FieldNotFoundError
type FieldNotFoundError struct {
Path string
}FieldNotFoundError is returned by DocumentSnapshot.DataAt and DocumentSnapshot.DataAtPath when the given field does not exist.
func (*FieldNotFoundError) Error
func (e *FieldNotFoundError) Error() stringFieldPath
type FieldPath []stringA FieldPath is a non-empty sequence of non-empty fields that reference a value.
A FieldPath value should only be necessary if one of the field names contains one of the runes ".˜*/[]". Most methods accept a simpler form of field path as a string in which the individual fields are separated by dots. For example,
[]string{"a", "b"}
is equivalent to the string form
"a.b"
but
[]string{"*"}
has no equivalent string form.
FindNearestOptions
type FindNearestOptions struct {
// DistanceThreshold specifies a threshold for which no less similar documents
// will be returned. The behavior of the specified [DistanceMeasure] will
// affect the meaning of the distance threshold. Since [DistanceMeasureDotProduct]
// distances increase when the vectors are more similar, the comparison is inverted.
// For [DistanceMeasureEuclidean], [DistanceMeasureCosine]: WHERE distance <= distancethreshold="" for="" [distancemeasuredotproduct]:="" where="" distance="">= distance_threshold
DistanceThreshold *float64
// DistanceResultField specifies name of the document field to output the result of
// the vector distance calculation.
// If the field already exists in the document, its value get overwritten with the distance calculation.
// Otherwise, a new field gets added to the document.
DistanceResultField string
}FindNearestOptions are options for a FindNearest vector query.
FunctionExpression
type FunctionExpression interface {
Expression
// contains filtered or unexported methods
}FunctionExpression represents Firestore [Pipeline] functions, which can be evaluated within pipeline execution.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
OrFilter
type OrFilter struct {
Filters []EntityFilter
}OrFilter represents a union of two or more filters.
Ordering
type Ordering struct {
Expr Expression
Direction OrderingDirection
}Ordering specifies the field and direction for sorting.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Ascending
func Ascending(expr Expression) OrderingAscending creates an Ordering for ascending sort direction.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func Descending
func Descending(expr Expression) OrderingDescending creates an Ordering for descending sort direction.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
OrderingDirection
type OrderingDirection stringOrderingDirection is the sort direction for pipeline result ordering.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
OrderingAsc, OrderingDesc
const (
// OrderingAsc sorts results from smallest to largest.
OrderingAsc OrderingDirection = OrderingDirection("ascending")
// OrderingDesc sorts results from largest to smallest.
OrderingDesc OrderingDirection = OrderingDirection("descending")
)Pipeline
type Pipeline struct {
// contains filtered or unexported fields
}Pipeline class provides a flexible and expressive framework for building complex data transformation and query pipelines for Firestore.
A pipeline takes data sources, such as Firestore collections or collection groups, and applies a series of stages that are chained together. Each stage takes the output from the previous stage (or the data source) and produces an output for the next stage (or as the final output of the pipeline).
Expressions can be used within each stages to filter and transform data through the stage.
NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline. Instead, Firestore only guarantees that the result is the same as if the chained stages were executed in order.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) AddFields
func (p *Pipeline) AddFields(selectables ...Selectable) *PipelineAddFields adds new fields to outputs from previous stages.
This stage allows you to compute values on-the-fly based on existing data from previous stages or constants. You can use this to create new fields or overwrite existing ones (if there is name overlaps).
The added fields are defined using [Selectable]s
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Aggregate
func (p *Pipeline) Aggregate(accumulators ...*AliasedAggregate) *PipelineAggregate performs aggregation operations on the documents from previous stages. This stage allows you to calculate aggregate values over a set of documents. You define the aggregations to perform using [AliasedAggregate] expressions which are typically results of calling [AggregateFunction.As] on [AggregateFunction] instances. Example:
client.Pipeline().Collection("users").
Aggregate(Sum("age").As("age_sum"))
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) AggregateWithSpec
func (p *Pipeline) AggregateWithSpec(spec *AggregateSpec) *PipelineAggregateWithSpec performs optionally grouped aggregation operations on the documents from previous stages. This stage allows you to calculate aggregate values over a set of documents, optionally grouped by one or more fields or functions. You can specify:
- Grouping Fields or Functions: One or more fields or functions to group the documents by. For each distinct combination of values in these fields, a separate group is created. If no grouping fields are provided, a single group containing all documents is used. Not specifying groups is the same as putting the entire inputs into one group.
- Accumulator targets: One or more accumulation operations to perform within each group. These are defined using [AliasedAggregate] expressions which are typically results of calling [AggregateFunction.As] on [AggregateFunction] instances. Each aggregation calculates a value (e.g., sum, average, count) based on the documents within its group.
Example:
// Calculate the average rating for each genre.
client.Pipeline().Collection("books").
AggregateWithSpec(NewAggregateSpec(Average("rating").As("avg_rating")).WithGroups("genre"))
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Distinct
Distinct removes duplicate documents from the outputs of previous stages.
You can optionally specify fields or [Selectable] expressions to determine distinctness. If no fields are specified, the entire document is used to determine distinctness.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Execute
func (p *Pipeline) Execute(ctx context.Context) *PipelineSnapshotExecute executes the pipeline and returns a snapshot of the results.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) FindNearest
func (p *Pipeline) FindNearest(vectorField any, queryVector any, measure PipelineDistanceMeasure, options *PipelineFindNearestOptions) *PipelineFindNearest performs vector distance (similarity) search with given parameters to the stage inputs.
This stage adds a "nearest neighbor search" capability to your pipelines. Given a field that stores vectors and a target vector, this stage will identify and return the inputs whose vector field is closest to the target vector.
The vectorField can be a string, a FieldPath or an Expr. The queryVector can be Vector32, Vector64, []float32, or []float64.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Limit
Limit limits the maximum number of documents returned by previous stages.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Offset
Offset skips the first offset number of documents from the results of previous stages.
This stage is useful for implementing pagination in your pipelines, allowing you to retrieve results in chunks. It is typically used in conjunction with [*Pipeline.Limit] to control the size of each page.
Example: Retrieve the second page of 20 results
client.Pipeline().Collection("books").
.Offset(20) // Skip the first 20 results
.Limit(20) // Take the next 20 results
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) RawStage
RawStage adds a generic stage to the pipeline. This method provides a flexible way to extend the pipeline's functionality by adding custom stages.
Example:
// Assume we don't have a built-in "where" stage
client.Pipeline().Collection("books").
RawStage(
NewRawStage("where").
WithArguments(
LessThan(FieldOf("published"), 1900),
),
).
Select("title", "author")
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) RemoveFields
RemoveFields removes fields from outputs from previous stages.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) ReplaceWith
ReplaceWith fully overwrites all fields in a document with those coming from a nested map.
This stage allows you to emit a map value as a document. Each key of the map becomes a field on the document that contains the corresponding value.
Example:
// Input: { "name": "John Doe Jr.", "parents": { "father": "John Doe Sr.", "mother": "Jane Doe" } }
// Emit parents as document.
client.Pipeline().Collection("people").ReplaceWith("parents")
// Output: { "father": "John Doe Sr.", "mother": "Jane Doe" }
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Sample
func (p *Pipeline) Sample(spec *SampleSpec) *PipelineSample performs a pseudo-random sampling of the documents from the previous stage.
This stage will filter documents pseudo-randomly. The behavior is defined by the SampleSpec. Use SampleByDocuments or SampleByPercentage to create a SampleSpec.
Example:
// Sample 10 books, if available.
client.Pipeline().Collection("books").Sample(SampleByDocuments(10))
// Sample 50% of books.
client.Pipeline().Collection("books").Sample(&SampleSpec{Size: 0.5, Mode: SampleModePercent})
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Select
Select selects or creates a set of fields from the outputs of previous stages. The selected fields are defined using field path string, [FieldPath] or [Selectable] expressions. [Selectable] expressions can be:
- Field: References an existing field.
- Function: Represents the result of a function with an assigned alias name using [FunctionExpression.As].
Example:
client.Pipeline().Collection("users").Select("info.email")
client.Pipeline().Collection("users").Select(FieldOf("info.email"))
client.Pipeline().Collection("users").Select(FieldOf([]string{"info", "email"}))
client.Pipeline().Collection("users").Select(FieldOf([]string{"info", "email"}))
client.Pipeline().Collection("users").Select(Add("age", 5).As("agePlus5"))
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Sort
Sort sorts the documents by the given fields and directions.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Union
Union performs union of all documents from two pipelines, including duplicates.
This stage will pass through documents from previous stage, and also pass through documents from previous stage of the other [*Pipeline] given in parameter. The order of documents emitted from this stage is undefined.
Example:
// Emit documents from books collection and magazines collection.
client.Pipeline().Collection("books").
Union(client.Pipeline().Collection("magazines"))
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Unnest
func (p *Pipeline) Unnest(field Selectable, opts *UnnestOptions) *PipelineUnnest produces a document for each element in an array field.
For each input document, this stage outputs zero or more documents.
Each output document is a copy of the input document, but the array field is replaced by an element from the array.
The field parameter specifies the array field to unnest. It can be a string representing the field path or a [Selectable] expression.
The alias of the selectable will be used as the new field name.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) UnnestWithAlias
func (p *Pipeline) UnnestWithAlias(fieldpath any, alias string, opts *UnnestOptions) *PipelineUnnestWithAlias produces a document for each element in an array field, with a specified alias for the unnested field. It can optionally take UnnestOptions.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) Where
func (p *Pipeline) Where(condition BooleanExpression) *PipelineWhere filters the documents from previous stages to only include those matching the specified [BooleanExpression].
This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) WithExecuteOptions
func (p *Pipeline) WithExecuteOptions(opts ...ExecuteOption) *PipelineWithExecuteOptions specifies options for executing a pipeline.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*Pipeline) WithReadOptions
func (p *Pipeline) WithReadOptions(opts ...ReadOption) *PipelineWithReadOptions specifies constraints for accessing documents from the database, such as ReadTime.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
PipelineDistanceMeasure
type PipelineDistanceMeasure stringPipelineDistanceMeasure is the distance measure for find_nearest pipeline stage.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
PipelineDistanceMeasureEuclidean, PipelineDistanceMeasureCosine, PipelineDistanceMeasureDotProduct
const (
// PipelineDistanceMeasureEuclidean is used to measures the Euclidean distance between the vectors.
PipelineDistanceMeasureEuclidean PipelineDistanceMeasure = "euclidean"
// PipelineDistanceMeasureCosine compares vectors based on the angle between them.
PipelineDistanceMeasureCosine PipelineDistanceMeasure = "cosine"
// PipelineDistanceMeasureDotProduct is similar to cosine but is affected by the magnitude of the vectors.
PipelineDistanceMeasureDotProduct PipelineDistanceMeasure = "dot_product"
)PipelineFindNearestOptions
PipelineFindNearestOptions are options for a FindNearest pipeline stage.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
PipelineResult
type PipelineResult struct {
// contains filtered or unexported fields
}PipelineResult is a result returned from executing a pipeline.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineResult) CreateTime
func (p *PipelineResult) CreateTime() *time.TimeCreateTime returns the time at which the document was created.
func (*PipelineResult) Data
func (p *PipelineResult) Data() map[string]anyData returns the PipelineResult's fields as a map. It is equivalent to
var m map[string]any
p.DataTo(&m)
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineResult) DataTo
func (p *PipelineResult) DataTo(v any) errorDataTo uses the PipelineResult's fields to populate v, which can be a pointer to a map[string]any or a pointer to a struct. This is similar to [DocumentSnapshot.DataTo]
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineResult) ExecutionTime
func (p *PipelineResult) ExecutionTime() *time.TimeExecutionTime returns the time at which the document(s) were read.
func (*PipelineResult) Exists
func (p *PipelineResult) Exists() boolExists reports whether the PipelineResult represents an document. Even if Exists returns false, the rest of the fields are valid.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineResult) Ref
func (p *PipelineResult) Ref() *DocumentRefRef returns the DocumentRef for this result.
func (*PipelineResult) UpdateTime
func (p *PipelineResult) UpdateTime() *time.TimeUpdateTime returns the time at which the document was last changed.
PipelineResultIterator
type PipelineResultIterator struct {
// contains filtered or unexported fields
}PipelineResultIterator is an iterator over PipelineResults from a pipeline execution.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineResultIterator) GetAll
func (it *PipelineResultIterator) GetAll() ([]*PipelineResult, error)GetAll returns all the documents remaining from the iterator. It is not necessary to call Stop on the iterator after calling GetAll.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineResultIterator) Next
func (it *PipelineResultIterator) Next() (*PipelineResult, error)Next returns the next result. Its second return value is iterator.Done if there are no more results. Once Next returns Done, all subsequent calls will return Done.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineResultIterator) Stop
func (it *PipelineResultIterator) Stop()Stop stops the iterator, freeing its resources. Always call Stop when you are done with a DocumentIterator. It is not safe to call Stop concurrently with Next.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
PipelineSnapshot
type PipelineSnapshot struct {
// contains filtered or unexported fields
}PipelineSnapshot contains zero or more [PipelineResult] objects representing the documents returned by a pipeline query. It provides methods to iterate over the documents and access metadata about the query results.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineSnapshot) ExecutionTime
func (ps *PipelineSnapshot) ExecutionTime() (*time.Time, error)ExecutionTime returns the time at which the pipeline was executed. It is available only after the iterator reaches the end.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineSnapshot) ExplainStats
func (ps *PipelineSnapshot) ExplainStats() *ExplainStatsExplainStats returns stats from query explain. If [WithExplainMode] was set to [ExplainModeExplain] or left unset, then no stats will be available.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineSnapshot) Results
func (ps *PipelineSnapshot) Results() *PipelineResultIteratorResults returns an iterator over the query results.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
PipelineSource
type PipelineSource struct {
// contains filtered or unexported fields
}PipelineSource is a factory for creating Pipeline instances. It is obtained by calling [Client.Pipeline()].
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineSource) Collection
func (ps *PipelineSource) Collection(path string, opts ...CollectionOption) *PipelineCollection creates a new [Pipeline] that operates on the specified Firestore collection.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineSource) CollectionGroup
func (ps *PipelineSource) CollectionGroup(collectionID string, opts ...CollectionGroupOption) *PipelineCollectionGroup creates a new [Pipeline] that operates on all documents in a group of collections that include the given ID, regardless of parent document.
For example, consider: Countries/France/Cities/Paris = {population: 100} Countries/Canada/Cities/Montreal = {population: 90}
CollectionGroup can be used to query across all "Cities" regardless of its parent "Countries".
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineSource) CreateFromAggregationQuery
func (ps *PipelineSource) CreateFromAggregationQuery(query *AggregationQuery) *PipelineCreateFromAggregationQuery creates a new [Pipeline] from the given [AggregationQuery]. Under the hood, this will translate the query semantics (order by document ID, etc.) to an equivalent pipeline.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineSource) CreateFromQuery
func (ps *PipelineSource) CreateFromQuery(query Queryer) *PipelineCreateFromQuery creates a new [Pipeline] from the given [Queryer]. Under the hood, this will translate the query semantics (order by document ID, etc.) to an equivalent pipeline.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineSource) Database
func (ps *PipelineSource) Database() *PipelineDatabase creates a new [Pipeline] that operates on all documents in the Firestore database.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*PipelineSource) Documents
func (ps *PipelineSource) Documents(refs ...*DocumentRef) *PipelineDocuments creates a new [Pipeline] that operates on a specific set of Firestore documents.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
PlanSummary
type PlanSummary struct {
// The indexes selected for the query. For example:
//
// [
// {"query_scope": "Collection", "properties": "(foo ASC, __name__ ASC)"},
// {"query_scope": "Collection", "properties": "(bar ASC, __name__ ASC)"}
// ]
IndexesUsed []*map[string]any
}PlanSummary represents planning phase information for the query.
Precondition
type Precondition interface {
// contains filtered or unexported methods
}A Precondition modifies a Firestore update or delete operation.
Exists
var Exists PreconditionExists is a Precondition that checks for the existence of a resource before writing to it. If the check fails, the write does not occur.
func LastUpdateTime
func LastUpdateTime(t time.Time) PreconditionLastUpdateTime returns a Precondition that checks that a resource must exist and must have last been updated at the given time. If the check fails, the write does not occur.
PropertyFilter
PropertyFilter represents a filter on single property.
Path can be a single field or a dot-separated sequence of fields denoting property path, and must not contain any of the runes "˜*/[]". Operator must be one of "==", "!=", "<", "<=", ">", ">=", "array-contains", "array-contains-any", "in" or "not-in".
PropertyPathFilter
type PropertyPathFilter struct {
Path FieldPath
Operator string
Value interface{}
}PropertyPathFilter represents a filter on single property.
Path can be an array of fields denoting property path. Operator must be one of "==", "!=", "<", "<=", ">", ">=", "array-contains", "array-contains-any", "in" or "not-in".
Query
type Query struct {
// contains filtered or unexported fields
}Query represents a Firestore query.
Query values are immutable. Each Query method creates a new Query; it does not modify the old.
func (Query) Deserialize
Deserialize takes a slice of bytes holding the wire-format message of RunQueryRequest, the underlying proto message used by Queries. It then populates and returns a Query object that can be used to execute that Query.
func (Query) Documents
func (q Query) Documents(ctx context.Context) *DocumentIteratorDocuments returns an iterator over the query's resulting documents.
Examples
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
q := client.Collection("States").Select("pop").
Where("pop", ">", 10).
OrderBy("pop", firestore.Desc).
Limit(10)
iter1 := q.Documents(ctx)
_ = iter1 // TODO: Use iter1.
// You can call Documents directly on a CollectionRef as well.
iter2 := client.Collection("States").Documents(ctx)
_ = iter2 // TODO: Use iter2.
}
path_methods
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
q := client.Collection("Unusual").SelectPaths([]string{"*"}, []string{"[~]"}).
WherePath([]string{"/"}, ">", 10).
OrderByPath([]string{"/"}, firestore.Desc).
Limit(10)
iter1 := q.Documents(ctx)
_ = iter1 // TODO: Use iter1.
// You can call Documents directly on a CollectionRef as well.
iter2 := client.Collection("States").Documents(ctx)
_ = iter2 // TODO: Use iter2.
}
func (Query) EndAt
EndAt returns a new Query that specifies that results should end at the document with the given field values. See Query.StartAt for more information.
Calling EndAt overrides a previous call to EndAt or EndBefore.
func (Query) EndBefore
EndBefore returns a new Query that specifies that results should end just before the document with the given field values. See Query.StartAt for more information.
Calling EndBefore overrides a previous call to EndAt or EndBefore.
func (Query) FindNearest
func (q Query) FindNearest(vectorField string, queryVector any, limit int, measure DistanceMeasure, options *FindNearestOptions) VectorQueryFindNearest returns a query that can perform vector distance (similarity) search.
The returned query, when executed, performs a distance search on the specified vectorField against the given queryVector and returns the top documents that are closest to the queryVector according to measure. At most limit documents are returned.
Only documents whose vectorField field is a Vector32 or Vector64 of the same dimension as queryVector participate in the query; all other documents are ignored. In particular, fields of type []float32 or []float64 are ignored.
The vectorField argument can be a single field or a dot-separated sequence of fields, and must not contain any of the runes "˜*/[]".
The queryVector argument can be any of the following types:
- []float32
- []float64
- Vector32
- Vector64
Example
package main
import (
"context"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
//
q := client.Collection("descriptions").
FindNearest("Embedding", []float32{1, 2, 3}, 5, firestore.DistanceMeasureDotProduct, &firestore.FindNearestOptions{
DistanceThreshold: firestore.Ptr(20.0),
DistanceResultField: "vector_distance",
})
iter1 := q.Documents(ctx)
_ = iter1 // TODO: Use iter1.
}
func (Query) FindNearestPath
func (q Query) FindNearestPath(vectorFieldPath FieldPath, queryVector any, limit int, measure DistanceMeasure, options *FindNearestOptions) VectorQueryFindNearestPath is like [Query.FindNearest] but it accepts a [FieldPath].
func (Query) Limit
Limit returns a new Query that specifies the maximum number of first results to return. It must not be negative.
func (Query) LimitToLast
LimitToLast returns a new Query that specifies the maximum number of last results to return. It must not be negative.
func (*Query) NewAggregationQuery
func (q *Query) NewAggregationQuery() *AggregationQueryNewAggregationQuery returns an AggregationQuery with this query as its base query.
func (Query) Offset
Offset returns a new Query that specifies the number of initial results to skip. It must not be negative.
func (Query) OrderBy
OrderBy returns a new Query that specifies the order in which results are returned. A Query can have multiple OrderBy/OrderByPath specifications. OrderBy appends the specification to the list of existing ones.
The path argument can be a single field or a dot-separated sequence of fields, and must not contain any of the runes "˜*/[]".
To order by document name, use the special field path DocumentID.
func (Query) OrderByPath
OrderByPath returns a new Query that specifies the order in which results are returned. A Query can have multiple OrderBy/OrderByPath specifications. OrderByPath appends the specification to the list of existing ones.
func (Query) Pipeline
Pipeline creates a new [Pipeline] from the query.
All of the operations of the query will be converted to pipeline stages.
For example, query.Where("f", "==", 1).Limit(10).OrderBy("f", Asc).Pipeline() is equivalent to
client.Pipeline().Collection("C").Where(Equal("f", 1)).Limit(10).Sort(Ascending("f")).
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (Query) Select
Select returns a new Query that specifies the paths to return from the result documents. Each path argument can be a single field or a dot-separated sequence of fields, and must not contain any of the runes "˜*/[]".
An empty Select call will produce a query that returns only document IDs.
func (Query) SelectPaths
SelectPaths returns a new Query that specifies the field paths to return from the result documents.
An empty SelectPaths call will produce a query that returns only document IDs.
func (Query) Serialize
Serialize creates a RunQueryRequest wire-format byte slice from a Query object. This can be used in combination with Deserialize to marshal Query objects. This could be useful, for instance, if executing a query formed in one process in another.
func (Query) Snapshots
func (q Query) Snapshots(ctx context.Context) *QuerySnapshotIteratorSnapshots returns an iterator over snapshots of the query. Each time the query results change, a new snapshot will be generated.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
"google.golang.org/api/iterator"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
q := client.Collection("States").
Where("pop", ">", 10).
OrderBy("pop", firestore.Desc).
Limit(10)
qsnapIter := q.Snapshots(ctx)
// Listen forever for changes to the query's results.
for {
qsnap, err := qsnapIter.Next()
if err == iterator.Done {
break
}
if err != nil {
// TODO: Handle error.
}
fmt.Printf("At %s there were %d results.\n", qsnap.ReadTime, qsnap.Size)
_ = qsnap.Documents // TODO: Iterate over the results if desired.
_ = qsnap.Changes // TODO: Use the list of incremental changes if desired.
}
}
func (Query) StartAfter
StartAfter returns a new Query that specifies that results should start just after the document with the given field values. See Query.StartAt for more information.
Calling StartAfter overrides a previous call to StartAt or StartAfter.
func (Query) StartAt
StartAt returns a new Query that specifies that results should start at the document with the given field values.
StartAt may be called with a single DocumentSnapshot, representing an existing document within the query. The document must be a direct child of the location being queried (not a parent document, or document in a different collection, or a grandchild document, for example).
Otherwise, StartAt should be called with one field value for each OrderBy clause, in the order that they appear. For example, in
q.OrderBy("X", Asc).OrderBy("Y", Desc).StartAt(1, 2)
results will begin at the first document where X = 1 and Y = 2.
If an OrderBy call uses the special DocumentID field path, the corresponding value should be the document ID relative to the query's collection. For example, to start at the document "NewYork" in the "States" collection, write
client.Collection("States").OrderBy(DocumentID, firestore.Asc).StartAt("NewYork")
Calling StartAt overrides a previous call to StartAt or StartAfter.
func (Query) Where
Where returns a new Query that filters the set of results. A Query can have multiple filters. The path argument can be a single field or a dot-separated sequence of fields, and must not contain any of the runes "˜*/[]". The op argument must be one of "==", "!=", "<", "<=", ">", ">=", "array-contains", "array-contains-any", "in" or "not-in". WARNING: Using WhereEntity with Simple and Composite filters is recommended.
func (Query) WhereEntity
func (q Query) WhereEntity(ef EntityFilter) QueryWhereEntity returns a query with provided filter.
EntityFilter can be a simple filter or a composite filter PropertyFilter and PropertyPathFilter are supported simple filters AndFilter and OrFilter are supported composite filters Entity filters in multiple calls are joined together by AND
func (Query) WherePath
WherePath returns a new Query that filters the set of results. A Query can have multiple filters. The op argument must be one of "==", "!=", "<", "<=", ">", ">=", "array-contains", "array-contains-any", "in" or "not-in". WARNING: Using WhereEntity with Simple and Composite filters is recommended.
func (*Query) WithReadOptions
func (q *Query) WithReadOptions(opts ...ReadOption) *QueryWithReadOptions specifies constraints for accessing documents from the database, e.g. at what time snapshot to read the documents.
func (Query) WithRunOptions
WithRunOptions allows passing options to the query Calling WithRunOptions overrides a previous call to WithRunOptions.
QuerySnapshot
type QuerySnapshot struct {
// An iterator over the query results.
// It is not necessary to call Stop on this iterator.
Documents *DocumentIterator
// The number of results in this snapshot.
Size int
// The changes since the previous snapshot.
Changes []DocumentChange
// The time at which this snapshot was obtained from Firestore.
ReadTime time.Time
}A QuerySnapshot is a snapshot of query results. It is returned by QuerySnapshotIterator.Next whenever the results of a query change.
QuerySnapshotIterator
type QuerySnapshotIterator struct {
// The Query used to construct this iterator.
Query Query
// contains filtered or unexported fields
}QuerySnapshotIterator is an iterator over snapshots of a query. Call Next on the iterator to get a snapshot of the query's results each time they change. Call Stop on the iterator when done.
For an example, see Query.Snapshots.
func (*QuerySnapshotIterator) Next
func (it *QuerySnapshotIterator) Next() (*QuerySnapshot, error)Next blocks until the query's results change, then returns a QuerySnapshot for the current results.
Next is not expected to return iterator.Done unless it is called after Stop. Rarely, networking issues may also cause iterator.Done to be returned.
func (*QuerySnapshotIterator) Stop
func (it *QuerySnapshotIterator) Stop()Stop stops receiving snapshots. You should always call Stop when you are done with a QuerySnapshotIterator, to free up resources. It is not safe to call Stop concurrently with Next.
Queryer
type Queryer interface {
// contains filtered or unexported methods
}A Queryer is a Query or a CollectionRef. CollectionRefs act as queries whose results are all the documents in the collection.
RawStage
type RawStage struct {
// contains filtered or unexported fields
}RawStage is a generic stage in the pipeline. It provides a flexible way to extend the pipeline's functionality by adding custom stages. It also allows the users to call the stages that are supported by the Firestore backend but not yet available in the current SDK version.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func NewRawStage
NewRawStage creates a new RawStage with the given name.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*RawStage) WithArguments
WithArguments sets the arguments for the RawStage.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func (*RawStage) WithOptions
func (s *RawStage) WithOptions(options RawStageOptions) *RawStageWithOptions sets the options for the RawStage.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
RawStageOptions
RawStageOptions holds the options for a RawStage.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
ReadOption
type ReadOption interface {
// contains filtered or unexported methods
}ReadOption interface allows for abstraction of computing read time settings.
func ReadTime
func ReadTime(t time.Time) ReadOptionReadTime specifies a time-specific snapshot of the database to read.
RunOption
type RunOption interface {
// contains filtered or unexported methods
}RunOption are options used while running a query
SampleMode
type SampleMode stringSampleMode defines the mode for the sample stage.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
SampleModeDocuments, SampleModePercent
const (
// SampleModeDocuments samples a fixed number of documents.
SampleModeDocuments SampleMode = "documents"
// SampleModePercent samples a percentage of documents.
SampleModePercent SampleMode = "percent"
)SampleSpec
type SampleSpec struct {
Size any
Mode SampleMode
}SampleSpec is used to define a sample operation.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
func SampleByDocuments
func SampleByDocuments(limit int) *SampleSpecSampleByDocuments creates a SampleSpec for sampling a fixed number of documents.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
Selectable
type Selectable interface {
// contains filtered or unexported methods
}Selectable is an interface for expressions that can be selected in a pipeline.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
SetOption
type SetOption interface {
// contains filtered or unexported methods
}A SetOption modifies a Firestore set operation.
MergeAll
var MergeAll SetOption = merge{/* contains filtered or unexported fields */}MergeAll is a SetOption that causes all the field paths given in the data argument to Set to be overwritten. It is not supported for struct data.
func Merge
Merge returns a SetOption that causes only the given field paths to be overwritten. Other fields on the existing document will be untouched. It is an error if a provided field path does not refer to a value in the data passed to Set.
SimpleFilter
type SimpleFilter interface {
EntityFilter
// contains filtered or unexported methods
}SimpleFilter represents a simple Firestore filter.
Transaction
type Transaction struct {
// contains filtered or unexported fields
}Transaction represents a Firestore transaction.
func (*Transaction) Create
func (t *Transaction) Create(dr *DocumentRef, data interface{}) errorCreate adds a Create operation to the Transaction. See DocumentRef.Create for details.
func (*Transaction) Delete
func (t *Transaction) Delete(dr *DocumentRef, opts ...Precondition) errorDelete adds a Delete operation to the Transaction. See DocumentRef.Delete for details.
func (*Transaction) DocumentRefs
func (t *Transaction) DocumentRefs(cr *CollectionRef) *DocumentRefIteratorDocumentRefs returns references to all the documents in the collection, including missing documents. A missing document is a document that does not exist but has sub-documents.
func (*Transaction) Documents
func (t *Transaction) Documents(q Queryer) *DocumentIteratorDocuments returns a DocumentIterator based on given Query or CollectionRef. The results will be in the context of the transaction.
func (*Transaction) Execute
func (t *Transaction) Execute(p *Pipeline) *PipelineSnapshotExecute runs the given pipeline in the context of the transaction.
func (*Transaction) Get
func (t *Transaction) Get(dr *DocumentRef) (*DocumentSnapshot, error)Get gets the document in the context of the transaction. The transaction holds a pessimistic lock on the returned document. If the document does not exist, Get returns a NotFound error, which can be checked with
status.Code(err) == codes.NotFound
func (*Transaction) GetAll
func (t *Transaction) GetAll(drs []*DocumentRef) ([]*DocumentSnapshot, error)GetAll retrieves multiple documents with a single call. The DocumentSnapshots are returned in the order of the given DocumentRefs. If a document is not present, the corresponding DocumentSnapshot's Exists method will return false. The transaction holds a pessimistic lock on all of the returned documents.
func (*Transaction) Set
func (t *Transaction) Set(dr *DocumentRef, data interface{}, opts ...SetOption) errorSet adds a Set operation to the Transaction. See DocumentRef.Set for details.
func (*Transaction) Update
func (t *Transaction) Update(dr *DocumentRef, data []Update, opts ...Precondition) errorUpdate adds a new Update operation to the Transaction. See DocumentRef.Update for details.
func (*Transaction) WithReadOptions
func (t *Transaction) WithReadOptions(opts ...ReadOption) *TransactionWithReadOptions specifies constraints for accessing documents from the database, e.g. at what time snapshot to read the documents.
TransactionOption
type TransactionOption interface {
// contains filtered or unexported methods
}A TransactionOption is an option passed to Client.Transaction.
UnnestOptions
type UnnestOptions struct {
// IndexField specifies the name of the field to store the array index of the unnested element.
IndexField any
}UnnestOptions holds the configuration for the Unnest stage.
Experimental: Firestore Pipelines is currently in preview and is subject to potential breaking changes in future versions, regardless of any other documented package stability guarantees.
Update
type Update struct {
Path string // Will be split on dots, and must not contain any of "˜*/[]".
FieldPath FieldPath
Value interface{}
}An Update describes an update to a value referred to by a path. An Update should have either a non-empty Path or a non-empty FieldPath, but not both.
See DocumentRef.Create for acceptable values. To delete a field, specify firestore.Delete as the value.
func (Update) String
String returns string representation of firestore.Update
Vector32
type Vector32 []float32Vector32 is an embedding vector of float32s.
Vector64
type Vector64 []float64Vector64 is an embedding vector of float64s.
VectorQuery
type VectorQuery struct {
// contains filtered or unexported fields
}VectorQuery represents a query that uses [Query.FindNearest] or [Query.FindNearestPath].
func (VectorQuery) Documents
func (vq VectorQuery) Documents(ctx context.Context) *DocumentIteratorDocuments returns an iterator over the vector query's resulting documents.
WriteBatch (deprecated)
type WriteBatch struct {
// contains filtered or unexported fields
}A WriteBatch holds multiple database updates. Build a batch with the Create, Set, Update and Delete methods, then run it with the Commit method. Errors in Create, Set, Update or Delete are recorded instead of being returned immediately. The first such error is returned by Commit.
Deprecated: The WriteBatch API has been replaced with the transaction and
the bulk writer API. For atomic transaction operations, use Transaction.
For bulk read and write operations, use BulkWriter.
func (*WriteBatch) Commit (deprecated)
func (b *WriteBatch) Commit(ctx context.Context) (_ []*WriteResult, err error)Commit applies all the writes in the batch to the database atomically. Commit returns an error if there are no writes in the batch, if any errors occurred in constructing the writes, or if the Commmit operation fails.
Example
package main
import (
"context"
"fmt"
"cloud.google.com/go/firestore"
)
func main() {
ctx := context.Background()
client, err := firestore.NewClient(ctx, "project-id")
if err != nil {
// TODO: Handle error.
}
defer client.Close()
type State struct {
Capital string `firestore:"capital"`
Population float64 `firestore:"pop"` // in millions
}
ny := client.Doc("States/NewYork")
ca := client.Doc("States/California")
writeResults, err := client.Batch().
Create(ny, State{Capital: "Albany", Population: 19.8}).
Set(ca, State{Capital: "Sacramento", Population: 39.14}).
Delete(client.Doc("States/WestDakota")).
Commit(ctx)
if err != nil {
// TODO: Handle error.
}
fmt.Println(writeResults)
}
func (*WriteBatch) Create (deprecated)
func (b *WriteBatch) Create(dr *DocumentRef, data interface{}) *WriteBatchCreate adds a Create operation to the batch. See DocumentRef.Create for details.
func (*WriteBatch) Delete (deprecated)
func (b *WriteBatch) Delete(dr *DocumentRef, opts ...Precondition) *WriteBatchDelete adds a Delete operation to the batch. See DocumentRef.Delete for details.
func (*WriteBatch) Set (deprecated)
func (b *WriteBatch) Set(dr *DocumentRef, data interface{}, opts ...SetOption) *WriteBatchSet adds a Set operation to the batch. See DocumentRef.Set for details.
func (*WriteBatch) Update (deprecated)
func (b *WriteBatch) Update(dr *DocumentRef, data []Update, opts ...Precondition) *WriteBatchUpdate adds an Update operation to the batch. See DocumentRef.Update for details.
WriteResult
type WriteResult struct {
// The time at which the document was updated, or created if it did not
// previously exist. Writes that do not actually change the document do
// not change the update time.
UpdateTime time.Time
}A WriteResult is returned by methods that write documents.