Pipelines

Firestore pipeline queries overview: stages, sources, Firestore Enterprise/cloud-execution requirements, basic usage, and expression helpers like findNearest().

Prerequisites

  • @react-native-firebase/app installed and native config completed per Getting Started (Android google-services.json, iOS GoogleService-Info.plist, Expo config plugin, or React Native CLI setup). From v26, New Architecture is required for packages with a native bridge.
  • @react-native-firebase/firestore installed: npm install --save @react-native-firebase/firestore or yarn add @react-native-firebase/firestore, then rebuild native apps (cd ios && pod install on iOS).
  • A Firestore Enterprise database in your Firebase project. Pipeline execute() is rejected on Standard edition databases.
  • Network access to that Enterprise database. The local Firestore emulator is not a supported target for pipelines.

Firestore pipeline queries let you run multi-stage read operations (filter, project, aggregate, vector search, and more) against Cloud Firestore using a fluent, composable API. React Native Firebase exposes the same modular pipeline surface as the firebase-js-sdk so you can reuse patterns from web documentation and samples.

Pipeline support in React Native Firebase is marked @beta in TypeScript, so signatures can change when Firebase changes the pipeline API.

What are pipeline queries?

Traditional Firestore queries are collection-scoped and limited to a single query shape. Pipelines chain stages (for example where, select, aggregate, findNearest) on a source (collection, collection group, documents list, or an existing query). Each stage transforms the result of the previous stage.

Google's upstream resources:

For a full list of which firebase-js-sdk exports are available in React Native Firebase, see SDK compatibility.

Requirements

Firestore Enterprise edition

Pipeline execute() requires a Firestore Enterprise database. Standard edition databases reject pipeline execution. Create an Enterprise database in the Firebase console or with the Firebase CLI before testing pipelines in your project.

Cloud execution (not the local emulator)

The local Firestore emulator runs in Standard edition mode and does not faithfully execute pipeline queries. Develop and test pipelines against a live Enterprise database in your Firebase project.

Installation

Pipelines ship inside @react-native-firebase/firestore. Install the app and Firestore modules as described in Cloud Firestore usage:

bash
yarn add @react-native-firebase/app @react-native-firebase/firestore
cd ios && pod install

Expression helpers and types are imported from the pipelines entry point. You can also call getFirestore().pipeline() on any Firestore instance to start building a pipeline from a source stage:

js
import { getFirestore } from '@react-native-firebase/firestore';
import { field, constant, execute } from '@react-native-firebase/firestore/pipelines';

const db = getFirestore();
console.log(
  'Pipelines imports ready:',
  Boolean(field),
  Boolean(constant),
  Boolean(execute),
  Boolean(db),
);

Basic example

This example reads documents from a collection, keeps rows where score is at least 10, projects two fields, and sorts by score descending. Adjust the database id and collection path for your Enterprise database.

js
import { getFirestore } from '@react-native-firebase/firestore';
import { field, execute } from '@react-native-firebase/firestore/pipelines';

const db = getFirestore(); // use a named Enterprise database id if needed

const pipeline = db
  .pipeline()
  .collection('books')
  .where(field('score').greaterThanOrEqual(10))
  .select(field('title'), field('score'))
  .sort(field('score').descending());

const snapshot = await execute(pipeline);
snapshot.results.forEach(row => {
  console.log(row.data());
});

execute() returns a PipelineSnapshot with a results array of pipeline rows and an executionTime timestamp. Each row (PipelineResult) has data() for the projected fields, get(fieldPath) for a single field, and, for rows that map to a document, ref, id, createTime, and updateTime. Use pipelineResultEqual(left, right) to compare two rows.

js
import { getFirestore } from '@react-native-firebase/firestore';
import { execute, field, pipelineResultEqual } from '@react-native-firebase/firestore/pipelines';

const db = getFirestore();
const first = await execute(
  db.pipeline().collection('books').sort(field('score').descending()).limit(1),
);
const second = await execute(
  db.pipeline().collection('books').sort(field('score').descending()).limit(1),
);

const row = first.results[0];
console.log('Executed at:', first.executionTime.toDate().toISOString());
console.log('Title:', row?.get('title'), 'id:', row?.id, 'path:', row?.ref?.path);
console.log(
  'Same row:',
  row && second.results[0] ? pipelineResultEqual(row, second.results[0]) : false,
);

execute also accepts an options object, execute({ pipeline, indexMode: 'recommended', rawOptions }). indexMode and rawOptions are applied on Android; iOS rejects them because the native iOS pipeline SDK does not expose execute options.

Supported stages and sources

React Native Firebase supports these source types:

{/* prettier-ignore */}

SourceDescription
collectionDocuments in a collection path
collectionGroupDocuments across a collection id
databaseDatabase-scoped pipeline source
documentsExplicit document paths
queryPipeline created from an existing Firestore query (createFrom)

These stage types are available on the pipeline builder:

{/* prettier-ignore */}

StagePurpose
whereFilter rows
selectProject fields
addFields / removeFieldsAdd or drop computed fields
sortOrder results
limit / offsetPaginate
aggregateGroup and reduce
distinctDeduplicate
findNearestVector similarity search (requires vector index)
searchFull-text and geospatial search (requires search index; must be the first stage)
defineBind expressions to named variables for later stages
replaceWithReplace row shape
sampleRandom sample
unionCombine pipelines
unnestExpand array fields into rows
rawStageAdd a stage by name when no typed method exists

Vector search with findNearest

The findNearest stage runs vector similarity search over an indexed embedding field. Use the same lowercase distanceMeasure values as the firebase-js-sdk pipeline reference: 'euclidean', 'cosine', or 'dot_product'.

Create a vector index on your Enterprise database before running this query.

js
import { getFirestore } from '@react-native-firebase/firestore';
import { execute } from '@react-native-firebase/firestore/pipelines';

const db = getFirestore(); // Enterprise database with a vector index on `embedding`

const queryVector = [1.0, 0.0, 0.0];

const snapshot = await execute(
  db
    .pipeline()
    .collection('products')
    .findNearest({
      field: 'embedding',
      vectorValue: queryVector,
      distanceMeasure: 'euclidean',
      limit: 5,
    })
    .select('name'),
);

snapshot.results.forEach(row => {
  console.log(row.data().name);
});

Platform notes

{/* prettier-ignore */}

PlatformRuntimeNotes
AndroidNative Firebase Android SDKFull native pipeline execution
iOSNative Firebase iOS SDKFull native pipeline execution
macOSfirebase-js-sdk (web interop)Same API shape as web; requires network access to Firestore

Expression helpers (aggregates, strings, arrays, maps, timestamps, vectors) are supported on Android, iOS, and macOS. The parent() expression helper may be unavailable on web and on macOS when pipelines execute through the firebase-js-sdk interop path.

On macOS, pipeline execution goes through the web Firebase SDK bundled for React Native macOS targets. Behavior should match web pipeline queries for the same database and rules.

TypeScript

Pipeline types and expression helpers are exported from @react-native-firebase/firestore/pipelines. The firestore.pipeline() method is augmented on Firestore when you import the firestore module.

See SDK compatibility for the known differences between these types and the firebase-js-sdk pipelines declarations.

Expression helpers

These helpers have their own pages:

{/* prettier-ignore */}

HelperDescription
currentDocument()Reference the document being processed
ifNull()Fallback when a field is null or absent
switchOn()First matching condition / default result
timestampDiff()Difference between two timestamps in a unit
timestampExtract()Calendar part of a timestamp
subcollection()Nested pipeline over a subcollection

@react-native-firebase/firestore/pipelines exports the rest of the firebase-js-sdk helper set as functions. Their signatures match the firebase-js-sdk pipeline reference:

{/* prettier-ignore */}

FamilyHelpers
Field and value referencesfield, variable, constant, currentDocument, documentId, collectionId, parent, currentTimestamp, ascending, descending
Logic and comparisonand, or, not, xor, nor, equal, notEqual, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, equalAny, notEqualAny, exists, isAbsent, isError, isType, type
Conditionalconditional, ifNull, ifAbsent, ifError, switchOn, coalesce, logicalMaximum, logicalMinimum
Mathabs, add, subtract, multiply, divide, mod, pow, sqrt, exp, ln, log, log10, ceil, floor, round, trunc, rand
Aggregatescount, countAll, countDistinct, countIf, sum, average, minimum, maximum, first, last, arrayAgg, arrayAggDistinct
Stringsconcat, stringConcat, length, charLength, byteLength, toLower, toUpper, trim, ltrim, rtrim, substring, split, join, reverse, stringReverse, stringContains, stringIndexOf, stringRepeat, stringReplaceOne, stringReplaceAll, startsWith, endsWith, like, regexContains, regexFind, regexFindAll, regexMatch
Arraysarray, arrayConcat, arrayContains, arrayContainsAll, arrayContainsAny, arrayFilter, arrayFirst, arrayFirstN, arrayGet, arrayIndexOf, arrayIndexOfAll, arrayLast, arrayLastIndexOf, arrayLastN, arrayLength, arrayMaximum, arrayMaximumN, arrayMinimum, arrayMinimumN, arraySlice, arraySum, arrayTransform, arrayTransformWithIndex
Mapsmap, mapEntries, mapGet, mapKeys, mapMerge, mapRemove, mapSet, mapValues
TimestampstimestampAdd, timestampSubtract, timestampDiff, timestampExtract, timestampTruncate, timestampToUnixMicros, timestampToUnixMillis, timestampToUnixSeconds, unixMicrosToTimestamp, unixMillisToTimestamp, unixSecondsToTimestamp
Vectors and distancecosineDistance, dotProduct, euclideanDistance, vectorLength, geoDistance
SearchdocumentMatches, score
Executionexecute, subcollection, pipelineResultEqual

Several names (and, or, count, sum, average, documentId) are also exported by @react-native-firebase/firestore for classic queries with different behavior. Import the pipeline versions from @react-native-firebase/firestore/pipelines.

Pipeline builders also expose rawStage(...) for stages that have no typed method, plus toArrayExpression() and toScalarExpression() to embed a pipeline in another pipeline (see subcollection).

Next steps