diff --git a/firestore/go.mod b/firestore/go.mod index d22b8522ad..f20d64d304 100644 --- a/firestore/go.mod +++ b/firestore/go.mod @@ -3,56 +3,57 @@ module github.com/GoogleCloudPlatform/golang-samples/firestore go 1.25.0 require ( - cloud.google.com/go/firestore v1.18.0 + cloud.google.com/go/firestore v1.22.0 github.com/GoogleCloudPlatform/golang-samples v0.0.0-20240724083556-7f760db013b7 - google.golang.org/api v0.217.0 - google.golang.org/genproto v0.0.0-20250115164207-1a7da9e5054f - google.golang.org/grpc v1.69.4 + google.golang.org/api v0.274.0 + google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 + google.golang.org/grpc v1.80.0 ) require ( - cel.dev/expr v0.19.1 // indirect - cloud.google.com/go v0.118.0 // indirect - cloud.google.com/go/auth v0.14.0 // indirect - cloud.google.com/go/auth/oauth2adapt v0.2.7 // indirect - cloud.google.com/go/compute/metadata v0.6.0 // indirect - cloud.google.com/go/iam v1.3.1 // indirect - cloud.google.com/go/longrunning v0.6.4 // indirect - cloud.google.com/go/monitoring v1.23.0 // indirect - cloud.google.com/go/storage v1.50.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.25.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.49.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.49.0 // indirect + cel.dev/expr v0.25.1 // indirect + cloud.google.com/go v0.123.0 // indirect + cloud.google.com/go/auth v0.18.2 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect + cloud.google.com/go/compute/metadata v0.9.0 // indirect + cloud.google.com/go/iam v1.5.3 // indirect + cloud.google.com/go/longrunning v0.9.0 // indirect + cloud.google.com/go/monitoring v1.24.3 // indirect + cloud.google.com/go/storage v1.56.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/cncf/xds/go v0.0.0-20250121191232-2f005788dc42 // indirect - github.com/envoyproxy/go-control-plane/envoy v1.32.3 // indirect - github.com/envoyproxy/protoc-gen-validate v1.1.0 // indirect + github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.36.0 // indirect + github.com/envoyproxy/protoc-gen-validate v1.3.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/go-logr/logr v1.4.2 // indirect + github.com/go-jose/go-jose/v4 v4.1.3 // indirect + github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect - github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.4 // indirect - github.com/googleapis/gax-go/v2 v2.14.1 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.14 // indirect + github.com/googleapis/gax-go/v2 v2.21.0 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect - go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.34.0 // indirect - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 // indirect - go.opentelemetry.io/otel v1.34.0 // indirect - go.opentelemetry.io/otel/metric v1.34.0 // indirect - go.opentelemetry.io/otel/sdk v1.34.0 // indirect - go.opentelemetry.io/otel/sdk/metric v1.34.0 // indirect - go.opentelemetry.io/otel/trace v1.34.0 // indirect - golang.org/x/crypto v0.32.0 // indirect - golang.org/x/net v0.34.0 // indirect - golang.org/x/oauth2 v0.25.0 // indirect - golang.org/x/sync v0.10.0 // indirect - golang.org/x/sys v0.29.0 // indirect - golang.org/x/text v0.21.0 // indirect - golang.org/x/time v0.9.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20250115164207-1a7da9e5054f // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f // indirect - google.golang.org/protobuf v1.36.3 // indirect + github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.39.0 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect + go.opentelemetry.io/otel v1.43.0 // indirect + go.opentelemetry.io/otel/metric v1.43.0 // indirect + go.opentelemetry.io/otel/sdk v1.43.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.43.0 // indirect + go.opentelemetry.io/otel/trace v1.43.0 // indirect + golang.org/x/crypto v0.49.0 // indirect + golang.org/x/net v0.52.0 // indirect + golang.org/x/oauth2 v0.36.0 // indirect + golang.org/x/sync v0.20.0 // indirect + golang.org/x/sys v0.42.0 // indirect + golang.org/x/text v0.35.0 // indirect + golang.org/x/time v0.15.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect + google.golang.org/protobuf v1.36.11 // indirect ) diff --git a/firestore/go.sum b/firestore/go.sum index 9abb22cd83..26658c6b6a 100644 --- a/firestore/go.sum +++ b/firestore/go.sum @@ -1,127 +1,129 @@ -cel.dev/expr v0.19.1 h1:NciYrtDRIR0lNCnH1LFJegdjspNx9fI59O7TWcua/W4= -cel.dev/expr v0.19.1/go.mod h1:MrpN08Q+lEBs+bGYdLxxHkZoUSsCp0nSKTs0nTymJgw= -cloud.google.com/go v0.118.0 h1:tvZe1mgqRxpiVa3XlIGMiPcEUbP1gNXELgD4y/IXmeQ= -cloud.google.com/go v0.118.0/go.mod h1:zIt2pkedt/mo+DQjcT4/L3NDxzHPR29j5HcclNH+9PM= -cloud.google.com/go/auth v0.14.0 h1:A5C4dKV/Spdvxcl0ggWwWEzzP7AZMJSEIgrkngwhGYM= -cloud.google.com/go/auth v0.14.0/go.mod h1:CYsoRL1PdiDuqeQpZE0bP2pnPrGqFcOkI0nldEQis+A= -cloud.google.com/go/auth/oauth2adapt v0.2.7 h1:/Lc7xODdqcEw8IrZ9SvwnlLX6j9FHQM74z6cBk9Rw6M= -cloud.google.com/go/auth/oauth2adapt v0.2.7/go.mod h1:NTbTTzfvPl1Y3V1nPpOgl2w6d/FjO7NNUQaWSox6ZMc= -cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= -cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= -cloud.google.com/go/firestore v1.18.0 h1:cuydCaLS7Vl2SatAeivXyhbhDEIR8BDmtn4egDhIn2s= -cloud.google.com/go/firestore v1.18.0/go.mod h1:5ye0v48PhseZBdcl0qbl3uttu7FIEwEYVaWm0UIEOEU= -cloud.google.com/go/iam v1.3.1 h1:KFf8SaT71yYq+sQtRISn90Gyhyf4X8RGgeAVC8XGf3E= -cloud.google.com/go/iam v1.3.1/go.mod h1:3wMtuyT4NcbnYNPLMBzYRFiEfjKfJlLVLrisE7bwm34= -cloud.google.com/go/logging v1.13.0 h1:7j0HgAp0B94o1YRDqiqm26w4q1rDMH7XNRU34lJXHYc= -cloud.google.com/go/logging v1.13.0/go.mod h1:36CoKh6KA/M0PbhPKMq6/qety2DCAErbhXT62TuXALA= -cloud.google.com/go/longrunning v0.6.4 h1:3tyw9rO3E2XVXzSApn1gyEEnH2K9SynNQjMlBi3uHLg= -cloud.google.com/go/longrunning v0.6.4/go.mod h1:ttZpLCe6e7EXvn9OxpBRx7kZEB0efv8yBO6YnVMfhJs= -cloud.google.com/go/monitoring v1.23.0 h1:M3nXww2gn9oZ/qWN2bZ35CjolnVHM3qnSbu6srCPgjk= -cloud.google.com/go/monitoring v1.23.0/go.mod h1:034NnlQPDzrQ64G2Gavhl0LUHZs9H3rRmhtnp7jiJgg= -cloud.google.com/go/storage v1.50.0 h1:3TbVkzTooBvnZsk7WaAQfOsNrdoM8QHusXA1cpk6QJs= -cloud.google.com/go/storage v1.50.0/go.mod h1:l7XeiD//vx5lfqE3RavfmU9yvk5Pp0Zhcv482poyafY= -cloud.google.com/go/trace v1.11.3 h1:c+I4YFjxRQjvAhRmSsmjpASUKq88chOX854ied0K/pE= -cloud.google.com/go/trace v1.11.3/go.mod h1:pt7zCYiDSQjC9Y2oqCsh9jF4GStB/hmjrYLsxRR27q8= +cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= +cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= +cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= +cloud.google.com/go/auth v0.18.2 h1:+Nbt5Ev0xEqxlNjd6c+yYUeosQ5TtEUaNcN/3FozlaM= +cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M= +cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= +cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= +cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +cloud.google.com/go/firestore v1.22.0 h1:avooeboIq37vKXobrbPUFhFBxS/c3FqmWoX0xs8dO6E= +cloud.google.com/go/firestore v1.22.0/go.mod h1:PaM4i7i7ruALSKmlpHXXZaPObcZw0W7ie5UOPr72iTU= +cloud.google.com/go/iam v1.5.3 h1:+vMINPiDF2ognBJ97ABAYYwRgsaqxPbQDlMnbHMjolc= +cloud.google.com/go/iam v1.5.3/go.mod h1:MR3v9oLkZCTlaqljW6Eb2d3HGDGK5/bDv93jhfISFvU= +cloud.google.com/go/logging v1.13.2 h1:qqlHCBvieJT9Cdq4QqYx1KPadCQ2noD4FK02eNqHAjA= +cloud.google.com/go/logging v1.13.2/go.mod h1:zaybliM3yun1J8mU2dVQ1/qDzjbOqEijZCn6hSBtKak= +cloud.google.com/go/longrunning v0.9.0 h1:0EzbDEGsAvOZNbqXopgniY0w0a1phvu5IdUFq8grmqY= +cloud.google.com/go/longrunning v0.9.0/go.mod h1:pkTz846W7bF4o2SzdWJ40Hu0Re+UoNT6Q5t+igIcb8E= +cloud.google.com/go/monitoring v1.24.3 h1:dde+gMNc0UhPZD1Azu6at2e79bfdztVDS5lvhOdsgaE= +cloud.google.com/go/monitoring v1.24.3/go.mod h1:nYP6W0tm3N9H/bOw8am7t62YTzZY+zUeQ+Bi6+2eonI= +cloud.google.com/go/storage v1.56.0 h1:iixmq2Fse2tqxMbWhLWC9HfBj1qdxqAmiK8/eqtsLxI= +cloud.google.com/go/storage v1.56.0/go.mod h1:Tpuj6t4NweCLzlNbw9Z9iwxEkrSem20AetIeH/shgVU= +cloud.google.com/go/trace v1.11.7 h1:kDNDX8JkaAG3R2nq1lIdkb7FCSi1rCmsEtKVsty7p+U= +cloud.google.com/go/trace v1.11.7/go.mod h1:TNn9d5V3fQVf6s4SCveVMIBS2LJUqo73GACmq/Tky0s= github.com/GoogleCloudPlatform/golang-samples v0.0.0-20240724083556-7f760db013b7 h1:yGCaiv5IE3WoRTUOXHD/jybC2RIGTdCKuNwwmwQq7u4= github.com/GoogleCloudPlatform/golang-samples v0.0.0-20240724083556-7f760db013b7/go.mod h1:CK/v6fB0p6JTQtDAQ1UyKABPBiHRsA3+qbX2yuZZk1w= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.25.0 h1:3c8yed4lgqTt+oTQ+JNMDo+F4xprBf+O/il4ZC0nRLw= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.25.0/go.mod h1:obipzmGjfSjam60XLwGfqUkJsfiheAl+TUjG+4yzyPM= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.49.0 h1:o90wcURuxekmXrtxmYWTyNla0+ZEHhud6DI1ZTxd1vI= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.49.0/go.mod h1:6fTWu4m3jocfUZLYF5KsZC1TUfRvEjs7lM4crme/irw= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.49.0 h1:jJKWl98inONJAr/IZrdFQUWcwUO95DLY1XMD1ZIut+g= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.49.0/go.mod h1:l2fIqmwB+FKSfvn3bAD/0i+AXAxhIZjTK2svT/mgUXs= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.49.0 h1:GYUJLfvd++4DMuMhCFLgLXvFwofIxh/qOwoGuS/LTew= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.49.0/go.mod h1:wRbFgBQUVm1YXrvWKofAEmq9HNJTDphbAaJSSX01KUI= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 h1:DHa2U07rk8syqvCge0QIGMCE1WxGj9njT44GH7zNJLQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0 h1:owcC2UnmsZycprQ5RfRgjydWhuoxg71LUfyiQdijZuM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.53.0/go.mod h1:ZPpqegjbE99EPKsu3iUWV22A04wzGPcAY/ziSIQEEgs= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0 h1:4LP6hvB4I5ouTbGgWtixJhgED6xdf67twf9PoY96Tbg= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.53.0/go.mod h1:jUZ5LYlw40WMd07qxcQJD5M40aUxrfwqQX1g7zxYnrQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0 h1:Ron4zCA/yk6U7WOBXhTJcDpsUBG9npumK6xw2auFltQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.53.0/go.mod h1:cSgYe11MCNYunTnRXrKiR/tHc0eoKjICUuWpNZoVCOo= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= -github.com/cncf/xds/go v0.0.0-20250121191232-2f005788dc42 h1:Om6kYQYDUk5wWbT0t0q6pvyM49i9XZAv9dDrkDA7gjk= -github.com/cncf/xds/go v0.0.0-20250121191232-2f005788dc42/go.mod h1:W+zGtBO5Y1IgJhy4+A9GOqVhqLpfZi+vwmdNXUehLA8= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/envoyproxy/go-control-plane v0.13.4 h1:zEqyPVyku6IvWCFwux4x9RxkLOMUL+1vC9xUFv5l2/M= -github.com/envoyproxy/go-control-plane v0.13.4/go.mod h1:kDfuBlDVsSj2MjrLEtRWtHlsWIFcGyB2RMO44Dc5GZA= -github.com/envoyproxy/go-control-plane/envoy v1.32.3 h1:hVEaommgvzTjTd4xCaFd+kEQ2iYBtGxP6luyLrx6uOk= -github.com/envoyproxy/go-control-plane/envoy v1.32.3/go.mod h1:F6hWupPfh75TBXGKA++MCT/CZHFq5r9/uwt/kQYkZfE= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w= +github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= +github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= +github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g= +github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= -github.com/envoyproxy/protoc-gen-validate v1.1.0 h1:tntQDh69XqOCOZsDz0lVJQez/2L6Uu2PdjCQwWCJ3bM= -github.com/envoyproxy/protoc-gen-validate v1.1.0/go.mod h1:sXRDRVmzEbkM7CVcM06s9shE/m23dg3wzjl0UWqJ2q4= +github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4= +github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs= +github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= -github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ= -github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= -github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/googleapis/enterprise-certificate-proxy v0.3.4 h1:XYIDZApgAnrN1c855gTgghdIA6Stxb52D5RnLI1SLyw= -github.com/googleapis/enterprise-certificate-proxy v0.3.4/go.mod h1:YKe7cfqYXjKGpGvmSg28/fFvhNzinZQm8DGnaburhGA= -github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q= -github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA= +github.com/googleapis/enterprise-certificate-proxy v0.3.14 h1:yh8ncqsbUY4shRD5dA6RlzjJaT4hi3kII+zYw8wmLb8= +github.com/googleapis/enterprise-certificate-proxy v0.3.14/go.mod h1:vqVt9yG9480NtzREnTlmGSBmFrA+bzb0yl0TxoBQXOg= +github.com/googleapis/gax-go/v2 v2.21.0 h1:h45NjjzEO3faG9Lg/cFrBh2PgegVVgzqKzuZl/wMbiI= +github.com/googleapis/gax-go/v2 v2.21.0/go.mod h1:But/NJU6TnZsrLai/xBAQLLz+Hc7fHZJt/hsCz3Fih4= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= -go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= -go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= -go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/contrib/detectors/gcp v1.34.0 h1:JRxssobiPg23otYU5SbWtQC//snGVIM3Tx6QRzlQBao= -go.opentelemetry.io/contrib/detectors/gcp v1.34.0/go.mod h1:cV4BMFcscUR/ckqLkbfQmF0PRsq8w/lMGzdbCSveBHo= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0 h1:rgMkmiGfix9vFJDcDi1PK8WEQP4FLQwLDfhp5ZLpFeE= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0/go.mod h1:ijPqXp5P6IRRByFVVg9DY8P5HkxkHE5ARIa+86aXPf4= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 h1:CV7UdSGJt/Ao6Gp4CXckLxVRRsRgDHoI8XjbL3PDl8s= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0/go.mod h1:FRmFuRJfag1IZ2dPkHnEoSFVgTVPUd2qf5Vi69hLb8I= -go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY= -go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0 h1:WDdP9acbMYjbKIyJUhTvtzj601sVJOqgWdUxSdR/Ysc= -go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0/go.mod h1:BLbf7zbNIONBLPwvFnwNHGj4zge8uTCM/UPIVW1Mq2I= -go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ= -go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE= -go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A= -go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU= -go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= -go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= -go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k= -go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= -golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc= -golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc= -golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= -golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= -golang.org/x/oauth2 v0.25.0 h1:CY4y7XT9v0cRI9oupztF8AgiIu99L/ksR/Xp/6jrZ70= -golang.org/x/oauth2 v0.25.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= -golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= -golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU= -golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= -golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= -golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= -golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= -google.golang.org/api v0.217.0 h1:GYrUtD289o4zl1AhiTZL0jvQGa2RDLyC+kX1N/lfGOU= -google.golang.org/api v0.217.0/go.mod h1:qMc2E8cBAbQlRypBTBWHklNJlaZZJBwDv81B1Iu8oSI= -google.golang.org/genproto v0.0.0-20250115164207-1a7da9e5054f h1:387Y+JbxF52bmesc8kq1NyYIp33dnxCw6eiA7JMsTmw= -google.golang.org/genproto v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:0joYwWwLQh18AOj8zMYeZLjzuqcYTU3/nC5JdCvC3JI= -google.golang.org/genproto/googleapis/api v0.0.0-20250115164207-1a7da9e5054f h1:gap6+3Gk41EItBuyi4XX/bp4oqJ3UwuIMl25yGinuAA= -google.golang.org/genproto/googleapis/api v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:Ic02D47M+zbarjYYUlK57y316f2MoN0gjAwI3f2S95o= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f h1:OxYkA3wjPsZyBylwymxSHa7ViiW1Sml4ToBrncvFehI= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250115164207-1a7da9e5054f/go.mod h1:+2Yz8+CLJbIfL9z73EW45avw8Lmge3xVElCP9zEKi50= -google.golang.org/grpc v1.69.4 h1:MF5TftSMkd8GLw/m0KM6V8CMOCY6NZ1NQDPGFgbTt4A= -google.golang.org/grpc v1.69.4/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4= -google.golang.org/protobuf v1.36.3 h1:82DV7MYdb8anAVi3qge1wSnMDrnKK7ebr+I0hHRN1BU= -google.golang.org/protobuf v1.36.3/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo= +github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE= +go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= +go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I= +go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0 h1:rixTyDGXFxRy1xzhKrotaHy3/KXdPhlWARrCgK+eqUY= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0/go.mod h1:dowW6UsM9MKbJq5JTz2AMVp3/5iW5I/TStsk8S+CfHw= +go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM= +go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY= +go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg= +go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg= +go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw= +go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A= +go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A= +go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0= +golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= +golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= +golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= +golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/api v0.274.0 h1:aYhycS5QQCwxHLwfEHRRLf9yNsfvp1JadKKWBE54RFA= +google.golang.org/api v0.274.0/go.mod h1:JbAt7mF+XVmWu6xNP8/+CTiGH30ofmCmk9nM8d8fHew= +google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0= +google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I= +google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA= +google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 h1:m8qni9SQFH0tJc1X0vmnpw/0t+AImlSvp30sEupozUg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM= +google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/firestore/pipeline_snippets_accumulators_aggregation.go b/firestore/pipeline_snippets_accumulators_aggregation.go new file mode 100644 index 0000000000..bc3543242b --- /dev/null +++ b/firestore/pipeline_snippets_accumulators_aggregation.go @@ -0,0 +1,106 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" +) + +func countFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_count_function] + // Total number of books in the collection + countAll, err := client.Pipeline().Collection("books"). + Aggregate(firestore.Accumulators(firestore.CountAll().As("count"))). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + + // Number of books with nonnull `ratings` field + countField, err := client.Pipeline(). + Collection("books"). + Aggregate(firestore.Accumulators(firestore.Count("ratings").As("count"))). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + // [END firestore_count_function] + fmt.Fprintln(w, countAll, countField) + return nil +} + +func countIfFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_count_if] + snapshot := client.Pipeline(). + Collection("books"). + Aggregate(firestore.Accumulators( + firestore.CountIf(firestore.FieldOf("rating").GreaterThan(4)).As("filteredCount"), + )). + Execute(ctx) + // [END firestore_count_if] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func countDistinctFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_count_distinct] + snapshot := client.Pipeline(). + Collection("books"). + Aggregate(firestore.Accumulators( + firestore.CountDistinct("author").As("unique_authors"), + )). + Execute(ctx) + // [END firestore_count_distinct] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func avgFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_avg_function] + snapshot := client.Pipeline(). + Collection("cities"). + Aggregate(firestore.Accumulators( + firestore.Average("population").As("averagePopulation"), + )). + Execute(ctx) + // [END firestore_avg_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} diff --git a/firestore/pipeline_snippets_arithmetic.go b/firestore/pipeline_snippets_arithmetic.go new file mode 100644 index 0000000000..643cebbeda --- /dev/null +++ b/firestore/pipeline_snippets_arithmetic.go @@ -0,0 +1,292 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" +) + +func addFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_add_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Add(firestore.FieldOf("soldBooks"), firestore.FieldOf("unsoldBooks")).As("totalBooks"), + )). + Execute(ctx) + // [END firestore_add_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func subtractFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_subtract_function] + storeCredit := 7 + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Subtract(firestore.FieldOf("price"), storeCredit).As("totalCost"), + )). + Execute(ctx) + // [END firestore_subtract_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func multiplyFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_multiply_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Multiply(firestore.FieldOf("price"), firestore.FieldOf("soldBooks")).As("revenue"), + )). + Execute(ctx) + // [END firestore_multiply_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func divideFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_divide_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Divide(firestore.FieldOf("ratings"), firestore.FieldOf("soldBooks")).As("reviewRate"), + )). + Execute(ctx) + // [END firestore_divide_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func modFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_mod_function] + displayCapacity := 1000 + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Mod(firestore.FieldOf("unsoldBooks"), displayCapacity).As("warehousedBooks"), + )). + Execute(ctx) + // [END firestore_mod_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func ceilFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_ceil_function] + booksPerShelf := 100 + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Ceil(firestore.Divide(firestore.FieldOf("unsoldBooks"), booksPerShelf)).As("requiredShelves"), + )). + Execute(ctx) + // [END firestore_ceil_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func floorFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_floor_function] + snapshot := client.Pipeline(). + Collection("books"). + AddFields(firestore.Selectables( + firestore.Floor(firestore.Divide(firestore.FieldOf("wordCount"), firestore.FieldOf("pages"))).As("wordsPerPage"), + )). + Execute(ctx) + // [END firestore_floor_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func roundFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_round_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Round(firestore.Multiply(firestore.FieldOf("soldBooks"), firestore.FieldOf("price"))).As("partialRevenue"), + )). + Aggregate(firestore.Accumulators( + firestore.Sum("partialRevenue").As("totalRevenue"), + )). + Execute(ctx) + // [END firestore_round_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func powFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_pow_function] + googleplexLat := 37.4221 + googleplexLng := -122.0853 + snapshot := client.Pipeline(). + Collection("cities"). + AddFields(firestore.Selectables( + firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lat"), googleplexLat), 111), 2).As("latitudeDifference"), + firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lng"), googleplexLng), 111), 2).As("longitudeDifference"), + )). + Select(firestore.Fields( + firestore.Sqrt(firestore.Add(firestore.FieldOf("latitudeDifference"), firestore.FieldOf("longitudeDifference"))). + // Inaccurate for large distances or close to poles + As("approximateDistanceToGoogle"), + )). + Execute(ctx) + // [END firestore_pow_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func sqrtFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sqrt_function] + googleplexLat := 37.4221 + googleplexLng := -122.0853 + snapshot := client.Pipeline(). + Collection("cities"). + AddFields(firestore.Selectables( + firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lat"), googleplexLat), 111), 2).As("latitudeDifference"), + firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lng"), googleplexLng), 111), 2).As("longitudeDifference"), + )). + Select(firestore.Fields( + firestore.Sqrt(firestore.Add(firestore.FieldOf("latitudeDifference"), firestore.FieldOf("longitudeDifference"))). + // Inaccurate for large distances or close to poles + As("approximateDistanceToGoogle"), + )). + Execute(ctx) + // [END firestore_sqrt_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func expFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_exp_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Exp(firestore.FieldOf("rating")).As("expRating"), + )). + Execute(ctx) + // [END firestore_exp_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func lnFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_ln_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Ln(firestore.FieldOf("rating")).As("lnRating"), + )). + Execute(ctx) + // [END firestore_ln_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func logFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_log_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Log(firestore.FieldOf("rating"), 2).As("log2Rating"), + )). + Execute(ctx) + // [END firestore_log_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} diff --git a/firestore/pipeline_snippets_array.go b/firestore/pipeline_snippets_array.go new file mode 100644 index 0000000000..4399a94686 --- /dev/null +++ b/firestore/pipeline_snippets_array.go @@ -0,0 +1,266 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" +) + +func sumFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sum_function] + snapshot := client.Pipeline(). + Collection("cities"). + Aggregate(firestore.Accumulators( + firestore.Sum("population").As("totalPopulation"), + )). + Execute(ctx) + // [END firestore_sum_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func minFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_min_function] + snapshot := client.Pipeline(). + Collection("books"). + Aggregate(firestore.Accumulators( + firestore.Minimum("price").As("minimumPrice"), + )). + Execute(ctx) + // [END firestore_min_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func maxFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_max_function] + snapshot := client.Pipeline(). + Collection("books"). + Aggregate(firestore.Accumulators( + firestore.Maximum("price").As("maximumPrice"), + )). + Execute(ctx) + // [END firestore_max_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func arrayConcatFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_array_concat] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.ArrayConcat(firestore.FieldOf("genre"), firestore.FieldOf("subGenre")).As("allGenres"), + )). + Execute(ctx) + // [END firestore_array_concat] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func arrayContainsFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_array_contains] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.ArrayContains(firestore.FieldOf("genre"), "mystery").As("isMystery"), + )). + Execute(ctx) + // [END firestore_array_contains] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func arrayContainsAllFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_array_contains_all] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.ArrayContainsAll(firestore.FieldOf("genre"), []string{"fantasy", "adventure"}).As("isFantasyAdventure"), + )). + Execute(ctx) + // [END firestore_array_contains_all] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func arrayContainsAnyFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_array_contains_any] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.ArrayContainsAny(firestore.FieldOf("genre"), []string{"fantasy", "nonfiction"}).As("isMysteryOrFantasy"), + )). + Execute(ctx) + // [END firestore_array_contains_any] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func arrayLengthFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_array_length] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.ArrayLength(firestore.FieldOf("genre")).As("genreCount"), + )). + Execute(ctx) + // [END firestore_array_length] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func arrayReverseFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_array_reverse] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.ArrayReverse(firestore.FieldOf("genre")).As("reversedGenres"), + )). + Execute(ctx) + // [END firestore_array_reverse] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func equalAnyFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_eq_any] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.EqualAny(firestore.FieldOf("genre"), []string{"Science Fiction", "Psychological Thriller"}).As("matchesGenreFilters"), + )). + Execute(ctx) + // [END firestore_eq_any] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func notEqualAnyFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_not_eq_any] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.NotEqualAny(firestore.FieldOf("author"), []string{"George Orwell", "F. Scott Fitzgerald"}).As("byExcludedAuthors"), + )). + Execute(ctx) + // [END firestore_not_eq_any] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func functionsExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_functions_example] + // Type 1: Scalar (for use in non-aggregation stages) + // Example: Return the min store price for each book. + results1, err := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.LogicalMinimum(firestore.FieldOf("current"), firestore.FieldOf("updated")).As("price_min"), + )). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + + // Type 2: Aggregation (for use in aggregate stages) + // Example: Return the min price of all books. + results2, err := client.Pipeline(). + Collection("books"). + Aggregate(firestore.Accumulators( + firestore.Minimum("price").As("min_price"), + )). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + // [END firestore_functions_example] + fmt.Fprintln(w, results1) + fmt.Fprintln(w, results2) + return nil +} diff --git a/firestore/pipeline_snippets_comparison.go b/firestore/pipeline_snippets_comparison.go new file mode 100644 index 0000000000..889cf4d5bf --- /dev/null +++ b/firestore/pipeline_snippets_comparison.go @@ -0,0 +1,137 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" +) + +func equalFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_equal_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Equal(firestore.FieldOf("rating"), 5).As("hasPerfectRating"), + )). + Execute(ctx) + // [END firestore_equal_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func greaterThanFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_greater_than] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.GreaterThan(firestore.FieldOf("rating"), 4).As("hasHighRating"), + )). + Execute(ctx) + // [END firestore_greater_than] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func greaterThanOrEqualToFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_greater_or_equal] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.GreaterThanOrEqual(firestore.FieldOf("published"), 1900).As("publishedIn20thCentury"), + )). + Execute(ctx) + // [END firestore_greater_or_equal] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func lessThanFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_less_than] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.LessThan(firestore.FieldOf("published"), 1923).As("isPublicDomainProbably"), + )). + Execute(ctx) + // [END firestore_less_than] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func lessThanOrEqualToFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_less_or_equal] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.LessThanOrEqual(firestore.FieldOf("rating"), 2).As("hasBadRating"), + )). + Execute(ctx) + // [END firestore_less_or_equal] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func notEqualFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_not_equal] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.NotEqual(firestore.FieldOf("title"), "1984").As("not1984"), + )). + Execute(ctx) + // [END firestore_not_equal] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} diff --git a/firestore/pipeline_snippets_date_timestamp.go b/firestore/pipeline_snippets_date_timestamp.go new file mode 100644 index 0000000000..75dd37fcb0 --- /dev/null +++ b/firestore/pipeline_snippets_date_timestamp.go @@ -0,0 +1,175 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" +) + +func unixMicrosToTimestampFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unix_micros_timestamp] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.UnixMicrosToTimestamp(firestore.FieldOf("createdAtMicros")).As("createdAtString"), + )). + Execute(ctx) + // [END firestore_unix_micros_timestamp] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func unixMillisToTimestampFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unix_millis_timestamp] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.UnixMillisToTimestamp(firestore.FieldOf("createdAtMillis")).As("createdAtString"), + )). + Execute(ctx) + // [END firestore_unix_millis_timestamp] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func unixSecondsToTimestampFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unix_seconds_timestamp] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.UnixSecondsToTimestamp(firestore.FieldOf("createdAtSeconds")).As("createdAtString"), + )). + Execute(ctx) + // [END firestore_unix_seconds_timestamp] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func timestampAddFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_timestamp_add] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.TimestampAdd(firestore.FieldOf("createdAt"), "day", 3653).As("expiresAt"), + )). + Execute(ctx) + // [END firestore_timestamp_add] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func timestampSubFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_timestamp_sub] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.TimestampSubtract(firestore.FieldOf("expiresAt"), "day", 14).As("sendWarningTimestamp"), + )). + Execute(ctx) + // [END firestore_timestamp_sub] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func timestampToUnixMicrosFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_timestamp_unix_micros] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.TimestampToUnixMicros(firestore.FieldOf("dateString")).As("unixMicros"), + )). + Execute(ctx) + // [END firestore_timestamp_unix_micros] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func timestampToUnixMillisFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_timestamp_unix_millis] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.TimestampToUnixMillis(firestore.FieldOf("dateString")).As("unixMillis"), + )). + Execute(ctx) + // [END firestore_timestamp_unix_millis] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func timestampToUnixSecondsFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_timestamp_unix_seconds] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.TimestampToUnixSeconds(firestore.FieldOf("dateString")).As("unixSeconds"), + )). + Execute(ctx) + // [END firestore_timestamp_unix_seconds] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} diff --git a/firestore/pipeline_snippets_dml.go b/firestore/pipeline_snippets_dml.go new file mode 100644 index 0000000000..7a74046879 --- /dev/null +++ b/firestore/pipeline_snippets_dml.go @@ -0,0 +1,64 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" +) + +func pipelineUpdate(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_pipeline_update] + snapshot := client.Pipeline(). + CollectionGroup("users"). + Where(firestore.Not(firestore.FieldExists(firestore.FieldOf("preferences.color")))). + AddFields(firestore.Selectables( + firestore.ConstantOfNull().As("preferences.color"), + )). + RemoveFields(firestore.Fields("color")). + Update(). + Execute(ctx) + // [END firestore_pipeline_update] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func pipelineDelete(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_pipeline_delete] + snapshot := client.Pipeline(). + CollectionGroup("users"). + Where(firestore.FieldOf("address.country").Equal("USA")). + Where(firestore.FieldOf("__create_time__").Add(firestore.ConstantOf(10)).LessThan(firestore.CurrentTimestamp())). + Delete(). + Execute(ctx) + // [END firestore_pipeline_delete] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} diff --git a/firestore/pipeline_snippets_general.go b/firestore/pipeline_snippets_general.go new file mode 100644 index 0000000000..451fc46b29 --- /dev/null +++ b/firestore/pipeline_snippets_general.go @@ -0,0 +1,2101 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" + "google.golang.org/api/iterator" +) + +func searchBasic(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_search_basic] + snapshot := client.Pipeline(). + Collection("restaurants"). + Search(firestore.WithSearchQuery(firestore.DocumentMatches("waffles"))). + Execute(ctx) + // [END firestore_search_basic] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func searchExact(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_search_exact] + snapshot := client.Pipeline(). + Collection("restaurants"). + Search(firestore.WithSearchQuery(firestore.DocumentMatches("\"belgian waffles\""))). + Execute(ctx) + // [END firestore_search_exact] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func searchTwoTerms(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_search_two_terms] + snapshot := client.Pipeline(). + Collection("restaurants"). + Search(firestore.WithSearchQuery(firestore.DocumentMatches("waffles eggs"))). + Execute(ctx) + // [END firestore_search_two_terms] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func searchExcludeTerm(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_search_exclude_term] + snapshot := client.Pipeline(). + Collection("restaurants"). + Search(firestore.WithSearchQuery(firestore.DocumentMatches("-waffles"))). + Execute(ctx) + // [END firestore_search_exclude_term] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func searchSpecialFields(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_search_special_fields] + snapshot := client.Pipeline(). + Collection("restaurants"). + Search( + firestore.WithSearchQuery(firestore.FieldOf("menu").RegexMatch("waffles")), + firestore.WithSearchAddFields(firestore.Score().As("score")), + ). + Execute(ctx) + // [END firestore_search_special_fields] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func sort(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sort] + snapshot := client.Pipeline(). + Collection("books"). + Sort(firestore.Orders( + firestore.Descending(firestore.FieldOf("release_date")), + firestore.Ascending(firestore.FieldOf("author")), + )). + Execute(ctx) + // [END firestore_sort] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func sortComparison(w io.Writer, client *firestore.Client) error { + // [START firestore_sort_comparison] + query := client.Collection("cities"). + OrderBy("state", firestore.Asc). + OrderBy("population", firestore.Desc) + + pipeline := client.Pipeline(). + Collection("books"). + Sort(firestore.Orders( + firestore.Descending(firestore.FieldOf("release_date")), + firestore.Ascending(firestore.FieldOf("author")), + )) + // [END firestore_sort_comparison] + fmt.Fprintln(w, query) + fmt.Fprintln(w, pipeline) + return nil +} + +func sortSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sort_syntax] + snapshot := client.Pipeline().Collection("cities"). + Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("population")))). + Execute(ctx) + // [END firestore_sort_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func sortSyntaxExample2(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sort_syntax_2] + snapshot := client.Pipeline().Collection("cities"). + Sort(firestore.Orders(firestore.Ascending(firestore.CharLength(firestore.FieldOf("name"))))). + Execute(ctx) + // [END firestore_sort_syntax_2] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func sortDocumentIDExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sort_document_id] + snapshot := client.Pipeline().Collection("cities"). + Sort(firestore.Orders( + firestore.Ascending(firestore.FieldOf("country")), + firestore.Ascending(firestore.FieldOf("__name__")), + )). + Execute(ctx) + // [END firestore_sort_document_id] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func aggregateGroups(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_aggregate_groups] + snapshot := client.Pipeline(). + Collection("books"). + Aggregate( + firestore.Accumulators(firestore.Average("rating").As("avg_rating")), + firestore.WithAggregateGroups("genre"), + ). + Execute(ctx) + // [END firestore_aggregate_groups] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func aggregateDistinct(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_aggregate_distinct] + snapshot := client.Pipeline(). + Collection("books"). + Distinct(firestore.Fields( + firestore.ToUpper(firestore.FieldOf("author")).As("author"), + firestore.FieldOf("genre"), + )). + Execute(ctx) + // [END firestore_aggregate_distinct] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func aggregateSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_aggregate_syntax] + snapshot := client.Pipeline().Collection("cities"). + Aggregate(firestore.Accumulators( + firestore.CountAll().As("total"), + firestore.Average("population").As("averagePopulation"), + )). + Execute(ctx) + // [END firestore_aggregate_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func aggregateGroupSyntax(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_aggregate_group_syntax] + snapshot := client.Pipeline().CollectionGroup("cities"). + Aggregate( + firestore.Accumulators( + firestore.CountAll().As("cities"), + firestore.Sum("population").As("totalPopulation"), + ), + firestore.WithAggregateGroups(firestore.FieldOf("location.state").As("state")), + ). + Execute(ctx) + // [END firestore_aggregate_group_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + return err + } + fmt.Fprintln(w, results) + return nil +} + +func aggregateExampleData(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_aggregate_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "state": "CA", + "country": "USA", + "population": 870000, + }) + client.Collection("cities").Doc("LA").Set(ctx, map[string]any{ + "name": "Los Angeles", + "state": "CA", + "country": "USA", + "population": 3970000, + }) + client.Collection("cities").Doc("NY").Set(ctx, map[string]any{ + "name": "New York", + "state": "NY", + "country": "USA", + "population": 8530000, + }) + client.Collection("cities").Doc("TOR").Set(ctx, map[string]any{ + "name": "Toronto", + "state": nil, + "country": "Canada", + "population": 2930000, + }) + client.Collection("cities").Doc("MEX").Set(ctx, map[string]any{ + "name": "Mexico City", + "state": nil, + "country": "Mexico", + "population": 9200000, + }) + // [END firestore_aggregate_data] + return nil +} + +func aggregateWithoutGroupExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_aggregate_without_group] + snapshot := client.Pipeline().Collection("cities"). + Aggregate(firestore.Accumulators( + firestore.CountAll().As("total"), + firestore.Average("population").As("averagePopulation"), + )). + Execute(ctx) + // [END firestore_aggregate_without_group] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func aggregateGroupExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_aggregate_group_example] + snapshot := client.Pipeline().Collection("cities"). + Aggregate( + firestore.Accumulators( + firestore.CountAll().As("numberOfCities"), + firestore.Maximum("population").As("maxPopulation"), + ), + firestore.WithAggregateGroups("country", "state"), + ). + Execute(ctx) + // [END firestore_aggregate_group_example] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func aggregateGroupComplexExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_aggregate_group_complex] + snapshot := client.Pipeline().Collection("cities"). + Aggregate( + firestore.Accumulators(firestore.Sum("population").As("totalPopulation")), + firestore.WithAggregateGroups(firestore.FieldOf("state").Equal(nil).As("stateIsNull")), + ). + Execute(ctx) + // [END firestore_aggregate_group_complex] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func distinctSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_distinct_syntax] + cities1, err := client.Pipeline().Collection("cities").Distinct(firestore.Fields("country")).Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + + cities2, err := client.Pipeline().Collection("cities"). + Distinct(firestore.Fields( + firestore.ToLower(firestore.FieldOf("state")).As("normalizedState"), + firestore.FieldOf("country"), + )). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + // [END firestore_distinct_syntax] + fmt.Fprintln(w, cities1) + fmt.Fprintln(w, cities2) + return nil +} + +func distinctExampleData(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_distinct_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "state": "CA", + "country": "USA", + }) + client.Collection("cities").Doc("LA").Set(ctx, map[string]any{ + "name": "Los Angeles", + "state": "CA", + "country": "USA", + }) + client.Collection("cities").Doc("NY").Set(ctx, map[string]any{ + "name": "New York", + "state": "NY", + "country": "USA", + }) + client.Collection("cities").Doc("TOR").Set(ctx, map[string]any{ + "name": "Toronto", + "state": nil, + "country": "Canada", + }) + client.Collection("cities").Doc("MEX").Set(ctx, map[string]any{ + "name": "Mexico City", + "state": nil, + "country": "Mexico", + }) + // [END firestore_distinct_data] + return nil +} + +func distinctExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_distinct_example] + snapshot := client.Pipeline().Collection("cities").Distinct(firestore.Fields("country")).Execute(ctx) + // [END firestore_distinct_example] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func distinctExpressionsExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_distinct_expressions] + results, err := client.Pipeline().Collection("cities"). + Distinct(firestore.Fields( + firestore.ToLower(firestore.FieldOf("state")).As("normalizedState"), + firestore.FieldOf("country"), + )). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + // [END firestore_distinct_expressions] + fmt.Fprintln(w, results) + return nil +} + +func selectSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_select_syntax] + snapshot := client.Pipeline().Collection("cities"). + Select(firestore.Fields( + firestore.StringConcat(firestore.FieldOf("name"), ", ", firestore.FieldOf("location.country")).As("name"), + firestore.FieldOf("population"), + )). + Execute(ctx) + // [END firestore_select_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func selectPositionDataExample(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_select_position_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "population": 800000, + "location": map[string]any{ + "country": "USA", + "state": "California", + }, + }) + client.Collection("cities").Doc("TO").Set(ctx, map[string]any{ + "name": "Toronto", + "population": 3000000, + "location": map[string]any{ + "country": "Canada", + "province": "Ontario", + }, + }) + // [END firestore_select_position_data] + return nil +} + +func selectPositionExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_select_position] + snapshot := client.Pipeline().Collection("cities"). + Where(firestore.FieldOf("location.country").Equal("Canada")). + Select(firestore.Fields( + firestore.StringConcat(firestore.FieldOf("name"), ", ", firestore.FieldOf("location.country")).As("name"), + firestore.FieldOf("population"), + )). + Execute(ctx) + // [END firestore_select_position] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func selectBadPositionExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_select_bad_position] + snapshot := client.Pipeline().Collection("cities"). + Select(firestore.Fields( + firestore.StringConcat(firestore.FieldOf("name"), ", ", firestore.FieldOf("location.country")).As("name"), + firestore.FieldOf("population"), + )). + Where(firestore.FieldOf("location.country").Equal("Canada")). + Execute(ctx) + // [END firestore_select_bad_position] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func selectNestedDataExample(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_select_nested_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "population": 800000, + "location": map[string]any{ + "country": "USA", + "state": "California", + }, + "landmarks": []string{"Golden Gate Bridge", "Alcatraz"}, + }) + client.Collection("cities").Doc("TO").Set(ctx, map[string]any{ + "name": "Toronto", + "population": 3000000, + "province": "ON", + "location": map[string]any{ + "country": "Canada", + "province": "Ontario", + }, + "landmarks": []string{"CN Tower", "Casa Loma"}, + }) + client.Collection("cities").Doc("AT").Set(ctx, map[string]any{ + "name": "Atlantis", + "population": nil, + }) + // [END firestore_select_nested_data] + return nil +} + +func selectNestedExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_select_nested] + snapshot := client.Pipeline().Collection("cities"). + Select(firestore.Fields( + firestore.FieldOf("name").As("city"), + firestore.FieldOf("location.country").As("country"), + firestore.ArrayGet(firestore.FieldOf("landmarks"), 0).As("topLandmark"), + )). + Execute(ctx) + // [END firestore_select_nested] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func addFieldsSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_add_fields_syntax] + snapshot := client.Pipeline().Collection("users"). + AddFields(firestore.Selectables( + firestore.StringConcat(firestore.FieldOf("firstName"), " ", firestore.FieldOf("lastName")).As("fullName"), + )). + Execute(ctx) + // [END firestore_add_fields_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func addFieldsOverlapExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_add_fields_overlap] + snapshot := client.Pipeline().Collection("users"). + AddFields(firestore.Selectables(firestore.Abs(firestore.FieldOf("age")).As("age"))). + AddFields(firestore.Selectables(firestore.Add(firestore.FieldOf("age"), 10).As("age"))). + Execute(ctx) + // [END firestore_add_fields_overlap] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func addFieldsNestingExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_add_fields_nesting] + snapshot := client.Pipeline().Collection("users"). + AddFields(firestore.Selectables( + firestore.ToLower(firestore.FieldOf("address.city")).As("address.city"), + )). + Execute(ctx) + // [END firestore_add_fields_nesting] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func removeFieldsSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_remove_fields_syntax] + snapshot := client.Pipeline().Collection("cities"). + RemoveFields(firestore.Fields("population", "location.state")). + Execute(ctx) + // [END firestore_remove_fields_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func removeFieldsNestedDataExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_remove_fields_nested_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "location": map[string]any{ + "country": "USA", + "state": "California", + }, + }) + client.Collection("cities").Doc("TO").Set(ctx, map[string]any{ + "name": "Toronto", + "location": map[string]any{ + "country": "Canada", + "province": "Ontario", + }, + }) + // [END firestore_remove_fields_nested_data] + return nil +} + +func removeFieldsNestedExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_remove_fields_nested] + snapshot := client.Pipeline().Collection("cities"). + RemoveFields(firestore.Fields("location.state")). + Execute(ctx) + // [END firestore_remove_fields_nested] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func defineExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_define_example] + snapshot := client.Pipeline(). + Collection("authors"). + Define([]*firestore.AliasedExpression{ + firestore.FieldOf("id").As("currentAuthorId"), + }). + // [END firestore_define_example] + AddFields(firestore.Selectables( + client.Pipeline(). + Collection("books"). + Where(firestore.FieldOf("author_id").Equal(firestore.Variable("currentAuthorId"))). + Aggregate(firestore.Accumulators(firestore.Average("rating").As("avgRating"))). + ToScalarExpression().As("averageBookRating"), + )). + Execute(ctx) + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func toArrayExpression(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_to_array_expression] + snapshot := client.Pipeline(). + Collection("projects"). + Define([]*firestore.AliasedExpression{ + firestore.FieldOf("id").As("parentId"), + }). + AddFields(firestore.Selectables( + client.Pipeline(). + Collection("tasks"). + Where(firestore.FieldOf("project_id").Equal(firestore.Variable("parentId"))). + Select(firestore.Fields("title")). + ToArrayExpression().As("taskTitles"), + )). + Execute(ctx) + // [END firestore_to_array_expression] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func toScalarExpression(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_to_scalar_expression] + snapshot := client.Pipeline(). + Collection("authors"). + Define([]*firestore.AliasedExpression{ + firestore.FieldOf("id").As("currentAuthorId"), + }). + AddFields(firestore.Selectables( + client.Pipeline(). + Collection("books"). + Where(firestore.FieldOf("author_id").Equal(firestore.Variable("currentAuthorId"))). + Aggregate(firestore.Accumulators(firestore.Average("rating").As("avgRating"))). + ToScalarExpression().As("averageBookRating"), + )). + Execute(ctx) + // [END firestore_to_scalar_expression] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func creatingIndexes(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_query_example] + snapshot := client.Pipeline(). + Collection("books"). + Where(firestore.FieldOf("published").LessThan(1900)). + Where(firestore.FieldOf("genre").Equal("Science Fiction")). + Where(firestore.FieldOf("rating").GreaterThan(4.3)). + Sort(firestore.Orders(firestore.Descending(firestore.FieldOf("published")))). + Execute(ctx) + // [END firestore_query_example] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func sparseIndexes(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sparse_index_example] + snapshot := client.Pipeline(). + Collection("books"). + Where(firestore.FieldOf("category").Like("%fantasy%")). + Execute(ctx) + // [END firestore_sparse_index_example] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func sparseIndexes2(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sparse_index_example_2] + snapshot := client.Pipeline(). + Collection("books"). + Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("release_date")))). + Execute(ctx) + // [END firestore_sparse_index_example_2] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func coveredQuery(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_covered_query] + snapshot := client.Pipeline(). + Collection("books"). + Where(firestore.FieldOf("category").Like("%fantasy%")). + Where(firestore.FieldOf("title").FieldExists()). + Where(firestore.FieldOf("author").FieldExists()). + Select(firestore.Fields("title", "author")). + Execute(ctx) + // [END firestore_covered_query] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func pagination(w io.Writer, client *firestore.Client) error { + // [START firestore_pagination_not_supported_preview] + // Existing pagination via `StartAt()` + query := client.Collection("cities").OrderBy("population", firestore.Asc).StartAt(1000000) + + pipeline := client.Pipeline(). + Collection("cities"). + Where(firestore.FieldOf("population").GreaterThanOrEqual(1000000)). + Sort(firestore.Orders(firestore.Descending(firestore.FieldOf("population")))) + // [END firestore_pagination_not_supported_preview] + fmt.Fprintln(w, query) + fmt.Fprintln(w, pipeline) + return nil +} + +func collectionStage(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_collection_example] + snapshot := client.Pipeline(). + Collection("users/bob/games"). + Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("name")))). + Execute(ctx) + // [END firestore_collection_example] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func collectionGroupStage(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_collection_group_example] + snapshot := client.Pipeline(). + CollectionGroup("games"). + Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("name")))). + Execute(ctx) + // [END firestore_collection_group_example] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func databaseStage(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_database_example] + // Count all documents in the database + snapshot := client.Pipeline(). + Database(). + Aggregate(firestore.Accumulators(firestore.CountAll().As("total"))). + Execute(ctx) + // [END firestore_database_example] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func documentsStage(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_documents_example] + snapshot := client.Pipeline(). + Documents([]*firestore.DocumentRef{ + client.Collection("cities").Doc("SF"), + client.Collection("cities").Doc("DC"), + client.Collection("cities").Doc("NY"), + }). + Execute(ctx) + // [END firestore_documents_example] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func replaceWithStage(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_initial_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "population": 800000, + "location": map[string]any{ + "country": "USA", + "state": "California", + }, + }) + client.Collection("cities").Doc("TO").Set(ctx, map[string]any{ + "name": "Toronto", + "population": 3000000, + "province": "ON", + "location": map[string]any{ + "country": "Canada", + "province": "Ontario", + }, + }) + client.Collection("cities").Doc("NY").Set(ctx, map[string]any{ + "name": "New York", + "population": 8500000, + "location": map[string]any{ + "country": "USA", + "state": "New York", + }, + }) + client.Collection("cities").Doc("AT").Set(ctx, map[string]any{ + "name": "Atlantis", + }) + // [END firestore_initial_data] + + // [START firestore_full_replace] + snapshot := client.Pipeline(). + Collection("cities"). + ReplaceWith(firestore.FieldOf("location")). + Execute(ctx) + // [END firestore_full_replace] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + + // [START firestore_map_merge_overwrite] + // unsupported in client SDKs for now + // [END firestore_map_merge_overwrite] + fmt.Fprintln(w, results) + return nil +} + +func sampleStage(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sample_example] + // Get a sample of 100 documents in a database + results1, err := client.Pipeline().Database().Sample(firestore.WithDocLimit(100)).Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + + // Randomly shuffle a list of 3 documents + results2, err := client.Pipeline(). + Documents([]*firestore.DocumentRef{ + client.Collection("cities").Doc("SF"), + client.Collection("cities").Doc("NY"), + client.Collection("cities").Doc("DC"), + }). + Sample(firestore.WithDocLimit(3)). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + // [END firestore_sample_example] + fmt.Fprintln(w, results1) + fmt.Fprintln(w, results2) + return nil +} + +func samplePercent(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sample_percent] + // Get a sample of on average 50% of the documents in the database + snapshot := client.Pipeline(). + Database(). + Sample(firestore.WithPercentage(0.5)). + Execute(ctx) + // [END firestore_sample_percent] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func sampleSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sample_syntax] + sampled1, err := client.Pipeline().Database().Sample(firestore.WithDocLimit(50)).Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + + sampled2, err := client.Pipeline().Database().Sample(firestore.WithPercentage(0.5)).Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + // [END firestore_sample_syntax] + fmt.Fprintln(w, sampled1) + fmt.Fprintln(w, sampled2) + return nil +} + +func sampleDocumentsDataExample(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sample_documents_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "state": "California", + }) + client.Collection("cities").Doc("NYC").Set(ctx, map[string]any{ + "name": "New York City", + "state": "New York", + }) + client.Collection("cities").Doc("CHI").Set(ctx, map[string]any{ + "name": "Chicago", + "state": "Illinois", + }) + // [END firestore_sample_documents_data] + return nil +} + +func sampleDocumentsExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sample_documents] + snapshot := client.Pipeline().Collection("cities").Sample(firestore.WithDocLimit(1)).Execute(ctx) + // [END firestore_sample_documents] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func sampleAllDocumentsExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sample_all_documents] + snapshot := client.Pipeline().Collection("cities").Sample(firestore.WithDocLimit(5)).Execute(ctx) + // [END firestore_sample_all_documents] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func samplePercentageDataExample(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sample_percentage_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "state": "California", + }) + client.Collection("cities").Doc("NYC").Set(ctx, map[string]any{ + "name": "New York City", + "state": "New York", + }) + client.Collection("cities").Doc("CHI").Set(ctx, map[string]any{ + "name": "Chicago", + "state": "Illinois", + }) + client.Collection("cities").Doc("ATL").Set(ctx, map[string]any{ + "name": "Atlanta", + "state": "Georgia", + }) + // [END firestore_sample_percentage_data] + return nil +} + +func samplePercentageExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_sample_percentage] + snapshot := client.Pipeline().Collection("cities").Sample(firestore.WithPercentage(0.5)).Execute(ctx) + // [END firestore_sample_percentage] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func unionStage(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_union_stage] + snapshot := client.Pipeline(). + Collection("cities/SF/restaurants"). + Where(firestore.FieldOf("type").Equal("Chinese")). + Union( + client.Pipeline(). + Collection("cities/NY/restaurants"). + Where(firestore.FieldOf("type").Equal("Italian")), + ). + Where(firestore.FieldOf("rating").GreaterThanOrEqual(4.5)). + Sort(firestore.Orders(firestore.Descending(firestore.FieldOf("__name__")))). + Execute(ctx) + // [END firestore_union_stage] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func unionStageStable(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_union_stage_stable] + snapshot := client.Pipeline(). + Collection("cities/SF/restaurants"). + Where(firestore.FieldOf("type").Equal("Chinese")). + Union( + client.Pipeline(). + Collection("cities/NY/restaurants"). + Where(firestore.FieldOf("type").Equal("Italian")), + ). + Where(firestore.FieldOf("rating").GreaterThanOrEqual(4.5)). + Sort(firestore.Orders(firestore.Descending(firestore.FieldOf("__name__")))). + Execute(ctx) + // [END firestore_union_stage_stable] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func offsetSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_offset_syntax] + snapshot := client.Pipeline().Collection("cities").Offset(10).Execute(ctx) + // [END firestore_offset_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func collectionInputSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_collection_input_syntax] + snapshot := client.Pipeline().Collection("cities/SF/departments").Execute(ctx) + // [END firestore_collection_input_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func collectionInputExampleData(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_collection_input_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "state": "California", + }) + client.Collection("cities").Doc("NYC").Set(ctx, map[string]any{ + "name": "New York City", + "state": "New York", + }) + client.Collection("cities").Doc("CHI").Set(ctx, map[string]any{ + "name": "Chicago", + "state": "Illinois", + }) + client.Collection("states").Doc("CA").Set(ctx, map[string]any{ + "name": "California", + }) + // [END firestore_collection_input_data] + return nil +} + +func collectionInputExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_collection_input] + snapshot := client.Pipeline().Collection("cities"). + Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("name")))). + Execute(ctx) + // [END firestore_collection_input] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func subcollectionInputExampleData(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_subcollection_input_data] + client.Collection("cities/SF/departments").Doc("building").Set(ctx, map[string]any{ + "name": "SF Building Department", + "employees": 750, + }) + client.Collection("cities/NY/departments").Doc("building").Set(ctx, map[string]any{ + "name": "NY Building Department", + "employees": 1000, + }) + client.Collection("cities/CHI/departments").Doc("building").Set(ctx, map[string]any{ + "name": "CHI Building Department", + "employees": 900, + }) + client.Collection("cities/NY/departments").Doc("finance").Set(ctx, map[string]any{ + "name": "NY Finance Department", + "employees": 1200, + }) + // [END firestore_subcollection_input_data] + return nil +} + +func subcollectionInputExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_subcollection_input] + snapshot := client.Pipeline().Collection("cities/NY/departments"). + Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("employees")))). + Execute(ctx) + // [END firestore_subcollection_input] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func collectionGroupInputSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_collection_group_input_syntax] + snapshot := client.Pipeline().CollectionGroup("departments").Execute(ctx) + // [END firestore_collection_group_input_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func collectionGroupInputExampleData(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_collection_group_data] + client.Collection("cities/SF/departments").Doc("building").Set(ctx, map[string]any{ + "name": "SF Building Department", + "employees": 750, + }) + client.Collection("cities/NY/departments").Doc("building").Set(ctx, map[string]any{ + "name": "NY Building Department", + "employees": 1000, + }) + client.Collection("cities/CHI/departments").Doc("building").Set(ctx, map[string]any{ + "name": "CHI Building Department", + "employees": 900, + }) + client.Collection("cities/NY/departments").Doc("finance").Set(ctx, map[string]any{ + "name": "NY Finance Department", + "employees": 1200, + }) + // [END firestore_collection_group_data] + return nil +} + +func collectionGroupInputExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_collection_group_input] + snapshot := client.Pipeline().CollectionGroup("departments"). + Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("employees")))). + Execute(ctx) + // [END firestore_collection_group_input] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func databaseInputSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_database_syntax] + snapshot := client.Pipeline().Database().Execute(ctx) + // [END firestore_database_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func databaseInputSyntaxExampleData(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_database_input_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "state": "California", + "population": 800000, + }) + client.Collection("states").Doc("CA").Set(ctx, map[string]any{ + "name": "California", + "population": 39000000, + }) + client.Collection("countries").Doc("USA").Set(ctx, map[string]any{ + "name": "United States of America", + "population": 340000000, + }) + // [END firestore_database_input_data] + return nil +} + +func databaseInputExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_database_input] + snapshot := client.Pipeline().Database(). + Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("population")))). + Execute(ctx) + // [END firestore_database_input] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func documentInputSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_document_input_syntax] + snapshot := client.Pipeline(). + Documents([]*firestore.DocumentRef{ + client.Collection("cities").Doc("SF"), + client.Collection("cities").Doc("NY"), + }). + Execute(ctx) + // [END firestore_document_input_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func documentInputExampleData(_ io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_document_input_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "state": "California", + }) + client.Collection("cities").Doc("NYC").Set(ctx, map[string]any{ + "name": "New York City", + "state": "New York", + }) + client.Collection("cities").Doc("CHI").Set(ctx, map[string]any{ + "name": "Chicago", + "state": "Illinois", + }) + // [END firestore_document_input_data] + return nil +} + +func documentInputExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_document_input] + snapshot := client.Pipeline(). + Documents([]*firestore.DocumentRef{ + client.Collection("cities").Doc("SF"), + client.Collection("cities").Doc("NYC"), + }). + Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("name")))). + Execute(ctx) + // [END firestore_document_input] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func limitSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_limit_syntax] + snapshot := client.Pipeline().Collection("cities").Limit(10).Execute(ctx) + // [END firestore_limit_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func unionSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_union_syntax] + snapshot := client.Pipeline(). + Collection("cities/SF/restaurants"). + Union(client.Pipeline().Collection("cities/NYC/restaurants")). + Execute(ctx) + // [END firestore_union_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func forceIndexExamples(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_force_index] + // Force Planner to use Index ID CICAgOi36pgK + snapshot1 := client.Pipeline(). + CollectionGroup("customers", firestore.WithForceIndex("CICAgOi36pgK")). + Limit(100). + Execute(ctx) + // [END firestore_force_index] + results1, err := snapshot1.Results().GetAll() + if err != nil { + return err + } + fmt.Fprintln(w, results1) + + // [START firestore_force_scan] + // Force Planner to only do a collection scan + snapshot2 := client.Pipeline(). + CollectionGroup("customers", firestore.WithForceIndex("primary")). + Limit(100). + Execute(ctx) + // [END firestore_force_scan] + results2, err := snapshot2.Results().GetAll() + if err != nil { + return err + } + fmt.Fprintln(w, results2) + return nil +} + +func stagesExpressionsExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_stages_expressions_example] + nowMillis := firestore.ConstantOf(1712404800000) // Example timestamp + trailing30Days := nowMillis.UnixMillisToTimestamp().TimestampSubtract("day", 30) + + snapshot := client.Pipeline(). + Collection("productViews"). + Where(firestore.FieldOf("viewedAt").GreaterThan(trailing30Days)). + Aggregate(firestore.Accumulators(firestore.CountDistinct("productId").As("uniqueProductViews"))). + Execute(ctx) + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + // [END firestore_stages_expressions_example] + fmt.Fprintln(w, results) + return nil +} + +func wherePipeline(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_pipeline_where] + results1, err := client.Pipeline(). + Collection("books"). + Where(firestore.FieldOf("rating").Equal(5)). + Where(firestore.FieldOf("published").LessThan(1900)). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + + results2, err := client.Pipeline(). + Collection("books"). + Where(firestore.And( + firestore.FieldOf("rating").Equal(5), + firestore.FieldOf("published").LessThan(1900), + )). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + // [END firestore_pipeline_where] + fmt.Fprintln(w, results1) + fmt.Fprintln(w, results2) + return nil +} + +func whereEqualityExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_where_equality_example] + snapshot := client.Pipeline().Collection("cities"). + Where(firestore.FieldOf("state").Equal("CA")). + Execute(ctx) + // [END firestore_where_equality_example] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func whereMultipleStagesExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_where_multiple_stages] + snapshot := client.Pipeline().Collection("cities"). + Where(firestore.FieldOf("location.country").Equal("USA")). + Where(firestore.FieldOf("population").GreaterThan(500000)). + Execute(ctx) + // [END firestore_where_multiple_stages] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func whereComplexExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_where_complex] + snapshot := client.Pipeline().Collection("cities"). + Where( + firestore.Or( + firestore.Like(firestore.FieldOf("name"), "San%"), + firestore.And( + firestore.FieldOf("location.state").CharLength().GreaterThan(7), + firestore.FieldOf("location.country").Equal("USA"), + ), + ), + ). + Execute(ctx) + // [END firestore_where_complex] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func whereStageOrderExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_where_stage_order] + snapshot := client.Pipeline().Collection("cities"). + Limit(10). + Where(firestore.FieldOf("location.country").Equal("USA")). + Execute(ctx) + // [END firestore_where_stage_order] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func createWhereData(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_create_where_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "state": "CA", + "country": "USA", + "population": 870000, + }) + client.Collection("cities").Doc("LA").Set(ctx, map[string]any{ + "name": "Los Angeles", + "state": "CA", + "country": "USA", + "population": 3970000, + }) + client.Collection("cities").Doc("NY").Set(ctx, map[string]any{ + "name": "New York", + "state": "NY", + "country": "USA", + "population": 8530000, + }) + client.Collection("cities").Doc("TOR").Set(ctx, map[string]any{ + "name": "Toronto", + "state": nil, + "country": "Canada", + "population": 2930000, + }) + client.Collection("cities").Doc("MEX").Set(ctx, map[string]any{ + "name": "Mexico City", + "state": nil, + "country": "Mexico", + "population": 9200000, + }) + // [END firestore_create_where_data] + return nil +} + +func whereHavingExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_where_having_example] + snapshot := client.Pipeline(). + Collection("cities"). + Aggregate( + firestore.Accumulators(firestore.Sum("population").As("totalPopulation")), + firestore.WithAggregateGroups(firestore.FieldOf("state")), + ). + Where(firestore.FieldOf("totalPopulation").GreaterThan(10000000)). + Execute(ctx) + // [END firestore_where_having_example] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func pipelineConcepts(w io.Writer, client *firestore.Client) error { + // [START firestore_pipeline_concepts] + pipeline := client.Pipeline(). + Collection("cities"). + Where(firestore.FieldOf("population").GreaterThan(100000)). + Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("name")))). + Limit(10) + // [END firestore_pipeline_concepts] + fmt.Fprintln(w, pipeline) + return nil +} + +func basicRead(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_basic_read] + pipeline := client.Pipeline().Collection("users") + snapshot := pipeline.Execute(ctx) + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + for _, result := range results { + fmt.Fprintf(w, "%s => %v\n", result.Ref().ID, result.Data()) + } + // or, one at a time + it := pipeline.Execute(ctx).Results() + for { + result, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + fmt.Fprintf(w, "it.Next failed: %v", err) + return err + } + fmt.Fprintf(w, "%s => %v\n", result.Ref().ID, result.Data()) + } + // [END firestore_basic_read] + return nil +} + +func pipelineInitialization(w io.Writer, projectID string) error { + ctx := context.Background() + // [START firestore_pipeline_initialization] + client, err := firestore.NewClient(ctx, projectID) + if err != nil { + fmt.Fprintf(w, "firestore.NewClient failed: %v", err) + return err + } + pipeline := client.Pipeline().Collection("books") + // [END firestore_pipeline_initialization] + fmt.Fprintln(w, pipeline) + defer client.Close() + return nil +} + +func fieldVsConstants(w io.Writer, client *firestore.Client) error { + // [START firestore_field_or_constant] + pipeline := client.Pipeline().Collection("cities"). + Where(firestore.FieldOf("name").Equal(firestore.ConstantOf("Toronto"))) + // [END firestore_field_or_constant] + fmt.Fprintln(w, pipeline) + return nil +} + +func inputStages(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_input_stages] + // Return all restaurants in San Francisco + results1, err := client.Pipeline().Collection("cities/sf/restaurants").Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + + // Return all restaurants + results2, err := client.Pipeline().CollectionGroup("restaurants").Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + + // Return all documents across all collections in the database (the entire database) + results3, err := client.Pipeline().Database().Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + + // Batch read of 3 documents + results4, err := client.Pipeline(). + Documents([]*firestore.DocumentRef{ + client.Collection("cities").Doc("SF"), + client.Collection("cities").Doc("DC"), + client.Collection("cities").Doc("NY"), + }). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + // [END firestore_input_stages] + fmt.Fprintln(w, results1) + fmt.Fprintln(w, results2) + fmt.Fprintln(w, results3) + fmt.Fprintln(w, results4) + return nil +} + +func unnestStage(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_stage] + snapshot := client.Pipeline(). + Database(). + UnnestWithAlias("arrayField", "unnestedArrayField", firestore.WithUnnestIndexField("index")). + Execute(ctx) + // [END firestore_unnest_stage] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func unnestStageEmptyOrNonArray(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_edge_cases] + // Input + // { "identifier" : 1, "neighbors": [ "Alice", "Cathy" ] } + // { "identifier" : 2, "neighbors": [] } + // { "identifier" : 3, "neighbors": "Bob" } + + results, err := client.Pipeline(). + Database(). + UnnestWithAlias("neighbors", "unnestedNeighbors", firestore.WithUnnestIndexField("index")). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + + // Output + // { "identifier": 1, "neighbors": [ "Alice", "Cathy" ], + // "unnestedNeighbors": "Alice", "index": 0 } + // { "identifier": 1, "neighbors": [ "Alice", "Cathy" ], + // "unnestedNeighbors": "Cathy", "index": 1 } + // { "identifier": 3, "neighbors": "Bob", "index": nil} + // [END firestore_unnest_edge_cases] + fmt.Fprintln(w, results) + return nil +} + +func unnestSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_syntax] + snapshot := client.Pipeline().Collection("users"). + UnnestWithAlias("scores", "userScore", firestore.WithUnnestIndexField("attempt")). + Execute(ctx) + // [END firestore_unnest_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func unnestAliasIndexDataExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_alias_index_data] + client.Collection("users").Add(ctx, map[string]any{ + "name": "foo", + "scores": []int{5, 4}, + "userScore": 0, + }) + client.Collection("users").Add(ctx, map[string]any{ + "name": "bar", + "scores": []int{1, 3}, + "attempt": 5, + }) + // [END firestore_unnest_alias_index_data] + return nil +} + +func unnestAliasIndexExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_alias_index] + snapshot := client.Pipeline().Collection("users"). + UnnestWithAlias("scores", "userScore", firestore.WithUnnestIndexField("attempt")). + Execute(ctx) + // [END firestore_unnest_alias_index] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func unnestNonArrayDataExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_nonarray_data] + client.Collection("users").Add(ctx, map[string]any{ + "name": "foo", + "scores": 1, + }) + client.Collection("users").Add(ctx, map[string]any{ + "name": "bar", + "scores": nil, + }) + client.Collection("users").Add(ctx, map[string]any{ + "name": "qux", + "scores": map[string]any{ + "backupScores": 1, + }, + }) + // [END firestore_unnest_nonarray_data] + return nil +} + +func unnestNonArrayExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_nonarray] + snapshot := client.Pipeline().Collection("users"). + UnnestWithAlias("scores", "userScore", firestore.WithUnnestIndexField("attempt")). + Execute(ctx) + // [END firestore_unnest_nonarray] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func unnestEmptyArrayDataExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_empty_array_data] + client.Collection("users").Add(ctx, map[string]any{ + "name": "foo", + "scores": []int{5, 4}, + }) + client.Collection("users").Add(ctx, map[string]any{ + "name": "bar", + "scores": []int{}, + }) + // [END firestore_unnest_empty_array_data] + return nil +} + +func unnestEmptyArrayExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_empty_array] + snapshot := client.Pipeline().Collection("users"). + UnnestWithAlias("scores", "userScore", firestore.WithUnnestIndexField("attempt")). + Execute(ctx) + // [END firestore_unnest_empty_array] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func unnestPreserveEmptyArrayExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_preserve_empty_array] + userScore, err := client.Pipeline(). + Collection("users"). + Unnest(firestore.Conditional( + firestore.FieldOf("scores").Equal([]any{}), + firestore.Array(firestore.FieldOf("scores")), + firestore.FieldOf("scores"), + ).As("userScore"), firestore.WithUnnestIndexField("attempt")). + Execute(ctx).Results().GetAll() + if err != nil { + fmt.Fprintf(w, "GetAll failed: %v", err) + return err + } + // [END firestore_unnest_preserve_empty_array] + fmt.Fprintln(w, userScore) + return nil +} + +func unnestNestedDataExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_nested_data] + client.Collection("users").Add(ctx, map[string]any{ + "name": "foo", + "record": []any{ + map[string]any{ + "scores": []int{5, 4}, + "avg": 4.5, + }, + map[string]any{ + "scores": []int{1, 3}, + "old_avg": 2, + }, + }, + }) + // [END firestore_unnest_nested_data] + return nil +} + +func unnestNestedExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_unnest_nested] + snapshot := client.Pipeline().Collection("users"). + UnnestWithAlias("record", "record"). + UnnestWithAlias("record.scores", "userScore", firestore.WithUnnestIndexField("attempt")). + Execute(ctx) + // [END firestore_unnest_nested] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func findNearestSyntaxExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_find_nearest_syntax] + snapshot := client.Pipeline().Collection("cities"). + FindNearest("embedding", []float64{1.5, 2.345}, firestore.PipelineDistanceMeasureEuclidean). + Execute(ctx) + // [END firestore_find_nearest_syntax] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func findNearestLimitExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_find_nearest_limit] + snapshot := client.Pipeline().Collection("cities"). + FindNearest("embedding", []float64{1.5, 2.345}, firestore.PipelineDistanceMeasureEuclidean, firestore.WithFindNearestLimit(10)). + Execute(ctx) + // [END firestore_find_nearest_limit] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func findNearestDistanceDataExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_find_nearest_distance_data] + client.Collection("cities").Doc("SF").Set(ctx, map[string]any{ + "name": "San Francisco", + "embedding": []float64{1.0, -1.0}, + }) + client.Collection("cities").Doc("TO").Set(ctx, map[string]any{ + "name": "Toronto", + "embedding": []float64{5.0, -10.0}, + }) + client.Collection("cities").Doc("AT").Set(ctx, map[string]any{ + "name": "Atlantis", + "embedding": []float64{2.0, -4.0}, + }) + // [END firestore_find_nearest_distance_data] + return nil +} + +func findNearestDistanceExample(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_find_nearest_distance] + snapshot := client.Pipeline().Collection("cities"). + FindNearest("embedding", []float64{1.3, 2.345}, firestore.PipelineDistanceMeasureEuclidean, firestore.WithFindNearestDistanceField("computedDistance")). + Execute(ctx) + // [END firestore_find_nearest_distance] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} diff --git a/firestore/pipeline_snippets_logical.go b/firestore/pipeline_snippets_logical.go new file mode 100644 index 0000000000..e99bd59e3d --- /dev/null +++ b/firestore/pipeline_snippets_logical.go @@ -0,0 +1,191 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" +) + +func existsFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_exists_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.FieldExists(firestore.FieldOf("rating")).As("hasRating"), + )). + Execute(ctx) + // [END firestore_exists_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func andFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_and_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.And( + firestore.GreaterThan(firestore.FieldOf("rating"), 4), + firestore.LessThan(firestore.FieldOf("price"), 10), + ).As("under10Recommendation"), + )). + Execute(ctx) + // [END firestore_and_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func orFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_or_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Or( + firestore.Equal(firestore.FieldOf("genre"), "Fantasy"), + firestore.ArrayContains(firestore.FieldOf("tags"), "adventure"), + ).As("matchesSearchFilters"), + )). + Execute(ctx) + // [END firestore_or_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func xorFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_xor_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Xor( + firestore.ArrayContains(firestore.FieldOf("tags"), "magic"), + firestore.ArrayContains(firestore.FieldOf("tags"), "nonfiction"), + ).As("matchesSearchFilters"), + )). + Execute(ctx) + // [END firestore_xor_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func notFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_not_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Not(firestore.ArrayContains(firestore.FieldOf("tags"), "nonfiction")).As("isFiction"), + )). + Execute(ctx) + // [END firestore_not_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func condFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_cond_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.ArrayConcat( + firestore.FieldOf("tags"), + firestore.Conditional( + firestore.GreaterThan(firestore.FieldOf("pages"), 100), + firestore.ConstantOf("longRead"), + firestore.ConstantOf("shortRead"), + ), + ).As("extendedTags"), + )). + Execute(ctx) + // [END firestore_cond_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func maxLogicalFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_max_logical_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.LogicalMaximum(firestore.FieldOf("rating"), 1).As("flooredRating"), + )). + Execute(ctx) + // [END firestore_max_logical_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func minLogicalFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_min_logical_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.LogicalMinimum(firestore.FieldOf("rating"), 5).As("cappedRating"), + )). + Execute(ctx) + // [END firestore_min_logical_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} diff --git a/firestore/pipeline_snippets_object.go b/firestore/pipeline_snippets_object.go new file mode 100644 index 0000000000..171193baa0 --- /dev/null +++ b/firestore/pipeline_snippets_object.go @@ -0,0 +1,118 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" +) + +func mapGetFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_map_get] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.MapGet(firestore.FieldOf("awards"), "pulitzer").As("hasPulitzerAward"), + )). + Execute(ctx) + // [END firestore_map_get] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func mapSetFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_map_set] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.MapSet(firestore.FieldOf("awards"), "pulitzer", true).As("awards"), + )). + Execute(ctx) + // [END firestore_map_set] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func mapKeysFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_map_keys] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.MapKeys(firestore.FieldOf("awards")).As("award_categories"), + )). + Execute(ctx) + // [END firestore_map_keys] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func mapValuesFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_map_values] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.MapValues(firestore.FieldOf("awards")).As("award_details"), + )). + Execute(ctx) + // [END firestore_map_values] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func mapEntriesFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_map_entries] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.MapEntries(firestore.FieldOf("awards")).As("awards_list"), + )). + Execute(ctx) + // [END firestore_map_entries] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} diff --git a/firestore/pipeline_snippets_string.go b/firestore/pipeline_snippets_string.go new file mode 100644 index 0000000000..3163a00171 --- /dev/null +++ b/firestore/pipeline_snippets_string.go @@ -0,0 +1,442 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" +) + +func byteLengthFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_byte_length] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.ByteLength(firestore.FieldOf("title")).As("titleByteLength"), + )). + Execute(ctx) + // [END firestore_byte_length] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func charLengthFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_char_length] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.CharLength(firestore.FieldOf("title")).As("titleCharLength"), + )). + Execute(ctx) + // [END firestore_char_length] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func startsWithFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_starts_with] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.StartsWith(firestore.FieldOf("title"), "The").As("needsSpecialAlphabeticalSort"), + )). + Execute(ctx) + // [END firestore_starts_with] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func endsWithFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_ends_with] + snapshot := client.Pipeline(). + Collection("inventory/devices/laptops"). + Select(firestore.Fields( + firestore.EndsWith(firestore.FieldOf("name"), "16 inch").As("`Laptops16in`"), + )). + Execute(ctx) + // [END firestore_ends_with] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func likeFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_like] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Like(firestore.FieldOf("genre"), "%Fiction").As("anyFiction"), + )). + Execute(ctx) + // [END firestore_like] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func regexContainsFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_regex_contains] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.RegexContains(firestore.FieldOf("title"), "Firestore (Enterprise|Standard)").As("isFirestoreRelated"), + )). + Execute(ctx) + // [END firestore_regex_contains] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func regexFindFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_regex_find] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.RegexFind(firestore.FieldOf("email"), "@[A-Za-z0-9.-]+").As("domain"), + )). + Execute(ctx) + // [END firestore_regex_find] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func regexFindAllFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_regex_find_all] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.RegexFindAll(firestore.FieldOf("comment"), "@[A-Za-z0-9_]+").As("mentions"), + )). + Execute(ctx) + // [END firestore_regex_find_all] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func regexMatchFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_regex_match] + snapshot := client.Pipeline(). + Collection("documents"). + Select(firestore.Fields( + firestore.RegexMatch(firestore.FieldOf("title"), "Firestore (Enterprise|Standard)").As("isFirestoreExactly"), + )). + Execute(ctx) + // [END firestore_regex_match] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func strConcatFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_str_concat] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.StringConcat(firestore.FieldOf("title"), " by ", firestore.FieldOf("author")).As("fullyQualifiedTitle"), + )). + Execute(ctx) + // [END firestore_str_concat] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func strContainsFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_string_contains] + snapshot := client.Pipeline(). + Collection("articles"). + Select(firestore.Fields( + firestore.StringContains(firestore.FieldOf("body"), "Firestore").As("isFirestoreRelated"), + )). + Execute(ctx) + // [END firestore_string_contains] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func toUpperFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_to_upper] + snapshot := client.Pipeline(). + Collection("authors"). + Select(firestore.Fields( + firestore.ToUpper(firestore.FieldOf("name")).As("uppercaseName"), + )). + Execute(ctx) + // [END firestore_to_upper] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func toLowerFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_to_lower] + snapshot := client.Pipeline(). + Collection("authors"). + Select(firestore.Fields( + firestore.Equal(firestore.ToLower(firestore.FieldOf("genre")), "fantasy").As("isFantasy"), + )). + Execute(ctx) + // [END firestore_to_lower] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func substrFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_substr_function] + snapshot := client.Pipeline(). + Collection("books"). + Where(firestore.StartsWith(firestore.FieldOf("title"), "The ")). + Select(firestore.Fields( + firestore.Substring(firestore.FieldOf("title"), firestore.ConstantOf(4), firestore.FieldOf("title").CharLength()).As("titleWithoutLeadingThe"), + )). + Execute(ctx) + // [END firestore_substr_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func strReverseFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_str_reverse] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Reverse(firestore.FieldOf("name")).As("reversedName"), + )). + Execute(ctx) + // [END firestore_str_reverse] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func strTrimFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_trim_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.Trim(firestore.FieldOf("name")).As("whitespaceTrimmedName"), + )). + Execute(ctx) + // [END firestore_trim_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func strLTrimFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_ltrim_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.LTrim(firestore.FieldOf("name")).As("ltrimmedName"), + )). + Execute(ctx) + // [END firestore_ltrim_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func strRTrimFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_rtrim_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.RTrim(firestore.FieldOf("name")).As("rtrimmedName"), + )). + Execute(ctx) + // [END firestore_rtrim_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func strRepeatFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_string_repeat_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.StringRepeat(firestore.FieldOf("title"), 2).As("repeatedTitle"), + )). + Execute(ctx) + // [END firestore_string_repeat_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func strReplaceAllFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_string_replace_all_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.StringReplaceAll(firestore.FieldOf("title"), "The", "A").As("replacedTitle"), + )). + Execute(ctx) + // [END firestore_string_replace_all_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func strReplaceOneFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_string_replace_one_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.StringReplaceOne(firestore.FieldOf("title"), "The", "A").As("replacedTitle"), + )). + Execute(ctx) + // [END firestore_string_replace_one_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func strIndexOfFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_string_index_of_function] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.StringIndexOf(firestore.FieldOf("title"), "The").As("indexOfThe"), + )). + Execute(ctx) + // [END firestore_string_index_of_function] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} diff --git a/firestore/pipeline_snippets_test.go b/firestore/pipeline_snippets_test.go new file mode 100644 index 0000000000..fe35d1a8b9 --- /dev/null +++ b/firestore/pipeline_snippets_test.go @@ -0,0 +1,1362 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "bytes" + "context" + "os" + "testing" + + "cloud.google.com/go/firestore" +) + +func TestPipelineSnippets(t *testing.T) { + projectID := os.Getenv("GOLANG_SAMPLES_FIRESTORE_PROJECT") + if projectID == "" { + t.Skip("Skipping firestore test. Set GOLANG_SAMPLES_FIRESTORE_PROJECT.") + } + + databaseID := os.Getenv("GOLANG_SAMPLES_FIRESTORE_ENTERPRISE_DATABASE") + if databaseID == "" { + t.Skip("Skipping firestore enterprise test. Set GOLANG_SAMPLES_FIRESTORE_ENTERPRISE_DATABASE.") + } + + ctx := context.Background() + + client, err := firestore.NewClientWithDatabase(ctx, projectID, databaseID) + if err != nil { + t.Fatalf("firestore.NewClient: %v", err) + } + defer client.Close() + + buf := new(bytes.Buffer) + + t.Run("pipelineConcepts", func(t *testing.T) { + buf.Reset() + if err := pipelineConcepts(buf, client); err != nil { + t.Errorf("pipelineConcepts failed: %v", err) + } + }) + + t.Run("basicRead", func(t *testing.T) { + buf.Reset() + if err := basicRead(buf, client); err != nil { + t.Errorf("basicRead failed: %v", err) + } + }) + + t.Run("fieldVsConstants", func(t *testing.T) { + buf.Reset() + if err := fieldVsConstants(buf, client); err != nil { + t.Errorf("fieldVsConstants failed: %v", err) + } + }) + + t.Run("inputStages", func(t *testing.T) { + buf.Reset() + if err := inputStages(buf, client); err != nil { + t.Errorf("inputStages failed: %v", err) + } + }) + + t.Run("wherePipeline", func(t *testing.T) { + buf.Reset() + if err := wherePipeline(buf, client); err != nil { + t.Errorf("wherePipeline failed: %v", err) + } + }) + + t.Run("aggregateGroups", func(t *testing.T) { + buf.Reset() + if err := aggregateGroups(buf, client); err != nil { + t.Errorf("aggregateGroups failed: %v", err) + } + }) + + t.Run("aggregateDistinct", func(t *testing.T) { + buf.Reset() + if err := aggregateDistinct(buf, client); err != nil { + t.Errorf("aggregateDistinct failed: %v", err) + } + }) + + t.Run("sort", func(t *testing.T) { + buf.Reset() + if err := sort(buf, client); err != nil { + t.Errorf("sort failed: %v", err) + } + }) + + t.Run("sortComparison", func(t *testing.T) { + buf.Reset() + if err := sortComparison(buf, client); err != nil { + t.Errorf("sortComparison failed: %v", err) + } + }) + + t.Run("functionsExample", func(t *testing.T) { + buf.Reset() + if err := functionsExample(buf, client); err != nil { + t.Errorf("functionsExample failed: %v", err) + } + }) + + t.Run("creatingIndexes", func(t *testing.T) { + buf.Reset() + if err := creatingIndexes(buf, client); err != nil { + t.Errorf("creatingIndexes failed: %v", err) + } + }) + + t.Run("sparseIndexes", func(t *testing.T) { + buf.Reset() + if err := sparseIndexes(buf, client); err != nil { + t.Errorf("sparseIndexes failed: %v", err) + } + }) + + t.Run("sparseIndexes2", func(t *testing.T) { + buf.Reset() + if err := sparseIndexes2(buf, client); err != nil { + t.Errorf("sparseIndexes2 failed: %v", err) + } + }) + + t.Run("coveredQuery", func(t *testing.T) { + buf.Reset() + if err := coveredQuery(buf, client); err != nil { + t.Errorf("coveredQuery failed: %v", err) + } + }) + + t.Run("pagination", func(t *testing.T) { + buf.Reset() + if err := pagination(buf, client); err != nil { + t.Errorf("pagination failed: %v", err) + } + }) + + t.Run("collectionStage", func(t *testing.T) { + buf.Reset() + if err := collectionStage(buf, client); err != nil { + t.Errorf("collectionStage failed: %v", err) + } + }) + + t.Run("collectionGroupStage", func(t *testing.T) { + buf.Reset() + if err := collectionGroupStage(buf, client); err != nil { + t.Errorf("collectionGroupStage failed: %v", err) + } + }) + + t.Run("databaseStage", func(t *testing.T) { + buf.Reset() + if err := databaseStage(buf, client); err != nil { + t.Errorf("databaseStage failed: %v", err) + } + }) + + t.Run("documentsStage", func(t *testing.T) { + buf.Reset() + if err := documentsStage(buf, client); err != nil { + t.Errorf("documentsStage failed: %v", err) + } + }) + + t.Run("replaceWithStage", func(t *testing.T) { + buf.Reset() + if err := replaceWithStage(buf, client); err != nil { + t.Errorf("replaceWithStage failed: %v", err) + } + }) + + t.Run("sampleStage", func(t *testing.T) { + buf.Reset() + if err := sampleStage(buf, client); err != nil { + t.Errorf("sampleStage failed: %v", err) + } + }) + + t.Run("samplePercent", func(t *testing.T) { + buf.Reset() + if err := samplePercent(buf, client); err != nil { + t.Errorf("samplePercent failed: %v", err) + } + }) + + t.Run("unionStage", func(t *testing.T) { + buf.Reset() + if err := unionStage(buf, client); err != nil { + t.Errorf("unionStage failed: %v", err) + } + }) + + t.Run("unionStageStable", func(t *testing.T) { + buf.Reset() + if err := unionStageStable(buf, client); err != nil { + t.Errorf("unionStageStable failed: %v", err) + } + }) + + t.Run("unnestStage", func(t *testing.T) { + buf.Reset() + if err := unnestStage(buf, client); err != nil { + t.Errorf("unnestStage failed: %v", err) + } + }) + + t.Run("unnestStageEmptyOrNonArray", func(t *testing.T) { + buf.Reset() + if err := unnestStageEmptyOrNonArray(buf, client); err != nil { + t.Errorf("unnestStageEmptyOrNonArray failed: %v", err) + } + }) + + t.Run("countFunction", func(t *testing.T) { + buf.Reset() + if err := countFunction(buf, client); err != nil { + t.Errorf("countFunction failed: %v", err) + } + }) + + t.Run("countIfFunction", func(t *testing.T) { + buf.Reset() + if err := countIfFunction(buf, client); err != nil { + t.Errorf("countIfFunction failed: %v", err) + } + }) + + t.Run("countDistinctFunction", func(t *testing.T) { + buf.Reset() + if err := countDistinctFunction(buf, client); err != nil { + t.Errorf("countDistinctFunction failed: %v", err) + } + }) + + t.Run("sumFunction", func(t *testing.T) { + buf.Reset() + if err := sumFunction(buf, client); err != nil { + t.Errorf("sumFunction failed: %v", err) + } + }) + + t.Run("avgFunction", func(t *testing.T) { + buf.Reset() + if err := avgFunction(buf, client); err != nil { + t.Errorf("avgFunction failed: %v", err) + } + }) + + t.Run("minFunction", func(t *testing.T) { + buf.Reset() + if err := minFunction(buf, client); err != nil { + t.Errorf("minFunction failed: %v", err) + } + }) + + t.Run("maxFunction", func(t *testing.T) { + buf.Reset() + if err := maxFunction(buf, client); err != nil { + t.Errorf("maxFunction failed: %v", err) + } + }) + + t.Run("addFunction", func(t *testing.T) { + buf.Reset() + if err := addFunction(buf, client); err != nil { + t.Errorf("addFunction failed: %v", err) + } + }) + + t.Run("subtractFunction", func(t *testing.T) { + buf.Reset() + if err := subtractFunction(buf, client); err != nil { + t.Errorf("subtractFunction failed: %v", err) + } + }) + + t.Run("multiplyFunction", func(t *testing.T) { + buf.Reset() + if err := multiplyFunction(buf, client); err != nil { + t.Errorf("multiplyFunction failed: %v", err) + } + }) + + t.Run("divideFunction", func(t *testing.T) { + buf.Reset() + if err := divideFunction(buf, client); err != nil { + t.Errorf("divideFunction failed: %v", err) + } + }) + + t.Run("modFunction", func(t *testing.T) { + buf.Reset() + if err := modFunction(buf, client); err != nil { + t.Errorf("modFunction failed: %v", err) + } + }) + + t.Run("ceilFunction", func(t *testing.T) { + buf.Reset() + if err := ceilFunction(buf, client); err != nil { + t.Errorf("ceilFunction failed: %v", err) + } + }) + + t.Run("floorFunction", func(t *testing.T) { + buf.Reset() + if err := floorFunction(buf, client); err != nil { + t.Errorf("floorFunction failed: %v", err) + } + }) + + t.Run("roundFunction", func(t *testing.T) { + buf.Reset() + if err := roundFunction(buf, client); err != nil { + t.Errorf("roundFunction failed: %v", err) + } + }) + + t.Run("powFunction", func(t *testing.T) { + buf.Reset() + if err := powFunction(buf, client); err != nil { + t.Errorf("powFunction failed: %v", err) + } + }) + + t.Run("sqrtFunction", func(t *testing.T) { + buf.Reset() + if err := sqrtFunction(buf, client); err != nil { + t.Errorf("sqrtFunction failed: %v", err) + } + }) + + t.Run("expFunction", func(t *testing.T) { + buf.Reset() + if err := expFunction(buf, client); err != nil { + t.Errorf("expFunction failed: %v", err) + } + }) + + t.Run("lnFunction", func(t *testing.T) { + buf.Reset() + if err := lnFunction(buf, client); err != nil { + t.Errorf("lnFunction failed: %v", err) + } + }) + + t.Run("logFunction", func(t *testing.T) { + buf.Reset() + if err := logFunction(buf, client); err != nil { + t.Errorf("logFunction failed: %v", err) + } + }) + + t.Run("arrayConcatFunction", func(t *testing.T) { + buf.Reset() + if err := arrayConcatFunction(buf, client); err != nil { + t.Errorf("arrayConcatFunction failed: %v", err) + } + }) + + t.Run("arrayContainsFunction", func(t *testing.T) { + buf.Reset() + if err := arrayContainsFunction(buf, client); err != nil { + t.Errorf("arrayContainsFunction failed: %v", err) + } + }) + + t.Run("arrayContainsAllFunction", func(t *testing.T) { + buf.Reset() + if err := arrayContainsAllFunction(buf, client); err != nil { + t.Errorf("arrayContainsAllFunction failed: %v", err) + } + }) + + t.Run("arrayContainsAnyFunction", func(t *testing.T) { + buf.Reset() + if err := arrayContainsAnyFunction(buf, client); err != nil { + t.Errorf("arrayContainsAnyFunction failed: %v", err) + } + }) + + t.Run("arrayLengthFunction", func(t *testing.T) { + buf.Reset() + if err := arrayLengthFunction(buf, client); err != nil { + t.Errorf("arrayLengthFunction failed: %v", err) + } + }) + + t.Run("arrayReverseFunction", func(t *testing.T) { + buf.Reset() + if err := arrayReverseFunction(buf, client); err != nil { + t.Errorf("arrayReverseFunction failed: %v", err) + } + }) + + t.Run("equalFunction", func(t *testing.T) { + buf.Reset() + if err := equalFunction(buf, client); err != nil { + t.Errorf("equalFunction failed: %v", err) + } + }) + + t.Run("greaterThanFunction", func(t *testing.T) { + buf.Reset() + if err := greaterThanFunction(buf, client); err != nil { + t.Errorf("greaterThanFunction failed: %v", err) + } + }) + + t.Run("greaterThanOrEqualToFunction", func(t *testing.T) { + buf.Reset() + if err := greaterThanOrEqualToFunction(buf, client); err != nil { + t.Errorf("greaterThanOrEqualToFunction failed: %v", err) + } + }) + + t.Run("lessThanFunction", func(t *testing.T) { + buf.Reset() + if err := lessThanFunction(buf, client); err != nil { + t.Errorf("lessThanFunction failed: %v", err) + } + }) + + t.Run("lessThanOrEqualToFunction", func(t *testing.T) { + buf.Reset() + if err := lessThanOrEqualToFunction(buf, client); err != nil { + t.Errorf("lessThanOrEqualToFunction failed: %v", err) + } + }) + + t.Run("notEqualFunction", func(t *testing.T) { + buf.Reset() + if err := notEqualFunction(buf, client); err != nil { + t.Errorf("notEqualFunction failed: %v", err) + } + }) + + t.Run("existsFunction", func(t *testing.T) { + buf.Reset() + if err := existsFunction(buf, client); err != nil { + t.Errorf("existsFunction failed: %v", err) + } + }) + + t.Run("andFunction", func(t *testing.T) { + buf.Reset() + if err := andFunction(buf, client); err != nil { + t.Errorf("andFunction failed: %v", err) + } + }) + + t.Run("orFunction", func(t *testing.T) { + buf.Reset() + if err := orFunction(buf, client); err != nil { + t.Errorf("orFunction failed: %v", err) + } + }) + + t.Run("xorFunction", func(t *testing.T) { + buf.Reset() + if err := xorFunction(buf, client); err != nil { + t.Errorf("xorFunction failed: %v", err) + } + }) + + t.Run("notFunction", func(t *testing.T) { + buf.Reset() + if err := notFunction(buf, client); err != nil { + t.Errorf("notFunction failed: %v", err) + } + }) + + t.Run("condFunction", func(t *testing.T) { + buf.Reset() + if err := condFunction(buf, client); err != nil { + t.Errorf("condFunction failed: %v", err) + } + }) + + t.Run("equalAnyFunction", func(t *testing.T) { + buf.Reset() + if err := equalAnyFunction(buf, client); err != nil { + t.Errorf("equalAnyFunction failed: %v", err) + } + }) + + t.Run("notEqualAnyFunction", func(t *testing.T) { + buf.Reset() + if err := notEqualAnyFunction(buf, client); err != nil { + t.Errorf("notEqualAnyFunction failed: %v", err) + } + }) + + t.Run("maxLogicalFunction", func(t *testing.T) { + buf.Reset() + if err := maxLogicalFunction(buf, client); err != nil { + t.Errorf("maxLogicalFunction failed: %v", err) + } + }) + + t.Run("minLogicalFunction", func(t *testing.T) { + buf.Reset() + if err := minLogicalFunction(buf, client); err != nil { + t.Errorf("minLogicalFunction failed: %v", err) + } + }) + + t.Run("mapGetFunction", func(t *testing.T) { + buf.Reset() + if err := mapGetFunction(buf, client); err != nil { + t.Errorf("mapGetFunction failed: %v", err) + } + }) + + t.Run("mapSetFunction", func(t *testing.T) { + buf.Reset() + if err := mapSetFunction(buf, client); err != nil { + t.Errorf("mapSetFunction failed: %v", err) + } + }) + + t.Run("mapKeysFunction", func(t *testing.T) { + buf.Reset() + if err := mapKeysFunction(buf, client); err != nil { + t.Errorf("mapKeysFunction failed: %v", err) + } + }) + + t.Run("mapValuesFunction", func(t *testing.T) { + buf.Reset() + if err := mapValuesFunction(buf, client); err != nil { + t.Errorf("mapValuesFunction failed: %v", err) + } + }) + + t.Run("mapEntriesFunction", func(t *testing.T) { + buf.Reset() + if err := mapEntriesFunction(buf, client); err != nil { + t.Errorf("mapEntriesFunction failed: %v", err) + } + }) + + t.Run("byteLengthFunction", func(t *testing.T) { + buf.Reset() + if err := byteLengthFunction(buf, client); err != nil { + t.Errorf("byteLengthFunction failed: %v", err) + } + }) + + t.Run("charLengthFunction", func(t *testing.T) { + buf.Reset() + if err := charLengthFunction(buf, client); err != nil { + t.Errorf("charLengthFunction failed: %v", err) + } + }) + + t.Run("startsWithFunction", func(t *testing.T) { + buf.Reset() + if err := startsWithFunction(buf, client); err != nil { + t.Errorf("startsWithFunction failed: %v", err) + } + }) + + t.Run("likeFunction", func(t *testing.T) { + buf.Reset() + if err := likeFunction(buf, client); err != nil { + t.Errorf("likeFunction failed: %v", err) + } + }) + + t.Run("regexContainsFunction", func(t *testing.T) { + buf.Reset() + if err := regexContainsFunction(buf, client); err != nil { + t.Errorf("regexContainsFunction failed: %v", err) + } + }) + + t.Run("regexFindFunction", func(t *testing.T) { + buf.Reset() + if err := regexFindFunction(buf, client); err != nil { + t.Errorf("regexFindFunction failed: %v", err) + } + }) + + t.Run("regexFindAllFunction", func(t *testing.T) { + buf.Reset() + if err := regexFindAllFunction(buf, client); err != nil { + t.Errorf("regexFindAllFunction failed: %v", err) + } + }) + + t.Run("regexMatchFunction", func(t *testing.T) { + buf.Reset() + if err := regexMatchFunction(buf, client); err != nil { + t.Errorf("regexMatchFunction failed: %v", err) + } + }) + + t.Run("strConcatFunction", func(t *testing.T) { + buf.Reset() + if err := strConcatFunction(buf, client); err != nil { + t.Errorf("strConcatFunction failed: %v", err) + } + }) + + t.Run("strContainsFunction", func(t *testing.T) { + buf.Reset() + if err := strContainsFunction(buf, client); err != nil { + t.Errorf("strContainsFunction failed: %v", err) + } + }) + + t.Run("toUpperFunction", func(t *testing.T) { + buf.Reset() + if err := toUpperFunction(buf, client); err != nil { + t.Errorf("toUpperFunction failed: %v", err) + } + }) + + t.Run("toLowerFunction", func(t *testing.T) { + buf.Reset() + if err := toLowerFunction(buf, client); err != nil { + t.Errorf("toLowerFunction failed: %v", err) + } + }) + + t.Run("substrFunction", func(t *testing.T) { + buf.Reset() + if err := substrFunction(buf, client); err != nil { + t.Errorf("substrFunction failed: %v", err) + } + }) + + t.Run("strReverseFunction", func(t *testing.T) { + buf.Reset() + if err := strReverseFunction(buf, client); err != nil { + t.Errorf("strReverseFunction failed: %v", err) + } + }) + + t.Run("strTrimFunction", func(t *testing.T) { + buf.Reset() + if err := strTrimFunction(buf, client); err != nil { + t.Errorf("strTrimFunction failed: %v", err) + } + }) + + t.Run("strLTrimFunction", func(t *testing.T) { + buf.Reset() + if err := strLTrimFunction(buf, client); err != nil { + t.Errorf("strLTrimFunction failed: %v", err) + } + }) + + t.Run("strRTrimFunction", func(t *testing.T) { + buf.Reset() + if err := strRTrimFunction(buf, client); err != nil { + t.Errorf("strRTrimFunction failed: %v", err) + } + }) + + t.Run("strRepeatFunction", func(t *testing.T) { + buf.Reset() + if err := strRepeatFunction(buf, client); err != nil { + t.Errorf("strRepeatFunction failed: %v", err) + } + }) + + t.Run("strReplaceAllFunction", func(t *testing.T) { + buf.Reset() + if err := strReplaceAllFunction(buf, client); err != nil { + t.Errorf("strReplaceAllFunction failed: %v", err) + } + }) + + t.Run("strReplaceOneFunction", func(t *testing.T) { + buf.Reset() + if err := strReplaceOneFunction(buf, client); err != nil { + t.Errorf("strReplaceOneFunction failed: %v", err) + } + }) + + t.Run("strIndexOfFunction", func(t *testing.T) { + buf.Reset() + if err := strIndexOfFunction(buf, client); err != nil { + t.Errorf("strIndexOfFunction failed: %v", err) + } + }) + + t.Run("unixMicrosToTimestampFunction", func(t *testing.T) { + buf.Reset() + if err := unixMicrosToTimestampFunction(buf, client); err != nil { + t.Errorf("unixMicrosToTimestampFunction failed: %v", err) + } + }) + + t.Run("unixMillisToTimestampFunction", func(t *testing.T) { + buf.Reset() + if err := unixMillisToTimestampFunction(buf, client); err != nil { + t.Errorf("unixMillisToTimestampFunction failed: %v", err) + } + }) + + t.Run("unixSecondsToTimestampFunction", func(t *testing.T) { + buf.Reset() + if err := unixSecondsToTimestampFunction(buf, client); err != nil { + t.Errorf("unixSecondsToTimestampFunction failed: %v", err) + } + }) + + t.Run("timestampAddFunction", func(t *testing.T) { + buf.Reset() + if err := timestampAddFunction(buf, client); err != nil { + t.Errorf("timestampAddFunction failed: %v", err) + } + }) + + t.Run("timestampSubFunction", func(t *testing.T) { + buf.Reset() + if err := timestampSubFunction(buf, client); err != nil { + t.Errorf("timestampSubFunction failed: %v", err) + } + }) + + t.Run("timestampToUnixMicrosFunction", func(t *testing.T) { + buf.Reset() + if err := timestampToUnixMicrosFunction(buf, client); err != nil { + t.Errorf("timestampToUnixMicrosFunction failed: %v", err) + } + }) + + t.Run("timestampToUnixMillisFunction", func(t *testing.T) { + buf.Reset() + if err := timestampToUnixMillisFunction(buf, client); err != nil { + t.Errorf("timestampToUnixMillisFunction failed: %v", err) + } + }) + + t.Run("timestampToUnixSecondsFunction", func(t *testing.T) { + buf.Reset() + if err := timestampToUnixSecondsFunction(buf, client); err != nil { + t.Errorf("timestampToUnixSecondsFunction failed: %v", err) + } + }) + + t.Run("cosineDistanceFunction", func(t *testing.T) { + buf.Reset() + if err := cosineDistanceFunction(buf, client); err != nil { + t.Errorf("cosineDistanceFunction failed: %v", err) + } + }) + + t.Run("dotProductFunction", func(t *testing.T) { + buf.Reset() + if err := dotProductFunction(buf, client); err != nil { + t.Errorf("dotProductFunction failed: %v", err) + } + }) + + t.Run("euclideanDistanceFunction", func(t *testing.T) { + buf.Reset() + if err := euclideanDistanceFunction(buf, client); err != nil { + t.Errorf("euclideanDistanceFunction failed: %v", err) + } + }) + + t.Run("vectorLengthFunction", func(t *testing.T) { + buf.Reset() + if err := vectorLengthFunction(buf, client); err != nil { + t.Errorf("vectorLengthFunction failed: %v", err) + } + }) + + t.Run("stagesExpressionsExample", func(t *testing.T) { + buf.Reset() + if err := stagesExpressionsExample(buf, client); err != nil { + t.Errorf("stagesExpressionsExample failed: %v", err) + } + }) + + t.Run("createWhereData", func(t *testing.T) { + buf.Reset() + if err := createWhereData(buf, client); err != nil { + t.Errorf("createWhereData failed: %v", err) + } + }) + + t.Run("whereEqualityExample", func(t *testing.T) { + buf.Reset() + if err := whereEqualityExample(buf, client); err != nil { + t.Errorf("whereEqualityExample failed: %v", err) + } + }) + + t.Run("whereMultipleStagesExample", func(t *testing.T) { + buf.Reset() + if err := whereMultipleStagesExample(buf, client); err != nil { + t.Errorf("whereMultipleStagesExample failed: %v", err) + } + }) + + t.Run("whereComplexExample", func(t *testing.T) { + buf.Reset() + if err := whereComplexExample(buf, client); err != nil { + t.Errorf("whereComplexExample failed: %v", err) + } + }) + + t.Run("whereStageOrderExample", func(t *testing.T) { + buf.Reset() + if err := whereStageOrderExample(buf, client); err != nil { + t.Errorf("whereStageOrderExample failed: %v", err) + } + }) + + t.Run("unnestSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := unnestSyntaxExample(buf, client); err != nil { + t.Errorf("unnestSyntaxExample failed: %v", err) + } + }) + + t.Run("unnestAliasIndexDataExample", func(t *testing.T) { + buf.Reset() + if err := unnestAliasIndexDataExample(buf, client); err != nil { + t.Errorf("unnestAliasIndexDataExample failed: %v", err) + } + }) + + t.Run("unnestAliasIndexExample", func(t *testing.T) { + buf.Reset() + if err := unnestAliasIndexExample(buf, client); err != nil { + t.Errorf("unnestAliasIndexExample failed: %v", err) + } + }) + + t.Run("unnestNonArrayDataExample", func(t *testing.T) { + buf.Reset() + if err := unnestNonArrayDataExample(buf, client); err != nil { + t.Errorf("unnestNonArrayDataExample failed: %v", err) + } + }) + + t.Run("unnestNonArrayExample", func(t *testing.T) { + buf.Reset() + if err := unnestNonArrayExample(buf, client); err != nil { + t.Errorf("unnestNonArrayExample failed: %v", err) + } + }) + + t.Run("unnestEmptyArrayDataExample", func(t *testing.T) { + buf.Reset() + if err := unnestEmptyArrayDataExample(buf, client); err != nil { + t.Errorf("unnestEmptyArrayDataExample failed: %v", err) + } + }) + + t.Run("unnestEmptyArrayExample", func(t *testing.T) { + buf.Reset() + if err := unnestEmptyArrayExample(buf, client); err != nil { + t.Errorf("unnestEmptyArrayExample failed: %v", err) + } + }) + + t.Run("unnestPreserveEmptyArrayExample", func(t *testing.T) { + buf.Reset() + if err := unnestPreserveEmptyArrayExample(buf, client); err != nil { + t.Errorf("unnestPreserveEmptyArrayExample failed: %v", err) + } + }) + + t.Run("unnestNestedDataExample", func(t *testing.T) { + buf.Reset() + if err := unnestNestedDataExample(buf, client); err != nil { + t.Errorf("unnestNestedDataExample failed: %v", err) + } + }) + + t.Run("unnestNestedExample", func(t *testing.T) { + buf.Reset() + if err := unnestNestedExample(buf, client); err != nil { + t.Errorf("unnestNestedExample failed: %v", err) + } + }) + + t.Run("sampleSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := sampleSyntaxExample(buf, client); err != nil { + t.Errorf("sampleSyntaxExample failed: %v", err) + } + }) + + t.Run("sampleDocumentsDataExample", func(t *testing.T) { + buf.Reset() + if err := sampleDocumentsDataExample(buf, client); err != nil { + t.Errorf("sampleDocumentsDataExample failed: %v", err) + } + }) + + t.Run("sampleDocumentsExample", func(t *testing.T) { + buf.Reset() + if err := sampleDocumentsExample(buf, client); err != nil { + t.Errorf("sampleDocumentsExample failed: %v", err) + } + }) + + t.Run("sampleAllDocumentsExample", func(t *testing.T) { + buf.Reset() + if err := sampleAllDocumentsExample(buf, client); err != nil { + t.Errorf("sampleAllDocumentsExample failed: %v", err) + } + }) + + t.Run("samplePercentageDataExample", func(t *testing.T) { + buf.Reset() + if err := samplePercentageDataExample(buf, client); err != nil { + t.Errorf("samplePercentageDataExample failed: %v", err) + } + }) + + t.Run("samplePercentageExample", func(t *testing.T) { + buf.Reset() + if err := samplePercentageExample(buf, client); err != nil { + t.Errorf("samplePercentageExample failed: %v", err) + } + }) + + t.Run("sortSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := sortSyntaxExample(buf, client); err != nil { + t.Errorf("sortSyntaxExample failed: %v", err) + } + }) + + t.Run("sortSyntaxExample2", func(t *testing.T) { + buf.Reset() + if err := sortSyntaxExample2(buf, client); err != nil { + t.Errorf("sortSyntaxExample2 failed: %v", err) + } + }) + + t.Run("sortDocumentIDExample", func(t *testing.T) { + buf.Reset() + if err := sortDocumentIDExample(buf, client); err != nil { + t.Errorf("sortDocumentIDExample failed: %v", err) + } + }) + + t.Run("selectSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := selectSyntaxExample(buf, client); err != nil { + t.Errorf("selectSyntaxExample failed: %v", err) + } + }) + + t.Run("selectPositionDataExample", func(t *testing.T) { + buf.Reset() + if err := selectPositionDataExample(buf, client); err != nil { + t.Errorf("selectPositionDataExample failed: %v", err) + } + }) + + t.Run("selectPositionExample", func(t *testing.T) { + buf.Reset() + if err := selectPositionExample(buf, client); err != nil { + t.Errorf("selectPositionExample failed: %v", err) + } + }) + + t.Run("selectBadPositionExample", func(t *testing.T) { + buf.Reset() + if err := selectBadPositionExample(buf, client); err != nil { + t.Errorf("selectBadPositionExample failed: %v", err) + } + }) + + t.Run("selectNestedDataExample", func(t *testing.T) { + buf.Reset() + if err := selectNestedDataExample(buf, client); err != nil { + t.Errorf("selectNestedDataExample failed: %v", err) + } + }) + + t.Run("selectNestedExample", func(t *testing.T) { + buf.Reset() + if err := selectNestedExample(buf, client); err != nil { + t.Errorf("selectNestedExample failed: %v", err) + } + }) + + t.Run("removeFieldsSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := removeFieldsSyntaxExample(buf, client); err != nil { + t.Errorf("removeFieldsSyntaxExample failed: %v", err) + } + }) + + t.Run("removeFieldsNestedDataExample", func(t *testing.T) { + buf.Reset() + if err := removeFieldsNestedDataExample(buf, client); err != nil { + t.Errorf("removeFieldsNestedDataExample failed: %v", err) + } + }) + + t.Run("removeFieldsNestedExample", func(t *testing.T) { + buf.Reset() + if err := removeFieldsNestedExample(buf, client); err != nil { + t.Errorf("removeFieldsNestedExample failed: %v", err) + } + }) + + t.Run("limitSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := limitSyntaxExample(buf, client); err != nil { + t.Errorf("limitSyntaxExample failed: %v", err) + } + }) + + t.Run("findNearestSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := findNearestSyntaxExample(buf, client); err != nil { + t.Errorf("findNearestSyntaxExample failed: %v", err) + } + }) + + t.Run("findNearestLimitExample", func(t *testing.T) { + buf.Reset() + if err := findNearestLimitExample(buf, client); err != nil { + t.Errorf("findNearestLimitExample failed: %v", err) + } + }) + + t.Run("findNearestDistanceDataExample", func(t *testing.T) { + buf.Reset() + if err := findNearestDistanceDataExample(buf, client); err != nil { + t.Errorf("findNearestDistanceDataExample failed: %v", err) + } + }) + + t.Run("findNearestDistanceExample", func(t *testing.T) { + buf.Reset() + if err := findNearestDistanceExample(buf, client); err != nil { + t.Errorf("findNearestDistanceExample failed: %v", err) + } + }) + + t.Run("offsetSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := offsetSyntaxExample(buf, client); err != nil { + t.Errorf("offsetSyntaxExample failed: %v", err) + } + }) + + t.Run("addFieldsSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := addFieldsSyntaxExample(buf, client); err != nil { + t.Errorf("addFieldsSyntaxExample failed: %v", err) + } + }) + + t.Run("addFieldsOverlapExample", func(t *testing.T) { + buf.Reset() + if err := addFieldsOverlapExample(buf, client); err != nil { + t.Errorf("addFieldsOverlapExample failed: %v", err) + } + }) + + t.Run("addFieldsNestingExample", func(t *testing.T) { + buf.Reset() + if err := addFieldsNestingExample(buf, client); err != nil { + t.Errorf("addFieldsNestingExample failed: %v", err) + } + }) + + t.Run("collectionInputSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := collectionInputSyntaxExample(buf, client); err != nil { + t.Errorf("collectionInputSyntaxExample failed: %v", err) + } + }) + + t.Run("collectionInputExampleData", func(t *testing.T) { + buf.Reset() + if err := collectionInputExampleData(buf, client); err != nil { + t.Errorf("collectionInputExampleData failed: %v", err) + } + }) + + t.Run("collectionInputExample", func(t *testing.T) { + buf.Reset() + if err := collectionInputExample(buf, client); err != nil { + t.Errorf("collectionInputExample failed: %v", err) + } + }) + + t.Run("subcollectionInputExampleData", func(t *testing.T) { + buf.Reset() + if err := subcollectionInputExampleData(buf, client); err != nil { + t.Errorf("subcollectionInputExampleData failed: %v", err) + } + }) + + t.Run("subcollectionInputExample", func(t *testing.T) { + buf.Reset() + if err := subcollectionInputExample(buf, client); err != nil { + t.Errorf("subcollectionInputExample failed: %v", err) + } + }) + + t.Run("collectionGroupInputSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := collectionGroupInputSyntaxExample(buf, client); err != nil { + t.Errorf("collectionGroupInputSyntaxExample failed: %v", err) + } + }) + + t.Run("collectionGroupInputExampleData", func(t *testing.T) { + buf.Reset() + if err := collectionGroupInputExampleData(buf, client); err != nil { + t.Errorf("collectionGroupInputExampleData failed: %v", err) + } + }) + + t.Run("collectionGroupInputExample", func(t *testing.T) { + buf.Reset() + if err := collectionGroupInputExample(buf, client); err != nil { + t.Errorf("collectionGroupInputExample failed: %v", err) + } + }) + + t.Run("databaseInputSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := databaseInputSyntaxExample(buf, client); err != nil { + t.Errorf("databaseInputSyntaxExample failed: %v", err) + } + }) + + t.Run("databaseInputSyntaxExampleData", func(t *testing.T) { + buf.Reset() + if err := databaseInputSyntaxExampleData(buf, client); err != nil { + t.Errorf("databaseInputSyntaxExampleData failed: %v", err) + } + }) + + t.Run("databaseInputExample", func(t *testing.T) { + buf.Reset() + if err := databaseInputExample(buf, client); err != nil { + t.Errorf("databaseInputExample failed: %v", err) + } + }) + + t.Run("documentInputSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := documentInputSyntaxExample(buf, client); err != nil { + t.Errorf("documentInputSyntaxExample failed: %v", err) + } + }) + + t.Run("documentInputExampleData", func(t *testing.T) { + buf.Reset() + if err := documentInputExampleData(buf, client); err != nil { + t.Errorf("documentInputExampleData failed: %v", err) + } + }) + + t.Run("documentInputExample", func(t *testing.T) { + buf.Reset() + if err := documentInputExample(buf, client); err != nil { + t.Errorf("documentInputExample failed: %v", err) + } + }) + + t.Run("unionSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := unionSyntaxExample(buf, client); err != nil { + t.Errorf("unionSyntaxExample failed: %v", err) + } + }) + + t.Run("aggregateSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := aggregateSyntaxExample(buf, client); err != nil { + t.Errorf("aggregateSyntaxExample failed: %v", err) + } + }) + + t.Run("aggregateGroupSyntax", func(t *testing.T) { + buf.Reset() + if err := aggregateGroupSyntax(buf, client); err != nil { + t.Errorf("aggregateGroupSyntax failed: %v", err) + } + }) + + t.Run("aggregateExampleData", func(t *testing.T) { + buf.Reset() + if err := aggregateExampleData(buf, client); err != nil { + t.Errorf("aggregateExampleData failed: %v", err) + } + }) + + t.Run("aggregateWithoutGroupExample", func(t *testing.T) { + buf.Reset() + if err := aggregateWithoutGroupExample(buf, client); err != nil { + t.Errorf("aggregateWithoutGroupExample failed: %v", err) + } + }) + + t.Run("aggregateGroupExample", func(t *testing.T) { + buf.Reset() + if err := aggregateGroupExample(buf, client); err != nil { + t.Errorf("aggregateGroupExample failed: %v", err) + } + }) + + t.Run("aggregateGroupComplexExample", func(t *testing.T) { + buf.Reset() + if err := aggregateGroupComplexExample(buf, client); err != nil { + t.Errorf("aggregateGroupComplexExample failed: %v", err) + } + }) + + t.Run("distinctSyntaxExample", func(t *testing.T) { + buf.Reset() + if err := distinctSyntaxExample(buf, client); err != nil { + t.Errorf("distinctSyntaxExample failed: %v", err) + } + }) + + t.Run("distinctExampleData", func(t *testing.T) { + buf.Reset() + if err := distinctExampleData(buf, client); err != nil { + t.Errorf("distinctExampleData failed: %v", err) + } + }) + + t.Run("distinctExample", func(t *testing.T) { + buf.Reset() + if err := distinctExample(buf, client); err != nil { + t.Errorf("distinctExample failed: %v", err) + } + }) + + t.Run("distinctExpressionsExample", func(t *testing.T) { + buf.Reset() + if err := distinctExpressionsExample(buf, client); err != nil { + t.Errorf("distinctExpressionsExample failed: %v", err) + } + }) + + t.Run("endsWithFunction", func(t *testing.T) { + buf.Reset() + if err := endsWithFunction(buf, client); err != nil { + t.Errorf("endsWithFunction failed: %v", err) + } + }) + + t.Run("whereHavingExample", func(t *testing.T) { + buf.Reset() + if err := whereHavingExample(buf, client); err != nil { + t.Errorf("whereHavingExample failed: %v", err) + } + }) + + t.Run("searchBasic", func(t *testing.T) { + t.Skip("Requires a pre-created search index") + buf.Reset() + if err := searchBasic(buf, client); err != nil { + t.Errorf("searchBasic failed: %v", err) + } + }) + + t.Run("searchExact", func(t *testing.T) { + t.Skip("Requires a pre-created search index") + buf.Reset() + if err := searchExact(buf, client); err != nil { + t.Errorf("searchExact failed: %v", err) + } + }) + + t.Run("searchTwoTerms", func(t *testing.T) { + t.Skip("Requires a pre-created search index") + buf.Reset() + if err := searchTwoTerms(buf, client); err != nil { + t.Errorf("searchTwoTerms failed: %v", err) + } + }) + + t.Run("searchExcludeTerm", func(t *testing.T) { + t.Skip("Requires a pre-created search index") + buf.Reset() + if err := searchExcludeTerm(buf, client); err != nil { + t.Errorf("searchExcludeTerm failed: %v", err) + } + }) + + t.Run("searchSpecialFields", func(t *testing.T) { + t.Skip("Requires a pre-created search index") + buf.Reset() + if err := searchSpecialFields(buf, client); err != nil { + t.Errorf("searchSpecialFields failed: %v", err) + } + }) + + t.Run("defineExample", func(t *testing.T) { + buf.Reset() + if err := defineExample(buf, client); err != nil { + t.Errorf("defineExample failed: %v", err) + } + }) + + t.Run("toArrayExpression", func(t *testing.T) { + buf.Reset() + if err := toArrayExpression(buf, client); err != nil { + t.Errorf("toArrayExpression failed: %v", err) + } + }) + + t.Run("toScalarExpression", func(t *testing.T) { + buf.Reset() + if err := toScalarExpression(buf, client); err != nil { + t.Errorf("toScalarExpression failed: %v", err) + } + }) + + t.Run("forceIndexExamples", func(t *testing.T) { + t.Skip("Requires a pre-created specific index") + buf.Reset() + if err := forceIndexExamples(buf, client); err != nil { + t.Errorf("forceIndexExamples failed: %v", err) + } + }) + + t.Run("pipelineUpdate", func(t *testing.T) { + buf.Reset() + if err := pipelineUpdate(buf, client); err != nil { + t.Errorf("pipelineUpdate failed: %v", err) + } + }) + + t.Run("pipelineDelete", func(t *testing.T) { + buf.Reset() + if err := pipelineDelete(buf, client); err != nil { + t.Errorf("pipelineDelete failed: %v", err) + } + }) + +} diff --git a/firestore/pipeline_snippets_vector.go b/firestore/pipeline_snippets_vector.go new file mode 100644 index 0000000000..952fb9fcfd --- /dev/null +++ b/firestore/pipeline_snippets_vector.go @@ -0,0 +1,102 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package firestore + +import ( + "context" + "fmt" + "io" + + "cloud.google.com/go/firestore" +) + +func cosineDistanceFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_cosine_distance] + sampleVector := []float64{0.0, 1.0, 2.0, 3.0, 4.0, 5.0} + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.CosineDistance(firestore.FieldOf("embedding"), sampleVector).As("cosineDistance"), + )). + Execute(ctx) + // [END firestore_cosine_distance] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func dotProductFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_dot_product] + sampleVector := []float64{0.0, 1.0, 2.0, 3.0, 4.0, 5.0} + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.DotProduct(firestore.FieldOf("embedding"), sampleVector).As("dotProduct"), + )). + Execute(ctx) + // [END firestore_dot_product] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func euclideanDistanceFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_euclidean_distance] + sampleVector := []float64{0.0, 1.0, 2.0, 3.0, 4.0, 5.0} + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.EuclideanDistance(firestore.FieldOf("embedding"), sampleVector).As("euclideanDistance"), + )). + Execute(ctx) + // [END firestore_euclidean_distance] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} + +func vectorLengthFunction(w io.Writer, client *firestore.Client) error { + ctx := context.Background() + // [START firestore_vector_length] + snapshot := client.Pipeline(). + Collection("books"). + Select(firestore.Fields( + firestore.VectorLength(firestore.FieldOf("embedding")).As("vectorLength"), + )). + Execute(ctx) + // [END firestore_vector_length] + results, err := snapshot.Results().GetAll() + if err != nil { + fmt.Fprintf(w, "snapshot.Results().GetAll failed: %v", err) + return err + } + fmt.Fprintln(w, results) + return nil +} diff --git a/testing/kokoro/system_tests.sh b/testing/kokoro/system_tests.sh index 58f9498541..a9aaabeeac 100755 --- a/testing/kokoro/system_tests.sh +++ b/testing/kokoro/system_tests.sh @@ -110,6 +110,7 @@ export GOLANG_SAMPLES_BIGTABLE_PROJECT=golang-samples-tests export GOLANG_SAMPLES_BIGTABLE_INSTANCE=testing-instance export GOLANG_SAMPLES_FIRESTORE_PROJECT=golang-samples-fire-0 +export GOLANG_SAMPLES_FIRESTORE_ENTERPRISE_DATABASE=db-enterprise-01 # This flag is added to avoid protobuf conflicts while running tests for profiler. # TODO: Remove this after https://github.com/googleapis/google-cloud-go/issues/9207 is resolved. export GOLANG_PROTOBUF_REGISTRATION_CONFLICT=warn