-
Notifications
You must be signed in to change notification settings - Fork 667
Expand file tree
/
Copy pathpipelines.ts
More file actions
2060 lines (1935 loc) · 68.2 KB
/
pipelines.ts
File metadata and controls
2060 lines (1935 loc) · 68.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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
//
// http://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.
import * as firestore from '@google-cloud/firestore';
import * as deepEqual from 'fast-deep-equal';
import {google} from '../../protos/firestore_v1_proto_api';
import Firestore, {
CollectionReference,
FieldPath,
Query,
Timestamp,
} from '../index';
import {validateFieldPath} from '../path';
import {
ExecutionUtil,
aliasedAggregateToMap,
fieldOrExpression,
isAliasedAggregate,
isBooleanExpr,
isCollectionReference,
isExpr,
isField,
isNumber,
isOrdering,
isPipeline,
isSelectable,
isString,
selectablesToMap,
toField,
vectorToExpr,
} from './pipeline-util';
import {DocumentReference} from '../reference/document-reference';
import {PipelineResponse} from '../reference/types';
import {Serializer} from '../serializer';
import {ApiMapValue} from '../types';
import * as protos from '../../protos/firestore_v1_proto_api';
import api = protos.google.firestore.v1;
import IStage = google.firestore.v1.Pipeline.IStage;
import {isOptionalEqual, isPlainObject} from '../util';
import {
AggregateFunction,
AliasedAggregate,
Expression,
Field,
BooleanExpression,
Ordering,
constant,
_mapValue,
field,
} from './expression';
import {
AddFields,
Aggregate,
CollectionSource,
CollectionGroupSource,
DatabaseSource,
DocumentsSource,
Where,
FindNearest,
RawStage,
Limit,
Offset,
Select,
Sort,
Stage,
Distinct,
RemoveFields,
ReplaceWith,
Sample,
Union,
Unnest,
InternalWhereStageOptions,
InternalOffsetStageOptions,
InternalLimitStageOptions,
InternalDistinctStageOptions,
InternalAggregateStageOptions,
InternalFindNearestStageOptions,
InternalReplaceWithStageOptions,
InternalSampleStageOptions,
InternalUnionStageOptions,
InternalUnnestStageOptions,
InternalSortStageOptions,
InternalDocumentsStageOptions,
InternalCollectionGroupStageOptions,
InternalCollectionStageOptions,
} from './stage';
import {StructuredPipeline} from './structured-pipeline';
import Selectable = FirebaseFirestore.Pipelines.Selectable;
import {
load as loadProtos,
Root as ProtoRoot,
Type as MessageType,
ReflectionObject,
} from 'protobufjs';
/**
* @beta
* Represents the source of a Firestore `Pipeline`.
*/
export class PipelineSource implements firestore.Pipelines.PipelineSource {
constructor(private db: Firestore) {}
/**
* @beta
* Returns all documents from the entire collection. The collection can be nested.
* @param collection - Name or reference to the collection that will be used as the Pipeline source.
*/
collection(collection: string | firestore.CollectionReference): Pipeline;
/**
* @beta
* Returns all documents from the entire collection. The collection can be nested.
* @param options - Options defining how this CollectionStage is evaluated.
*/
collection(options: firestore.Pipelines.CollectionStageOptions): Pipeline;
collection(
collectionOrOptions:
| string
| firestore.CollectionReference
| firestore.Pipelines.CollectionStageOptions,
): Pipeline {
const options =
isString(collectionOrOptions) ||
isCollectionReference(collectionOrOptions)
? {}
: collectionOrOptions;
const collection =
isString(collectionOrOptions) ||
isCollectionReference(collectionOrOptions)
? collectionOrOptions
: collectionOrOptions.collection;
// Validate that a user provided reference is for the same Firestore DB
if (isCollectionReference(collection)) {
this._validateReference(collection);
}
const normalizedCollection = isString(collection)
? this.db.collection(collection)
: (collection as CollectionReference);
const internalOptions: InternalCollectionStageOptions = {
...options,
collection: normalizedCollection,
};
return new Pipeline(this.db, [new CollectionSource(internalOptions)]);
}
/**
* @beta
* Returns all documents from a collection ID regardless of the parent.
* @param collectionId - ID of the collection group to use as the Pipeline source.
*/
collectionGroup(collectionId: string): Pipeline;
/**
* @beta
* Returns all documents from a collection ID regardless of the parent.
* @param options - Options defining how this CollectionGroupStage is evaluated.
*/
collectionGroup(
options: firestore.Pipelines.CollectionGroupStageOptions,
): Pipeline;
collectionGroup(
collectionIdOrOptions:
| string
| firestore.Pipelines.CollectionGroupStageOptions,
): Pipeline {
const options: InternalCollectionGroupStageOptions = isString(
collectionIdOrOptions,
)
? {collectionId: collectionIdOrOptions}
: {...collectionIdOrOptions};
return new Pipeline(this.db, [new CollectionGroupSource(options)]);
}
/**
* @beta
* Returns all documents from the entire database.
*/
database(): Pipeline;
/**
* @beta
* Returns all documents from the entire database.
* @param options - Options defining how a DatabaseStage is evaluated.
*/
database(options: firestore.Pipelines.DatabaseStageOptions): Pipeline;
database(options?: firestore.Pipelines.DatabaseStageOptions): Pipeline {
return new Pipeline(this.db, [new DatabaseSource(options ?? {})]);
}
/**
* @beta
* Set the pipeline's source to the documents specified by the given paths and DocumentReferences.
*
* @param docs An array of paths and DocumentReferences specifying the individual documents that will be the source of this pipeline.
* The converters for these DocumentReferences will be ignored and not have an effect on this pipeline.
*
* @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline.
*/
documents(docs: Array<string | DocumentReference>): Pipeline;
/**
* @beta
* Set the pipeline's source to the documents specified by the given paths and DocumentReferences.
*
* @param options - Options defining how this DocumentsStage is evaluated.
*
* @throws {@FirestoreError} Thrown if any of the provided DocumentReferences target a different project or database than the pipeline.
*/
documents(options: firestore.Pipelines.DocumentsStageOptions): Pipeline;
documents(
docsOrOptions:
| Array<string | DocumentReference>
| firestore.Pipelines.DocumentsStageOptions,
): Pipeline {
const options = Array.isArray(docsOrOptions) ? {} : docsOrOptions;
const docs = Array.isArray(docsOrOptions)
? docsOrOptions
: docsOrOptions.docs;
// Validate that all user provided references are for the same Firestore DB
docs
.filter(v => v instanceof DocumentReference)
.forEach(dr =>
this._validateReference(dr as firestore.DocumentReference),
);
const normalizedDocs: Array<DocumentReference> = docs.map(doc =>
isString(doc) ? this.db.doc(doc) : (doc as DocumentReference),
);
const internalOptions: InternalDocumentsStageOptions = {
...options,
docs: normalizedDocs,
};
return new Pipeline(this.db, [new DocumentsSource(internalOptions)]);
}
/**
* @beta
* Convert the given VectorQuery into an equivalent Pipeline.
*
* @param query A VectorQuery to be converted into a Pipeline.
*
* @throws {@FirestoreError} Thrown if the provided VectorQuer targets a different project or database than the Pipeline.
*/
createFrom(query: firestore.VectorQuery): Pipeline;
/**
* @beta
* Convert the given Query into an equivalent Pipeline.
*
* @param query A Query to be converted into a Pipeline.
*
* @throws {@FirestoreError} Thrown if the provided VectorQuer targets a different project or database than the Pipeline.
*/
createFrom(query: firestore.Query): Pipeline;
createFrom(query: firestore.Query | firestore.VectorQuery): Pipeline {
return (query as unknown as {_pipeline(): Pipeline})._pipeline();
}
_validateReference(
reference: firestore.CollectionReference | firestore.DocumentReference,
): reference is CollectionReference | DocumentReference {
if (
!(
reference instanceof CollectionReference ||
reference instanceof DocumentReference
)
) {
throw new Error(
'Invalid reference. The value may not be a CollectionReference or DocumentReference. Or, it may be an object from a different SDK build.',
);
}
const refDbId = reference.firestore.formattedName;
if (refDbId !== this.db.formattedName) {
throw new Error(
`Invalid ${
reference instanceof CollectionReference
? 'CollectionReference'
: 'DocumentReference'
}. ` +
`The database name ("${refDbId}") of this reference does not match ` +
`the database name ("${this.db.formattedName}") of the target database of this Pipeline.`,
);
}
return true;
}
}
/**
* @beta
* The Pipeline class provides a flexible and expressive framework for building complex data
* transformation and query pipelines for Firestore.
*
* A pipeline takes data sources, such as Firestore collections or collection groups, and applies
* a series of stages that are chained together. Each stage takes the output from the previous stage
* (or the data source) and produces an output for the next stage (or as the final output of the
* pipeline).
*
* Expressions can be used within each stage to filter and transform data through the stage.
*
* NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline.
* Instead, Firestore only guarantees that the result is the same as if the chained stages were
* executed in order.
*
* Usage Examples:
*
* @example
* ```typescript
* const db: Firestore; // Assumes a valid firestore instance.
*
* // Example 1: Select specific fields and rename 'rating' to 'bookRating'
* const results1 = await db.pipeline()
* .collection('books')
* .select('title', 'author', field('rating').as('bookRating'))
* .execute();
*
* // Example 2: Filter documents where 'genre' is 'Science Fiction' and 'published' is after 1950
* const results2 = await db.pipeline()
* .collection('books')
* .where(and(field('genre').equal('Science Fiction'), field('published').greaterThan(1950)))
* .execute();
*
* // Example 3: Calculate the average rating of books published after 1980
* const results3 = await db.pipeline()
* .collection('books')
* .where(field('published').greaterThan(1980))
* .aggregate(average(field('rating')).as('averageRating'))
* .execute();
* ```
*/
export class Pipeline implements firestore.Pipelines.Pipeline {
constructor(
private db: Firestore | undefined,
private stages: Stage[],
) {}
private _addStage(stage: Stage): Pipeline {
const copy = this.stages.map(s => s);
copy.push(stage);
return new Pipeline(this.db, copy);
}
/**
* @beta
* Adds new fields to outputs from previous stages.
*
* This stage allows you to compute values on-the-fly based on existing data from previous
* stages or constants. You can use this to create new fields or overwrite existing ones (if there
* is name overlaps).
*
* The added fields are defined using `Selectable`s, which can be:
*
* - `Field`: References an existing document field.
* - `Expression`: Either a literal value (see `constant(value)`) or a computed value
* (see `Expression`) with an assigned alias using `Expression.as('alias')`.
*
*
* @example
* ```typescript
* firestore.pipeline().collection("books")
* .addFields(
* field("rating").as("bookRating"), // Rename 'rating' to 'bookRating'
* add(5, field("quantity")).as("totalCost") // Calculate 'totalCost'
* );
* ```
*
* @param field The first field to add to the documents, specified as a `Selectable`.
* @param additionalFields Optional additional fields to add to the documents, specified as `Selectable`s.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
addFields(
field: firestore.Pipelines.Selectable,
...additionalFields: firestore.Pipelines.Selectable[]
): Pipeline;
/**
* @beta
* Adds new fields to outputs from previous stages.
*
* This stage allows you to compute values on-the-fly based on existing data from previous
* stages or constants. You can use this to create new fields or overwrite existing ones (if there
* is name overlaps).
*
* The added fields are defined using `Selectable`s, which can be:
*
* - `Field`: References an existing document field.
* - `Expression`: Either a literal value (see `constant(value)`) or a computed value
* (see `Expression`) with an assigned alias using `Expression.as('alias')`}.
*
*
* @example
* ```typescript
* firestore.pipeline().collection("books")
* .addFields(
* field("rating").as("bookRating"), // Rename 'rating' to 'bookRating'
* add(5, field("quantity")).as("totalCost") // Calculate 'totalCost'
* );
* ```
*
* @param options - An object that specifies required and optional parameters for the stage.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
addFields(options: firestore.Pipelines.AddFieldsStageOptions): Pipeline;
addFields(
fieldOrOptions:
| firestore.Pipelines.Selectable
| firestore.Pipelines.AddFieldsStageOptions,
...additionalFields: firestore.Pipelines.Selectable[]
): Pipeline {
const options = isSelectable(fieldOrOptions) ? {} : fieldOrOptions;
const fields: firestore.Pipelines.Selectable[] = isSelectable(
fieldOrOptions,
)
? [fieldOrOptions, ...additionalFields]
: fieldOrOptions.fields;
const normalizedFields: Map<string, Expression> = selectablesToMap(fields);
const internalOptions = {
...options,
fields: normalizedFields,
};
return this._addStage(new AddFields(internalOptions));
}
/**
* @beta
* Remove fields from outputs of previous stages.
*
*
* @example
* ```typescript
* firestore.pipeline().collection('books')
* // removes field 'rating' and 'cost' from the previous stage outputs.
* .removeFields(
* field('rating'),
* 'cost'
* );
* ```
*
* @param fieldValue The first field to remove.
* @param additionalFields Optional additional fields to remove.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
removeFields(
fieldValue: firestore.Pipelines.Field | string,
...additionalFields: Array<firestore.Pipelines.Field | string>
): Pipeline;
/**
* @beta
* Remove fields from outputs of previous stages.
*
*
* @example
* ```typescript
* firestore.pipeline().collection('books')
* // removes field 'rating' and 'cost' from the previous stage outputs.
* .removeFields(
* field('rating'),
* 'cost'
* );
* ```
*
* @param options - An object that specifies required and optional parameters for the stage.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
removeFields(options: firestore.Pipelines.RemoveFieldsStageOptions): Pipeline;
removeFields(
fieldValueOrOptions:
| firestore.Pipelines.Field
| string
| firestore.Pipelines.RemoveFieldsStageOptions,
...additionalFields: Array<firestore.Pipelines.Field | string>
): Pipeline {
const options =
isField(fieldValueOrOptions) || isString(fieldValueOrOptions)
? {}
: fieldValueOrOptions;
const fields: Array<firestore.Pipelines.Field | string> =
isField(fieldValueOrOptions) || isString(fieldValueOrOptions)
? [fieldValueOrOptions, ...additionalFields]
: fieldValueOrOptions.fields;
const convertedFields: Array<Field> = fields.map(f =>
isString(f) ? field(f) : (f as Field),
);
const innerOptions = {
...options,
fields: convertedFields,
};
return this._addStage(new RemoveFields(innerOptions));
}
/**
* @beta
* Selects or creates a set of fields from the outputs of previous stages.
*
* <p>The selected fields are defined using `Selectable` expressions, which can be:
*
* <ul>
* <li>`string`: Name of an existing field</li>
* <li>`Field`: References an existing field.</li>
* <li>`AliasedExpression`: Represents the result of a function with an assigned alias name using
* {@link Expression#as}</li>
* </ul>
*
* <p>If no selections are provided, the output of this stage is empty. Use {@link
* Pipeline#addFields} instead if only additions are
* desired.
*
*
* @example
* ```typescript
* db.pipeline().collection("books")
* .select(
* "firstName",
* field("lastName"),
* field("address").toUppercase().as("upperAddress"),
* );
* ```
*
* @param selection The first field to include in the output documents, specified as
* `Selectable` expression or string value representing the field name.
* @param additionalSelections Optional additional fields to include in the output documents, specified as
* `Selectable` expressions or `string` values representing field names.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
select(
selection: firestore.Pipelines.Selectable | string,
...additionalSelections: Array<firestore.Pipelines.Selectable | string>
): Pipeline;
/**
* @beta
* Selects or creates a set of fields from the outputs of previous stages.
*
* <p>The selected fields are defined using `Selectable` expressions, which can be:
*
* <ul>
* <li>`string`: Name of an existing field</li>
* <li>`Field`: References an existing field.</li>
* <li>`AliasedExpression`: Represents the result of a function with an assigned alias name using
* {@link Expression#as}</li>
* </ul>
*
* <p>If no selections are provided, the output of this stage is empty. Use {@link
* Pipeline#addFields} instead if only additions are
* desired.
*
*
* @example
* ```typescript
* db.pipeline().collection("books")
* .select(
* "firstName",
* field("lastName"),
* field("address").toUppercase().as("upperAddress"),
* );
* ```
*
* @param options - An object that specifies required and optional parameters for the stage.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
select(options: firestore.Pipelines.SelectStageOptions): Pipeline;
select(
selectionOrOptions:
| firestore.Pipelines.Selectable
| string
| firestore.Pipelines.SelectStageOptions,
...additionalSelections: Array<firestore.Pipelines.Selectable | string>
): Pipeline {
const options =
isSelectable(selectionOrOptions) || isString(selectionOrOptions)
? {}
: selectionOrOptions;
const selections: Array<firestore.Pipelines.Selectable | string> =
isSelectable(selectionOrOptions) || isString(selectionOrOptions)
? [selectionOrOptions, ...additionalSelections]
: selectionOrOptions.selections;
const normalizedSelections: Map<string, Expression> =
selectablesToMap(selections);
const internalOptions = {
...options,
selections: normalizedSelections,
};
return this._addStage(new Select(internalOptions));
}
/**
* @beta
* Filters the documents from previous stages to only include those matching the specified `BooleanExpression`.
*
* <p>This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL.
* You can filter documents based on their field values, using implementations of `BooleanExpression`, typically
* including but not limited to:
*
* <ul>
* <li>field comparators: {@link Function#equal}, {@link Function#lessThan} (less than), {@link
* Function#greaterThan} (greater than), etc.</li>
* <li>logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.</li>
* <li>advanced functions: {@link Function#regexMatch}, {@link
* Function#arrayContains}, etc.</li>
* </ul>
*
*
* @example
* ```typescript
* firestore.pipeline().collection("books")
* .where(
* and(
* greaterThan(field("rating"), 4.0), // Filter for ratings greater than 4.0
* field("genre").equal("Science Fiction") // Equivalent to greaterThan("genre", "Science Fiction")
* )
* );
* ```
*
* @param condition The `BooleanExpression` to apply.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
where(condition: firestore.Pipelines.BooleanExpression): Pipeline;
/**
* @beta
* Filters the documents from previous stages to only include those matching the specified `BooleanExpression`.
*
* <p>This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL.
* You can filter documents based on their field values, using implementations of `BooleanExpression`, typically
* including but not limited to:
*
* <ul>
* <li>field comparators: {@link Function#equal}, {@link Function#lessThan} (less than), {@link
* Function#greaterThan} (greater than), etc.</li>
* <li>logical operators: {@link Function#and}, {@link Function#or}, {@link Function#not}, etc.</li>
* <li>advanced functions: {@link Function#regexMatch}, {@link
* Function#arrayContains}, etc.</li>
* </ul>
*
*
* @example
* ```typescript
* firestore.pipeline().collection("books")
* .where(
* and(
* greaterThan(field("rating"), 4.0), // Filter for ratings greater than 4.0
* field("genre").equal("Science Fiction") // Equivalent to greaterThan("genre", "Science Fiction")
* )
* );
* ```
*
* @param options - An object that specifies required and optional parameters for the stage.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
where(options: firestore.Pipelines.WhereStageOptions): Pipeline;
where(
conditionOrOptions:
| firestore.Pipelines.BooleanExpression
| firestore.Pipelines.WhereStageOptions,
): Pipeline {
const options = isBooleanExpr(conditionOrOptions) ? {} : conditionOrOptions;
const condition: firestore.Pipelines.BooleanExpression = isBooleanExpr(
conditionOrOptions,
)
? conditionOrOptions
: conditionOrOptions.condition;
const convertedCondition: BooleanExpression =
condition as BooleanExpression;
const internalOptions: InternalWhereStageOptions = {
...options,
condition: convertedCondition,
};
return this._addStage(new Where(internalOptions));
}
/**
* @beta
* Skips the first `offset` number of documents from the results of previous stages.
*
* <p>This stage is useful for implementing pagination in your pipelines, allowing you to retrieve
* results in chunks. It is typically used in conjunction with to control the
* size of each page.
*
*
* @example
* ```typescript
* // Retrieve the second page of 20 results
* firestore.pipeline().collection('books')
* .sort(field('published').descending())
* .offset(20) // Skip the first 20 results
* .limit(20); // Take the next 20 results
* ```
*
* @param offset The number of documents to skip.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
offset(offset: number): Pipeline;
/**
* @beta
* Skips the first `offset` number of documents from the results of previous stages.
*
* <p>This stage is useful for implementing pagination in your pipelines, allowing you to retrieve
* results in chunks. It is typically used in conjunction with `limit` to control the
* size of each page.
*
*
* @example
* ```typescript
* // Retrieve the second page of 20 results
* firestore.pipeline().collection('books')
* .sort(field('published').descending())
* .offset(20) // Skip the first 20 results
* .limit(20); // Take the next 20 results
* ```
*
* @param options - An object that specifies required and optional parameters for the stage.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
offset(options: firestore.Pipelines.OffsetStageOptions): Pipeline;
offset(
offsetOrOptions: number | firestore.Pipelines.OffsetStageOptions,
): Pipeline {
const options = isNumber(offsetOrOptions) ? {} : offsetOrOptions;
const offset: number = isNumber(offsetOrOptions)
? offsetOrOptions
: offsetOrOptions.offset;
const internalOptions: InternalOffsetStageOptions = {
...options,
offset,
};
return this._addStage(new Offset(internalOptions));
}
/**
* @beta
* Limits the maximum number of documents returned by previous stages to `limit`.
*
* <p>This stage is particularly useful when you want to retrieve a controlled subset of data from
* a potentially large result set. It's often used for:
*
* <ul>
* <li>**Pagination:** In combination with `offset` to retrieve specific pages of
* results.</li>
* <li>**Limiting Data Retrieval:** To prevent excessive data transfer and improve performance,
* especially when dealing with large collections.</li>
* </ul>
*
*
* @example
* ```typescript
* // Limit the results to the top 10 highest-rated books
* firestore.pipeline().collection('books')
* .sort(field('rating').descending())
* .limit(10);
* ```
*
* @param limit The maximum number of documents to return.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
limit(limit: number): Pipeline;
/**
* @beta
* Limits the maximum number of documents returned by previous stages to `limit`.
*
* <p>This stage is particularly useful when you want to retrieve a controlled subset of data from
* a potentially large result set. It's often used for:
*
* <ul>
* <li>**Pagination:** In combination with `offset` to retrieve specific pages of
* results.</li>
* <li>**Limiting Data Retrieval:** To prevent excessive data transfer and improve performance,
* especially when dealing with large collections.</li>
* </ul>
*
*
* @example
* ```typescript
* // Limit the results to the top 10 highest-rated books
* firestore.pipeline().collection('books')
* .sort(field('rating').descending())
* .limit(10);
* ```
*
* @param options - An object that specifies required and optional parameters for the stage.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
limit(options: firestore.Pipelines.LimitStageOptions): Pipeline;
limit(
limitOrOptions: number | firestore.Pipelines.LimitStageOptions,
): Pipeline {
const options = isNumber(limitOrOptions) ? {} : limitOrOptions;
const limit: number = isNumber(limitOrOptions)
? limitOrOptions
: limitOrOptions.limit;
const internalOptions: InternalLimitStageOptions = {
...options,
limit,
};
return this._addStage(new Limit(internalOptions));
}
/**
* @beta
* Returns a set of distinct values from the inputs to this stage.
*
* This stage runs through the results from previous stages to include only results with
* unique combinations of `Expression` values.
*
* The parameters to this stage are defined using `Selectable` expressions or strings:
*
* - `string`: Name of an existing field
* - `Field`: References an existing document field.
* - `AliasedExpression`: Represents the result of a function with an assigned alias name
* using {@link Expression#as}.
*
*
* @example
* ```typescript
* // Get a list of unique author names in uppercase and genre combinations.
* firestore.pipeline().collection("books")
* .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt")
* .select("authorName");
* ```
*
* @param group The `Selectable` expression or field name to consider when determining
* distinct value combinations.
* @param additionalGroups Optional additional `Selectable` expressions to consider when determining distinct
* value combinations or strings representing field names.
* @returns A new `Pipeline` object with this stage appended to the stage list.
*/
distinct(
group: string | firestore.Pipelines.Selectable,
...additionalGroups: Array<string | firestore.Pipelines.Selectable>
): Pipeline;
/**
* @beta
* Returns a set of distinct values from the inputs to this stage.
*
* This stage runs through the results from previous stages to include only results with
* unique combinations of `Expression` values.
*
* The parameters to this stage are defined using `Selectable` expressions or strings:
*
* - `string`: Name of an existing field
* - `Field`: References an existing document field.
* - `AliasedExpression`: Represents the result of a function with an assigned alias name
* using {@link Expression#as}.
*
*
* @example
* ```typescript
* // Get a list of unique author names in uppercase and genre combinations.
* firestore.pipeline().collection("books")
* .distinct(toUppercase(field("author")).as("authorName"), field("genre"), "publishedAt")
* .select("authorName");
* ```
*
* @param options - An object that specifies required and optional parameters for the stage.
* @returns A new `Pipeline` object with this stage appended to the stage list.
*/
distinct(options: firestore.Pipelines.DistinctStageOptions): Pipeline;
distinct(
groupOrOptions:
| string
| firestore.Pipelines.Selectable
| firestore.Pipelines.DistinctStageOptions,
...additionalGroups: Array<string | firestore.Pipelines.Selectable>
): Pipeline {
const options =
isString(groupOrOptions) || isSelectable(groupOrOptions)
? {}
: groupOrOptions;
const groups: Array<string | Selectable> =
isString(groupOrOptions) || isSelectable(groupOrOptions)
? [groupOrOptions, ...additionalGroups]
: groupOrOptions.groups;
const convertedGroups: Map<string, Expression> = selectablesToMap(groups);
const internalOptions: InternalDistinctStageOptions = {
...options,
groups: convertedGroups,
};
return this._addStage(new Distinct(internalOptions));
}
/**
* @beta
* Performs aggregation operations on the documents from previous stages.
*
* <p>This stage allows you to calculate aggregate values over a set of documents. You define the
* aggregations to perform using `AliasedAggregate` expressions which are typically results of
* calling {@link Expression#as} on `AggregateFunction` instances.
*
*
* @example
* ```typescript
* // Calculate the average rating and the total number of books
* firestore.pipeline().collection("books")
* .aggregate(
* field("rating").average().as("averageRating"),
* countAll().as("totalBooks")
* );
* ```
*
* @param accumulator The first `AliasedAggregate`, wrapping an `AggregateFunction`
* and providing a name for the accumulated results.
* @param additionalAccumulators Optional additional `AliasedAggregate`, each wrapping an `AggregateFunction`
* and providing a name for the accumulated results.
* @returns A new Pipeline object with this stage appended to the stage list.
*/
aggregate(
accumulator: firestore.Pipelines.AliasedAggregate,
...additionalAccumulators: firestore.Pipelines.AliasedAggregate[]
): Pipeline;
/**
* @beta
* Performs optionally grouped aggregation operations on the documents from previous stages.
*
* <p>This stage allows you to calculate aggregate values over a set of documents, optionally
* grouped by one or more fields or functions. You can specify:
*
* <ul>
* <li>**Grouping Fields or Functions:** One or more fields or functions to group the documents
* by. For each distinct combination of values in these fields, a separate group is created.
* If no grouping fields are provided, a single group containing all documents is used. Not
* specifying groups is the same as putting the entire inputs into one group.</li>
* <li>**Accumulators:** One or more accumulation operations to perform within each group. These
* are defined using `AliasedAggregate` expressions, which are typically created by
* calling {@link Expression#as} on `AggregateFunction` instances. Each aggregation
* calculates a value (e.g., sum, average, count) based on the documents within its group.</li>
* </ul>
*
*
* @example
* ```typescript
* // Calculate the average rating for each genre.
* firestore.pipeline().collection("books")
* .aggregate({
* accumulators: [average(field("rating")).as("avg_rating")]
* groups: ["genre"]
* });
* ```
*
* @param options - An object that specifies required and optional parameters for the stage.
* @returns A new `Pipeline` object with this stage appended to the stage
* list.
*/
aggregate(options: firestore.Pipelines.AggregateStageOptions): Pipeline;
aggregate(
targetOrOptions:
| firestore.Pipelines.AliasedAggregate
| firestore.Pipelines.AggregateStageOptions,
...rest: firestore.Pipelines.AliasedAggregate[]
): Pipeline {
const options = isAliasedAggregate(targetOrOptions) ? {} : targetOrOptions;
const accumulators: Array<firestore.Pipelines.AliasedAggregate> =
isAliasedAggregate(targetOrOptions)
? [targetOrOptions, ...rest]
: targetOrOptions.accumulators;
const convertedAccumulators: Map<string, AggregateFunction> =
aliasedAggregateToMap(accumulators);
const groups: Array<firestore.Pipelines.Selectable | string> =
isAliasedAggregate(targetOrOptions) ? [] : (targetOrOptions.groups ?? []);
const convertedGroups: Map<string, Expression> = selectablesToMap(groups);
const internalOptions: InternalAggregateStageOptions = {
...options,
accumulators: convertedAccumulators,
groups: convertedGroups,
};
return this._addStage(new Aggregate(internalOptions));
}