Purpose
The Firestore CLI covers queries, embeddings, export/import/backup/transfer workflows, saved queries and scripts, schema analysis, local JavaScript execution, and guarded document writes through shared FirestructCore services.
Query Documents
firestore query --collection users --limit 50
firestore query --collection users --where "role == admin" --order-by "createdAt desc"
firestore query --project demo-firestruct --collection users --limit 0
firestore query --collection products --limit 12 --vector-field embedding --vector "[0.1,0.2,0.3]" --distance-measure cosine --distance-result-field vector_distance
Options:
--collectionis required and accepts a collection path.--limitdefaults to50;0means no explicit limit where supported by the service.--whereaccepts Firestruct simple-query syntax.--order-byaccepts comma-compatible parsed order clauses from the query service.--vector-fieldand--vectorswitch the query into Firestore RESTfindNearestrequest-shape mode.--distance-measureacceptseuclidean,cosine, ordot-product; it defaults tocosine.--distance-result-fieldand--distance-thresholdpass through to the vector query options.--projectoptionally overrides selected project.
Output contains:
- selected project JSON
- query metadata, including vector dimension count and distance options when supplied
documentslogs
Current automated vector coverage proves CLI argument parsing, invalid-vector rejection before network, findNearest REST body construction through the real FirestoreSimpleQueryService, returned distance-field decoding, and machine-readable query.vector.requiresFirebaseVectorVerification. It does not prove Firebase vector ranking behavior. That still needs a Firebase emulator or approved live Firebase target that supports vector search before completion can be claimed.
Embedding Provider Configuration
firestore embedding-config set --provider openai --model text-embedding-3-small --vector-field embedding --source-fields title,body --credentials-reference env:OPENAI_API_KEY
firestore embedding-config set --provider custom-http --model custom-embedder --vector-field vectors.search --source-fields title,body --endpoint https://embeddings.example.test/v1/embed --credentials-reference keychain://firestruct/embeddings
firestore embedding-config show
firestore embedding-config delete --confirm
firestore embedding-generate --collection articles --limit 100 --confirm
Options:
--provideracceptsopenai,vertex-ai, orcustom-http; it defaults toopenai.--model,--vector-field, and--source-fieldsare required forset.--source-fieldsaccepts comma-separated or newline-separated field paths.--batch-sizedefaults to100and must be between1and500.--credentials-referencemust be a local reference such asenv:OPENAI_API_KEY,keychain://..., orfile://...; raw provider API keys are rejected.--endpointis required forcustom-httpand must be an absolute HTTP or HTTPS URL.
Output includes selected project JSON, the project/database-scoped config key, normalized config metadata, providerAPICalled: false, batchGenerationStarted: false, and executionMode: local-embedding-provider-config.
embedding-config only manages local per-project configuration. It does not call OpenAI, Vertex AI, or custom embedding endpoints, and it does not generate or write embedding vectors.
embedding-generate currently supports selected Firestore emulator projects with saved custom-http provider config. It requires --confirm, rejects read-only or non-emulator projects, queries the requested collection, POSTs { "model": "...", "inputs": [...] } batches to the configured endpoint, writes returned numeric embedding arrays to the configured field through Firestore REST arrayValue, and returns selected project JSON, embedding-generation counters, firestoreValueEncoding, writesNativeFirestoreVectorValues: false, logs, and a task snapshot. Current automated proof starts a real Firebase emulator and a real loopback HTTP embedding provider, runs the CLI command, asserts the provider request body, verifies task success/counters, and reads Firestore back to prove numeric arrays were written. Native Firestore vector-value writes, OpenAI/Vertex execution, live Firestore embedding writes, and Firebase vector ranking behavior still require approved verification before completion can be claimed.
Export Query Results
firestore export --collection users --format json --output users.json
firestore export --collection users --format jsonl --output users.jsonl --include-path
firestore export --collection users --format csv --output users.csv --include-path
firestore export --collection users --format archive --output users.zip --include-path
firestore export --collection firestruct_verification/run1/users --format json --output live-users.json --include-path --access-token "$TOKEN"
Options:
--collectionis required and uses the same query path rules asfirestore query.--formatacceptsjson,jsonl,csv, orarchive; it defaults tojson.--outputis required and points to the destination file.--limit,--where, and--order-byuse the same parsing asfirestore query.--include-pathwrites__path__into exported rows.--no-document-idomits__id__; document IDs are included by default.--access-tokenor--authorizationis required for live projects.
Output contains selected project JSON, query metadata, export metadata, combined query/export logs, and a task snapshot with status, operation counters, duration, attempt count, and error.
Emulator-backed coverage validates JSON, JSONL, CSV, and archive output. Live request-shape and artifact coverage validates authorization, database routing, file output, and task counters; approved disposable live export and cleanup evidence remain open.
Backup Collection
firestore backup --collection users --output users-backup.zip
firestore backup --collection users --where "role == owner" --output owners-backup.zip
firestore backup --all-collections --output database-backup.zip
firestore backup is a first-class archive command for selected collections or the discovered database tree. It writes archive format, includes both __id__ and __path__, and runs through the task queue. Collection backups default to no explicit query limit unless --limit is supplied. Whole-database backups discover root collections, query each collection path, recursively list subcollections below every discovered document, and archive every discovered document path.
Options:
--collectionbacks up one collection path and uses the same query path rules asfirestore query.--all-collectionsbacks up every discovered root collection and nested subcollection document path.--outputis required and points to the destination.zipfile.--limit,--where, and--order-byuse the same parsing asfirestore queryfor collection backups only.
Whole-database backups reject --collection, --limit, --where, and --order-by when used with --all-collections so the command cannot silently create a partial database backup.
Emulator-backed coverage validates collection and whole-database archive creation, task output, manifests, root documents, and recursively discovered subcollections.
Import Documents
firestore import --format json --file users.json --collection users --id-mode field-value --id-field docID --confirm
firestore import --format json --file users.json --collection users --id-mode object-keys --confirm
firestore import --format jsonl --file users.jsonl --collection users --id-field docID --confirm
firestore import --format csv --file users.csv --collection users --id-column docID --type-hints '{"score":"int"}' --confirm
firestore import --format archive --file users.zip --allow-overwrite --confirm
firestore import --format archive --file users.zip --target-prefix archive_restore/run1 --confirm
firestore import --format json --file live-users.json --collection firestruct_verification/run1/users --access-token "$TOKEN" --confirm
Options:
--formatacceptsjson,jsonl,csv, orarchive; it defaults tojson.--fileis required.--collectionis required for JSON, JSONL, and CSV imports unless CSV uses--absolute-path-column.--confirmis required for every import.--access-tokenor--authorizationis required for live projects.--production-confirm "IMPORT <project-id>"is required for production projects.--allow-overwritepermits replacing existing emulator documents.- JSON supports
--id-mode auto-generated|object-keys|field-valueand--id-field. - JSONL supports
--id-field. - CSV supports
--id-column,--delimiter,--no-header,--absolute-path-column,--type-hints, and--column-mappings. - Archive accepts
--target-prefix <parent-document-path>to import archived document paths under a parent document, for examplearchive_restore/run1/users/cli-alice.
Output contains selected project JSON, import metadata, logs, and a task snapshot with status, operation counters, duration, attempt count, and error.
Imports fail for read-only projects before file parsing or network work. Emulator-backed coverage validates JSON, JSONL, CSV, overwrite, archive restore, and target-prefix behavior through read-back. Live imports have guarded JSON/CSV request-shape coverage, but approved disposable live read-back and cleanup remain open.
Transfer Collections
firestore transfer --project SourceProject --target TargetProject --collection users --confirm
firestore transfer --project SourceProject --target TargetProject --collections users,orders --include-subcollections --allow-overwrite --confirm
firestore transfer --project SourceProject --target TargetProject --collection users --clean-target --confirm
Options:
--targetis required and resolves a linked Firebase project by name, Firebase project ID, or UUID.--projectoptionally selects the source project; otherwise the current selected project is used.--collectiontransfers one collection path.--collectionsaccepts a comma-separated list.--confirmis required for every transfer.--include-subcollectionsrecursively copies document subcollections.--allow-overwritepermits replacing existing target documents.--clean-targetdeletes existing target documents in the target collection before copying.--source-access-tokenand--target-access-tokenprovide distinct OAuth tokens for live source reads and target writes; the corresponding--source-authorizationand--target-authorizationoptions accept complete authorization header values.- A transfer involving production also requires
--production-confirm "TRANSFER <source-project-id> TO <target-project-id>".
Output contains source/target project JSON, transfer metadata, logs, and a task snapshot with status, operation counters, duration, attempt count, and error.
Transfers fail when either project is read-only. Emulator-backed coverage validates confirmation, recursive copy, read-back, and target cleanup. Live request shape and credential propagation are covered locally; approved disposable live transfer and cleanup proof remain open.
JavaScript Query Scripts
firestore run-js --collection users --file scripts/query-users.js
firestore run-js --collection users --where "role == admin" --limit 100 --file scripts/query-users.js
firestore run-js --collection users --file scripts/mutate-users.js --write-through --confirm
firestore js --collection users --script 'async function run(ctx, admin) { return admin.firestore().query({ path: ctx.queryPath }); }'
firestore run-js first loads real Firestore documents through the selected emulator or live query path, then injects those documents into the local JavaScript runtime as admin.firestore() data. It returns structured documents, raw runtime JSON, logs, and a completed task snapshot.
Options:
--collectionis required and defines the Firestore data loaded before the script runs.--where,--order-by, and--limitmatchfirestore query.--file <path>reads a script from disk.--script <text>runs an inline script for small automation checks.--timeout <seconds>defaults to15.--write-throughapplies Firestore mutations emitted by the local runtime to the selected Firestore emulator.--confirmis required with--write-through.
Without --write-through, script mutations affect only the local runtime snapshot. With --write-through --confirm, emitted set, update, and delete mutations are applied to the selected emulator. Output identifies the emulator write-through mode and applied mutation count.
Write-through JavaScript execution currently supports emulator projects only. Live JavaScript writes require a separate approved live verification slice before they can be claimed.
Emulator-backed coverage validates real document loading, script results, console logs, task output, confirmation guards, and read-back after update/create/delete mutations.
Saved Queries And Scripts
firestore saved-query save --name "Owner Users" --collection users --where "role == owner" --limit 10
firestore saved-query list
firestore saved-query show --name "Owner Users"
firestore saved-query run --name "Owner Users"
firestore saved-query delete --name "Owner Users" --confirm
firestore saved-script save --name "Owner Report" --collection users --file scripts/query-users.js
firestore saved-script list
firestore saved-script show --name "Owner Report"
firestore saved-script run --name "Owner Report"
firestore saved-script run --name "Owner Report" --write-through --confirm
firestore saved-script delete --name "Owner Report" --confirm
Saved workflows are stored in firestore-saved-workflows.json under the CLI support directory, or in the directory pointed to by FIRESTRUCT_CLI_HOME for command-line runs. Output includes persistence.mode and persistence.crossProcessPersistent so automation can distinguish file-backed storage from in-memory test contexts.
Saved query options:
saverequires--nameand--collection.--where,--order-by, and--limituse the same parsing asfirestore query.--replaceoverwrites an existing saved query with the same name.runreuses the persisted query definition against the selected project or--projectoverride.deleterequires--confirm.
Saved script options:
saverequires--name,--collection, and either--fileor--script.--where,--order-by,--limit, and--timeoutare persisted with the script.showincludes the stored script source text;listomits it for compact output.runloads real Firestore documents from the saved query definition before executing the stored script.run --write-through --confirmuses the same emulator-only write-through guardrails asfirestore run-js.deleterequires--confirm.
Emulator-backed coverage validates persistence across CLI contexts, duplicate rejection, query/script execution, logs, confirmation, and deletion.
Analyze Schema
firestore schema --collection users --format json --output schema.json
firestore schema --collection users --format csv --output schema.csv
firestore schema --collection users --format typescript --output schema.ts
firestore schema --collection users --format json-schema --output schema.schema.json
Options:
--collectionis required and uses the same query path rules asfirestore query.--formatacceptsjson,csv,typescript,dart,kotlin,java,swift,objc, orjson-schema; it defaults tojson.--outputis optional; when provided, the generated schema/type output is written to that path.--limit,--where, and--order-byuse the same parsing asfirestore query.
Output contains selected project JSON, query metadata, schema analysis JSON, generated output text, optional destination path, and a task snapshot with status, operation counters, duration, attempt count, and error.
The current emulator-backed CLI test runs every supported schema format against a real Firestore emulator query and validates the generated artifact contents.
Create Document
firestore create --collection users --document-id alice --data '{"name":"Alice"}' --confirm
firestore create --collection users --document-id alice --data '{"name":"Alice"}' --allow-overwrite --confirm
firestore create --collection firestruct_verification/run1/users --document-id alice --data '{"name":"Alice"}' --access-token "$TOKEN" --confirm
Required options:
--collection--document-id--data--confirm--access-tokenor--authorizationis required for live projects.--production-confirm "WRITE <project-id>"is required for production projects.
--allow-overwrite permits replacing an existing target when the core service supports it.
Creates fail for read-only projects.
The shared core write service and CLI now have live REST request-shape support for single-document create/update/delete when an explicit authorization header is supplied. Approved disposable live read-back/cleanup verification is still required before live success is claimed.
Update Document
firestore update --document users/alice --data '{"name":"Alice"}' --confirm
firestore update --document firestruct_verification/run1/users/alice --data '{"name":"Alice"}' --access-token "$TOKEN" --confirm
Required options:
--document--data--confirm--access-tokenor--authorizationis required for live projects.--production-confirm "WRITE <project-id>"is required for production projects.
Updates fail for read-only projects. CLI evidence covers live request construction, authorization propagation, selected database IDs, and production confirmation guardrails. Approved disposable live read-back/cleanup verification remains open.
Delete Document
firestore delete --document users/alice --confirm
firestore delete --document firestruct_verification/run1/users/alice --access-token "$TOKEN" --confirm
Required options:
--document--confirm--access-tokenor--authorizationis required for live projects.--production-confirm "DELETE <project-id>"is required for production projects.
Deletes fail without --confirm and fail for read-only projects.
CLI evidence covers live request construction, authorization propagation, selected database IDs, and production confirmation guardrails. Approved disposable live read-back/cleanup verification remains open.
Run Through Selected Module
module select firestore
run query --collection users --limit 50
run dispatches Firestore actions only when the selected CLI module is firestore.
Not Yet Covered by CLI
The GUI Firestore module has broader coverage than the current CLI. These flows are not first-class CLI commands yet:
- bulk field operations
- live write-through JavaScript mutations
- recursive copy/move/rename
- Firebase-proven vector nearest-neighbor ranking behavior
CLI parity for these workflows is tracked in tasks/prd-phase-3-cli-parity.md. Completion requires CLI integration tests against Firebase emulators or approved live Firebase evidence for behavior the emulator cannot represent.
Source Anchors
Sources/FirestructCLIKit/FirestoreCommand.swiftSources/FirestructCore/FirestoreSimpleQueryService.swiftSources/FirestructCore/FirestoreDocumentWriteService.swiftTests/FirestructCLIIntegrationTests/FirestructCLIIntegrationTests.swift