# CyborgDB Release Notes Source: https://docs.cyborg.co/changelog CyborgDB follows a bi-monthly release cadence, with new features, enhancements, and bug fixes released every even month (Feb, Apr, etc). This changelog provides a summary of the changes in each release. **v0.18.0** 2026-10-01 ## CyborgDB v0.18.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * **BM25 full-text and hybrid search** * Mark metadata fields as `full_text` in `metadata_schema` to make them keyword-searchable; tune scoring per index with `bm25_k1` / `bm25_b` * `query(text=...)` runs a keyword search, optionally limited to specific `text_fields`; combine it with a query vector for hybrid search, blended with `alpha`, `rrf_k`, and `window_mult` * Available in the embedded libraries, the REST API, and the Python, JavaScript/TypeScript, and Go SDKs * **Metadata schema.** `create_index` accepts a `metadata_schema` that sets, per field, whether it is `filterable`, indexed for fast `$regex` / `$contains` matching (`pattern`), or `full_text` * **`query_metadata`** returns the items matching a metadata filter without a query vector, in the embedded libraries, all client SDKs, and the REST API (`POST /v1/vectors/query_metadata`) * **TurboQuant storage precision.** `storage_precision` adds the `tq12`, `tq8`, `tq6`, and `tq4` tiers for much smaller stored vectors at a small recall cost (`tq4` is the most compact) * `GET /v1/embedding-models` lists the built-in embedding models the service supports * `load_sample_dataset` (`loadSampleDataset` / `LoadSampleDataset`) in the client SDKs loads a sample dataset for quick evaluation * `StorageConfig.disk(...)` adds a `cache_metadata_index` option ### Improvements * Built-in embedding models no longer require PyTorch; installing the `[embeddings]` extra is no longer needed * `$regex` filters are now evaluated with RE2, giving linear-time matching and protection against pathological patterns * `$contains` filter operator for substring matching * The client SDKs now raise standardized error types (for example `AuthenticationError`, `NotFoundError`, `ValidationError`) * Telemetry is not sent when no API key is set * Index dimension is now validated at `create_index` ### Breaking Changes * **Memory backend removed.** `StorageConfig.memory()` and `CYBORGDB_DB_TYPE=memory` are gone; use `disk` (or `s3`) instead * **One process per storage target.** A disk path or S3 bucket/prefix must be used by a single CyborgDB process at a time. Running multiple embedded processes or service replicas against the same storage target is not supported * `GET /v1/indexes/list` and `GET /v1/indexes/training-status` now require the root (admin) key ### Bug Fixes * JavaScript/TypeScript SDK: fixed decoding of `contents` returned by `get()`, and `verifySsl: false` is now honored **v0.17.0** 2026-06-25 ## CyborgDB v0.17.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * **Access control (RBAC)** on encrypted indexes, in both the embedded libraries and the service * The holder of the root index KEK can mint per-user keys scoped to `read` and/or `write` — the keys a user holds determine their permissions, enforced cryptographically on every request * Embedded: `create_user_keys` (Python) / `CreateUserKeys` (C++), plus `index_key=` / `user_id=` per-operation overrides for stateless deployments * Service: `POST`/`GET`/`DELETE` on `/v1/indexes/{name}/users`, surfaced as `users` in the Python, JavaScript/TypeScript, and Go SDKs * **Per-index KMS & BYOK.** Each index can be wrapped by its own operator-managed key, optionally living in a customer's own AWS account * Providers: `aws-kms` (AWS KMS `Encrypt`/`Decrypt`), `aws` (Secrets Manager), and `none` * Pass `kms_name` to `create_index` instead of `index_key`; the service resolves the key server-side from the index's stored key envelope, so the SDK never holds a long-term key * Cross-account BYOK via `role_arn` + `external_id`; KMS credentials are kept separate from `CYBORGDB_S3_*` storage credentials * **Free tier.** `CYBORGDB_API_KEY` is now optional — without it, CyborgDB runs free-tier with a 1,000,000-item-per-index cap. Demo keys are available via `get_demo_api_key()` / `getDemoApiKey()` / `GetDemoAPIKey()` * **YAML configuration.** The service can be configured entirely by `cyborgdb.yaml` (resolved from `CYBORGDB_CONFIG_FILE`, the working directory, or `/etc/cyborgdb/`), with `${VAR}` / `${VAR:-default}` env-var substitution. Environment variables override the file * `storage_precision` lets you store rerank vectors as `float16` instead of `float32`, halving the on-disk footprint at a small recall cost * `rerank_mult` on `query` tunes stage 1 retrieval depth (`top_k * rerank_mult` candidates before reranking), and `include=["vector"]` returns the stored rerank vector ### Improvements * `n_lists` is now selected automatically by the core engine ### Breaking Changes * **Single index type.** CyborgDB now ships a single IVF index type. The polymorphic `index_config` object is gone, along with the IVFFlat / IVFPQ / IVFSQ distinction * Configuration parameters (`dimension`, `metric`, `embedding_model`, `storage_precision`) are now top-level fields on `create_index` * `dimension` is optional — the server auto-detects it from the first upsert, or infers it from `embedding_model` * In the embedded SDKs, all parameters after `index_key` are keyword-only * **Storage refactor.** The backing store surface is now just `memory`, `disk`, or `s3` * The `standalone`, `postgres`, and `redis` backends have been removed * `CYBORGDB_CONNECTION_STRING` is replaced by `CYBORGDB_DISK_PATH` and the `CYBORGDB_S3_*` variables — switch `standalone` → `disk` when upgrading * In the embedded SDKs, a single `StorageConfig` (`StorageConfig.memory()` / `.disk(path)` / `.s3(bucket)`) replaces the `index_location` / `config_location` / `items_location` trio of `DBConfig` objects * **Authentication overhaul.** `CYBORGDB_API_KEY` is now a *license* key only and no longer gates access to the REST API * Request authentication is controlled by `CYBORGDB_SERVICE_ROOT_KEY`. Leave it unset and authentication is disabled; set it and routes accept only the root key or a per-user `cdbk_…` token in the `X-API-Key` header * The legacy `cyborgdb-api-key` header and the `REQUIRE_API_KEY` flag have been removed * A wrong `index_key` now returns `401` instead of `500` **v0.16.1** 2026-04-13 ## CyborgDB v0.16.1 ### Behavior Changes * `query()` now returns only `id` fields by default when `include` is not specified * Previously defaulted to `["distance", "metadata"]`; new default is `[]` * Pass `include=["distance", "metadata"]` explicitly to retain the prior behavior * Applies to both the embedded library and the REST service (`QueryRequest`, `BatchQueryRequest`, and `BinaryQueryRequest` all default `include` to `[]`) * **Breaking change for REST API clients**: requests without an explicit `include` field will no longer receive `distance` or `metadata` in the response ### Bug Fixes * Fixed an S3 backing store bug to properly support S3 versioned objects * Fixed a distance computation bug affecting query result ordering * Fixed an arm64 Linux issue where `cyborgdb-core` could fail to load runtime dependencies * query() now returns vector IDs by default ### Improvements * CUDA wheels now statically link CUDA runtime dependencies for improved portability **v0.16.0** 2026-04-02 ## CyborgDB v0.16.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * CyborgDB now supports **Amazon S3** as a backing store for encrypted indexes * Configure via `CYBORGDB_DB_TYPE=s3` with an S3 connection string * Compatible with AWS S3, MinIO, and any S3-compatible object storage * **CyborgDB Migrate**: New tool for migrating vector embeddings from other databases into CyborgDB * Supports Pinecone, Qdrant, Weaviate, ChromaDB, and Milvus as sources * Interactive TUI wizard or headless TOML-based config for CI/CD pipelines * Install via `pip install cyborgdb-migrate` * IVFSQ default scalar quantization bits increased from 8 to 16 for improved recall accuracy ### Improvements & Bug Fixes * Stability improvements and bug fixes across all components * Ingest errors now properly propagate to callers instead of being silently swallowed * Improved serialization support for all backing store types * New API contract test suite for guaranteed interface stability * Expanded E2E test coverage across all SDK languages and backing stores **v0.15.0** 2026-02-24 ## CyborgDB v0.15.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Significant performance optimizations for all index types * Added new `IVFSQ` index type and replace `IVFFlat` as the default * Deprecated IVF index type * Added standalone support for on-device encrypted indexes without external database dependencies * Added support for binary upsert and query vectors for faster data transfer and reduced memory usage * New `/training-status` endpoint in REST API for monitoring index training progress and status * Improved error handling and logging across all components **v0.14.0** 2025-11-25 ## CyborgDB v0.14.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Significant performance optimizations for `cyborgdb-core`: * Reduced single-query (unbatched) latency by 75% * Introduced `standalone` database mode for quick evaluation and testing: * Automatically enabled when no external database is configured * Useful for rapid prototyping and development without infrastructure overhead * Not recommended for production use - use PostgreSQL or Redis for production deployments * Improved type definitions for TypeScript SDK **v0.13.1** 2025-10-31 ## CyborgDB v0.13.1 ### Bug Fixes * Fixed an issue where `cyborgdb-core` would fail to find runtime dependencies on certain Linux arm64 systems * Exposed demo API key creation on Go and TypeScript SDKs **v0.13.0** 2025-10-27 ## CyborgDB v0.13.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Merged `cyborgdb-lite` functionality into `cyborgdb-core`: * `cyborgdb-lite` package has been deprecated and removed * All features previously available in `cyborgdb-lite` are now included in `cyborgdb-core` * Simplified package structure with a single unified library for embedded use * CyborgDB Service now supports CUDA with `pip install "cyborgdb-service[cuda]"`: * Enables existing `cyborgdb-core` CUDA optimizations in the REST API microservice * Deprecated support for Python 3.9 due to EOL for: * `cyborgdb-core` * `cyborgdb-service` * `cyborgdb-py` **v0.12.0** 2025-08-28 ## CyborgDB v0.12.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Go Client SDK now available: * [`go get github.com/cyborginc/cyborgdb-go`](https://pkg.go.dev/github.com/cyborginc/cyborgdb-go) * Automatic index management enabled by default in CyborgDB Service: * Simplifies setup and reduces manual configuration * `IndexConfig` classes now optional - CyborgDB can auto-configure indexes on the fly based on data & usage characteristics * Training & retraining now handled automatically, optimizing index performance without manual intervention * Queries can now automatically determine the optimal number of clusters to search * LangChain integration now available for Python Client SDK **v0.11.0** 2025-06-26 ## CyborgDB v0.11.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript & TypeScript) ### New Features * CyborgDB is now available as a **REST API** microservice * Available as a Python package ([`cyborgdb-service`](https://pypi.org/project/cyborgdb-service/)) * Available as a Docker image ([`cyborginc/cyborgdb-service`](https://hub.docker.com/r/cyborginc/cyborgdb-service)) * CyborgDB Client SDKs now available for REST API microservice * Python ([`cyborgdb`](https://pypi.org/project/cyborgdb/)) * JavaScript ([`cyborgdb`](https://www.npmjs.com/package/cyborgdb)) * TypeScript ([`cyborgdb`](https://www.npmjs.com/package/cyborgdb)) * Introduced API key management and a new Admin Dashboard for enhanced operational control * Optimized concurrency handling using opportunistic mutexes to improve performance under load * Improved Docker container reliability and stability across deployment environments **v0.10.0** 2025-04-30 ## CyborgDB v0.10.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker - *early access*) * Client SDK (Python, JavaScript & TypeScript - *early access*) ### New Features * CyborgDB REST API service in **early access** * CyborgDB Client SDKs in **early access** * Python * JavaScript * TypeScript * [LangChain integration for CyborgDB](/versions/latest/integrations/langchain/introduction) now available * Install via `pip install "cyborgdb-core[langchain]"` * Use via `from cyborgdb_core.integrations.langchain import CyborgVectorStore` * Supports both `cyborgdb-core` and `cyborgdb-lite` * Added configurable logging utility for embedded library in C++ and [Python](/versions/latest/embedded/python/client/logger) **v0.9.2** 2025-04-14 ## CyborgDB v0.9.2 ### New Features * `cyborgdb_lite` is now available for **evaluation** and **non-commercial use** on [PyPI](https://pypi.org/project/cyborgdb-lite/) **v0.9.1** 2025-03-28 ## CyborgDB v0.9.1 ### Bug Fixes * Fixed a bug where [automatic embedding generation](/versions/latest/embedded/guides/encrypted-indexes/create-index#automatic-embedding-generation) would not load the model correctly when using [`load_index()`](/versions/latest/embedded/guides/encrypted-indexes/load-index) * Fixed a bug which caused intermittent [`query()`](/versions/latest/embedded/guides/data-operations/query) recall issues on Linux * Fixed incorrect type returns for [`get()`](/versions/latest/embedded/guides/data-operations/get-items) in C++ and Python APIs ### Improvements * Enabled pre-filtering on [metadata queries](/versions/latest/embedded/guides/data-operations/metadata-filtering) to improve performance * Added annotations and IDE auto-completion for the Python API * Expanded support to Python 3.9 - 3.13 **v0.9.0** 2025-02-28 ## CyborgDB v0.9.0 > [!NOTE] > > This release renamed Cyborg Vector Search to **CyborgDB**. **Deployment Model**: Embedded Library (Python & C++) ### New Features * Added support for **metadata fields & query filtering** * Metadata fields can be added to items during [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items#adding-items-with-metadata) calls * [`query()`](/versions/latest/embedded/guides/data-operations/metadata-filtering) calls can filter results based on metadata fields * Added support for **item deletion** * [`delete()`](/versions/latest/embedded/guides/data-operations/delete-items) calls can remove items from the encrypted index * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items) conflicts are now resolved by overwriting existing items * Added support for **automatic embedding generation** * An embedding model can be specified during [index creation](/versions/latest/embedded/guides/encrypted-indexes/create-index#automatic-embedding-generation) * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items#automatic-embedding-generation) calls can generate embeddings directly from index contents * [`query()`](/versions/latest/embedded/guides/data-operations/query#automatic-embedding-generation) calls can use the model to generate embeddings for query vectors ### Breaking Changes * IDs are now `string`-type (instead of `int`) * This impacts `upsert()`, `get()` and `query()` function signatures * `get_item()` and `get_items()` have been replaced by [`get()`](/versions/latest/embedded/guides/data-operations/get-items) **v0.8.0** 2024-12-19 ## Cyborg Vector Search v0.8.0 **Deployment Model**: Embedded Library (Python & C++) ### New Features * Added support for **encrypted item storage & retrieval** * Encrypted indexes can now handle item content storage * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items) calls can take item content as bytes, encrypt and store them in the index * [`get_item()`](/versions/latest/embedded/guides/data-operations/get-items) calls can retrieve encrypted item content and decrypt them * Client-side caching now available for encrypted indexes (via [`max_cache_size`](/versions/latest/embedded/guides/encrypted-indexes/create-index) parameter) * Client can now handle more than one index via multiple `EncryptedIndex` objects * Optimizations: * Full-pipeline GPU acceleration for encrypted indexes * Optimized quantization and ranking logic * Backing store batch operations for improved performance ### Breaking Changes * Python & C++ APIs now split into two classes: * [`Client`](/versions/latest/embedded/guides/encrypted-indexes/create-client) class now handles DB backend connection, index creation and loading * [`EncryptedIndex`](/versions/latest/embedded/guides/encrypted-indexes/create-index) class now handles data operations (e.g., `upsert()`, `query()`, etc.) **v0.7.0** 2024-10-31 ## Cyborg Vector Search v0.7.0 **Deployment Model**: Embedded Library (Python & C++) ### New Features * First *public* release of Cyborg Vector Search * Python API available through PyBind11 * GPU acceleration with CUDA support # CyborgDB Docs Source: https://docs.cyborg.co/index ![CyborgDB](https://mintcdn.com/cyborg/o5z3-JbkwPXf99Si/images/cyborgdb-white.svg?fit=max\&auto=format\&n=o5z3-JbkwPXf99Si\&q=85\&s=7ad60fe8f70762276000d401bece8503) The vector database that keeps\ your data encrypted at rest, in transit, and in use.Similarity search directly on encrypted embeddings — self-hosted in your VPC or on-prem. AES-256-GCM with your KMS key, per-operation key derivation, keys zeroized after use. **CyborgDB** is an encrypted vector database — similarity search directly on encrypted embeddings, with per-operation key derivation via your KMS and keys zeroized after use. Only the final candidates are decrypted. It runs self-hosted and standalone — persisting to local disk (default) or S3 — exposes a familiar API that slots into existing AI pipelines, and can be [GPU-accelerated with NVIDIA cuVS](https://developer.nvidia.com/blog/bringing-confidentiality-to-vector-search-with-cyborg-and-nvidia-cuvs/). \<5msp95 encrypted query latency 100M+vectors per index Zerodata leaves your boundary ### Choose Your Path > [card] [Learn the Fundamentals](versions/latest/intro/about) > > Understand the architecture and principles behind encrypted vector search > [card] [Start Building](versions/latest/intro/quickstart) > > Get hands-on with CyborgDB in minutes using our quickstart guide > [card] [Explore Deployment Options](versions/latest/intro/deployment-models) > > Discover embedded libraries, managed service, and custom deployment options ### Documentation Structure > [card] [Introduction](versions/latest/intro/about) > > Core concepts, deployment models, and getting started guides > [card] [CyborgDB Service](versions/latest/service/guides/intro/about) > > CyborgDB self-hosted with REST API and client SDKs > [card] [CyborgDB Embedded](versions/latest/embedded/guides/intro/about) > > Self-hosted, embedded deployments with Python and C++ bindings > [card] [Integrations](versions/latest/integrations/about) > > LangChain and other framework integrations for seamless adoption > [card] [How to Use These Docs](versions/latest/intro/using-docs) > > Navigation tips and conventions used throughout these docs # About CyborgDB Source: https://docs.cyborg.co/versions/latest/intro/about **CyborgDB** is a Confidential Vector Database: a self-hosted, standalone vector search engine that keeps your embeddings encrypted end to end. It persists to local disk or S3, runs entirely inside your own infrastructure, and adds confidential vector search to your stack **while keeping your data encrypted throughout the entire process**. ### Why *Confidential*? According to KPMG, 63% of enterprises say that confidentiality and data privacy are their top risk to AI adoption ([1](https://iapp.org/resources/article/consumer-perspectives-of-privacy-and-ai/)). In regulated sectors, this figure increases to 76%. Yet, when it comes to solutions which address these concerns, the market has yet to answer. This leaves a critical mass of companies unserved and unable to adopt AI in their workflows. They need **Confidential AI**. ### Where CyborgDB Fits in Your Stack Think of CyborgDB as a **dedicated vector layer** that sits alongside your application: ![CyborgDB RAG Overview](https://mintcdn.com/cyborg/kXyFWu9saA_TjOzS/images/cyborgdb-search-overview.png?fit=max\&auto=format\&n=kXyFWu9saA_TjOzS\&q=85\&s=2159d929922ba04a37b9864a2d401a6c) **Self-hosted, with no external dependencies.** CyborgDB persists to local disk or S3 and runs wholly within your own environment. This means: * **No data leaves your infrastructure** - Run it in your VPC or on-prem * **Familiar development patterns** - A vector API that slots into existing AI pipelines * **Minimal operational surface** - Local disk by default; no separate database to run * **Gradual adoption possible** - Start with vector search, expand as needed ### The Vector Search Problem Vector Search powers the most popular AI applications - RAG, RecSys, Semantic Search, etc. However, traditional vector databases have a fundamental security flaw: they use (and often store) vector embeddings in **plaintext** to enable fast similarity search. This creates a massive attack surface. Your sensitive data - converted to embeddings that still contain semantic meaning - sits unprotected in your database. For enterprise AI applications, this is unacceptable. **CyborgDB solves this** by enabling Approximate Nearest-Neighbor (ANN) search directly over **encrypted vectors**. Your embeddings are never stored in plaintext, and during search only the candidates being scored are decrypted. ### How CyborgDB Works CyborgDB uses **cryptographic hashing** and **symmetric encryption** to enable vector search over encrypted data: **The Process:** 1. **Your app sends vectors** → CyborgDB encrypts them using your private key 2. **Encrypted vectors stored** → Your database stores only encrypted data, never plaintext 3. **Search tokens derived** → Your key derives search tokens for the relevant clusters 4. **Search over encrypted space** → ANN search happens on encrypted vectors 5. **Results returned** → Matching vectors and metadata **Key Innovation:** Traditional vector databases decrypt data during search. CyborgDB performs similarity search over an encrypted index and only decrypts the candidates it scores, so your sensitive embeddings are **never stored in plaintext**. This approach gives you a **Confidential Vector Database** you run yourself, with embeddings that are never stored in plaintext. ### Why Developers Choose CyborgDB **🔄 Works with Your Existing Stack**\ No need to rewrite applications. CyborgDB exposes a familiar vector API that drops into the AI pipelines and frameworks you already use. **🔒 True End-to-End Encryption**\ Vector embeddings stay encrypted throughout their entire lifecycle - at rest, in transit, and **during search operations**, where only the candidates being scored are decrypted. **⚡ Production-Ready Performance**\ GPU-accelerated indexing and training with CUDA support. Optimized algorithms deliver fast results without compromising security. **🛠️ Developer-Friendly APIs**\ Familiar programming interfaces and extensive framework integrations (LangChain, etc.) make adoption seamless within existing AI workflows. **📈 Flexible Deployment**\ Deploy as embedded libraries for maximum control, or as a service for easier scaling. Choose what works best for your team and infrastructure. ### Next Steps > [card] [Start Building](./quickstart) > > *Get hands-on in minutes* > > Choose your deployment path and build your first confidential vector search application > [card] [Choose Your Deployment](./deployment-models) > > *Embedded vs Service* > > Understand the trade-offs between embedded libraries and service deployment > [card] [Backing Stores](./backing-stores) > > *Disk, S3* > > Learn where CyborgDB persists your encrypted index, and how to pick per environment # Backing Stores Source: https://docs.cyborg.co/versions/latest/intro/backing-stores CyborgDB transforms traditional databases into Confidential Vector Databases by leveraging their storage capabilities while adding encrypted vector search functionality. Choose the backing store that best fits your existing infrastructure and operational requirements. ![CyborgDB RAG Overview](https://mintcdn.com/cyborg/kXyFWu9saA_TjOzS/images/cyborgdb-search-overview.png?fit=max\&auto=format\&n=kXyFWu9saA_TjOzS\&q=85\&s=2159d929922ba04a37b9864a2d401a6c) > [!NOTE] > > **Storage surface.** CyborgDB supports `disk` and `s3` (AWS S3 or any S3-compatible store) across both deployment models. ## Amazon S3 *Available in: Service · Embedded* **Scalable cloud object storage for distributed deployments** CyborgDB supports Amazon S3 (and S3-compatible stores such as MinIO) as a backing store, enabling fully cloud-native deployments without managing a traditional database server. ### Key Benefits **Infinite Scalability**\ Object storage scales seamlessly with your data — no capacity planning or provisioning required. **Managed Infrastructure**\ No database servers to patch, tune, or back up. AWS handles availability and durability. **S3-Compatible**\ Works with AWS S3, MinIO, Cloudflare R2, and any other S3-compatible object store that supports conditional writes. **Best For:** Cloud-native deployments and workloads that already rely on object storage infrastructure. *** ## Disk *Available in: Service · Embedded* > [!NOTE] > > The embedded libraries and LangChain integration select this backend with `StorageConfig.disk(path)`. CyborgDB Service selects it via `CYBORGDB_DB_TYPE=disk` (and it is the default). **Persistent local storage for single-node deployments** The disk backend provides persistent key-value storage directly on local disk, with no network dependency. This makes it the recommended backing store for single-node CyborgDB deployments where simplicity and reliability are priorities. ### Key Benefits **No Network Dependency** All data is stored locally on disk — no external database servers to configure or manage. **Persistent Storage** Data survives process restarts. **Optimized for Embedded Use** Low memory footprint with filesystem support. **Best For:** Embedded/local deployments, single-machine applications, edge devices, and scenarios where you want persistent storage without external infrastructure. *** ## Managed Services Support CyborgDB works seamlessly with managed object storage services, reducing operational overhead while maintaining security and performance. > [card] AWS > > **Amazon S3**\ > Scalable object storage with 11 nines of durability > [card] Cloudflare > > **Cloudflare R2**\ > S3-compatible object storage with zero egress fees > [card] Self-hosted > > **MinIO**\ > S3-compatible object storage you control end-to-end *** ## Choosing the Right Backing Store > [tab] Use Disk > > * **Single-node deployment** — You want persistent local storage with no external dependencies > * **Edge devices** — Running on hardware without network access to databases > * **Simplicity** — You want a single-binary deployment with built-in storage > * **Local development** — Persistent storage that survives restarts without infrastructure > * **Default choice** — It's the service default and works out of the box > [tab] Use S3 > > * **Cloud-Native** — Your infrastructure already uses AWS or S3-compatible storage > * **Serverless** — You want durable storage without managing database servers > * **Cost** — Object storage is cheaper than provisioned database instances at scale > * **MinIO / R2** — You want S3-compatible storage on-premise or in a private cloud > [!WARNING] > > **One process per storage target.** A given disk path or S3 bucket/prefix must be used by a single CyborgDB process (embedded application or service instance) at a time. Running multiple processes or service replicas against the same storage target is not currently supported. To scale, add CPU threads or GPU acceleration to a single process, or shard indexes across separate storage targets. ## Configuration Examples ### Embedded library ```python Disk theme={null} from cyborgdb_core import Client, StorageConfig # Local disk storage_config = StorageConfig.disk("/var/lib/cyborgdb") client = Client(storage_config=storage_config) ``` ```python S3 theme={null} from cyborgdb_core import StorageConfig, S3Credentials # AWS S3 (credentials from the AWS default credential chain) storage_config = StorageConfig.s3("my-bucket", region="us-east-1") # AWS S3 with explicit credentials storage_config = StorageConfig.s3( "my-bucket", region="us-east-1", credentials=S3Credentials(access_key="AKID...", secret_key="..."), ) # MinIO (S3-compatible) storage_config = StorageConfig.s3( "my-bucket", region="us-east-1", endpoint="http://localhost:9000", credentials=S3Credentials(access_key="minioadmin", secret_key="minioadmin"), ) ``` ### Service Select via the `CYBORGDB_DB_TYPE` environment variable (or the equivalent YAML key). See [Environment Variables](../service/guides/advanced/env-vars) for the full list. ```bash theme={null} # disk (default) export CYBORGDB_DB_TYPE=disk export CYBORGDB_DISK_PATH=/var/lib/cyborgdb # optional, defaults to ~/.cyborgdb/data export CACHE_POLICY_VECTORS=true # optional, disk only export CACHE_POLICY_METADATA=true # optional, disk only export CACHE_POLICY_IDS=true # optional, disk only # s3 export CYBORGDB_DB_TYPE=s3 export CYBORGDB_S3_BUCKET=my-bucket export CYBORGDB_S3_REGION=us-east-1 export CYBORGDB_S3_ENDPOINT=http://localhost:9000 # optional, for S3-compatible stores export CYBORGDB_S3_PREFIX=cyborgdb/ # optional export CYBORGDB_S3_ACCESS_KEY=... # optional, otherwise the AWS default credential chain export CYBORGDB_S3_SECRET_KEY=... export CYBORGDB_S3_SESSION_TOKEN=... # optional ``` > [!NOTE] > > With a custom `CYBORGDB_S3_ENDPOINT` (MinIO, R2, etc.), set `CYBORGDB_S3_ACCESS_KEY` and `CYBORGDB_S3_SECRET_KEY` explicitly. ## Performance Characteristics | Backing Store | Latency | Throughput | Durability | Consistency | | - | :-: | :-: | :-: | :-: | | **Disk** | \~10µs | High | Local Disk | Single Process | | **S3** | \~10ms | Medium | Full (11 nines) | Strong | Choose based on your application's specific requirements for speed, durability, and consistency. # Deployment Models Source: https://docs.cyborg.co/versions/latest/intro/deployment-models CyborgDB offers two deployment approaches, each optimized for different use cases and operational requirements. Both models are **self-hosted** and run entirely within your own infrastructure. *** ## CyborgDB Service **Self-deployed REST API service** Deploy CyborgDB as a self-contained microservice that provides REST API access to confidential vector search. The service runs on your infrastructure and can scale independently from your applications. > [!TIP] > > Learn more about CyborgDB Service [here](../service/guides/intro/about). ### Key Benefits **Independent Scaling**\ Scale vector operations separately from your main application. Handle high query loads without impacting your core services. Each service process must own its storage target (disk path or S3 bucket/prefix); running multiple replicas against the same storage is not currently supported, so scale with more CPU threads or GPU acceleration, or shard indexes across separate storage targets. **Self-Optimization**\ The service automatically trains (and retrains) indexes as they grow, so search performance keeps up with your data without manual tuning. **Multi-Language Access**\ One service deployment supports multiple applications and programming languages through REST API and client SDKs. **Operational Simplicity**\ Centralized deployment, monitoring, and maintenance. Update vector search capabilities without touching application code. ### Deployment Options > [card] [Docker Deployment](../service/guides/intro/quickstart-docker) > > *Containerized service* > > Deploy as a Docker container for easy orchestration and scaling > [card] [Python Service](../service/guides/intro/quickstart-python) > > *Direct Python installation* > > Install and run as a Python service with pip for lightweight deployment ### Client SDKs > [card] [Python SDK](../service/python-sdk/introduction) > > Full-featured Python client with async support and type hints > [card] [JavaScript/TypeScript SDK](../service/js-ts-sdk/introduction) > > Modern JS/TS client with Promise-based API and TypeScript definitions > [card] [Go SDK](../service/go-sdk/introduction) > > High-performance Go client with idiomatic API and concurrency support *** ## CyborgDB Embedded **Direct library integration** Embed CyborgDB directly into your applications using the Python library. This approach provides maximum control and performance by eliminating network overhead. > [!TIP] > > Learn more about CyborgDB Embedded [here](../embedded/guides/intro/about). ### Key Benefits **Maximum Performance**\ Direct memory access and zero network latency. Ideal for latency-sensitive applications requiring sub-millisecond response times. **Deep Integration**\ Customize every aspect of vector operations. Perfect for specialized workflows and performance tuning requirements. **Complete Control**\ Full ownership of the vector search stack. No external dependencies or service management overhead. **Advanced Customization**\ Access to low-level APIs for custom index configurations, memory management, and algorithm tuning. ### Deployment Options > [card] [Python Embedded](../embedded/python/introduction) > > *Direct Python integration* > > Embed confidential vector search directly in Python applications *** ## Choosing the Right Model > [tab] Use CyborgDB Service > > * **Multi-application architecture** - Multiple services need vector search capabilities > * **Team scalability** - Different teams use different programming languages > * **Operational simplicity** - You want centralized vector search management > * **Independent scaling** - Vector workloads need to scale separately from applications (one service process per storage target) > * **Microservice patterns** - You prefer service-oriented architecture > [tab] Embedded Deployment > > * **Maximum performance** - Sub-millisecond latency requirements > * **Deep customization** - Need fine-grained control over vector operations > * **Single application focus** - One primary application using vector search > * **Resource optimization** - Want to eliminate network overhead entirely > * **Specialized workflows** - Require custom integration or algorithm tuning Start with embedded libraries for rapid prototyping, then scale to service deployment for production multi-application environments, or vice versa based on your specific requirements. # Embedding Inversion Source: https://docs.cyborg.co/versions/latest/intro/embedding-inversion Vector embeddings are often treated as opaque numerical representations, but they are not. Modern machine learning techniques can **reconstruct the original content** from an embedding with high fidelity, making plaintext embeddings a direct data exposure risk. > [!WARNING] > > Cyborg has [demonstrated](./threat-model#4-attack-demonstration) embedding inversion attacks achieving **99.38% content reconstruction** in under 5 minutes on a production-like vector database. ## 1. What Is Embedding Inversion? Embedding models map input data (text, images, audio, or any other modality) into dense vector representations that capture semantic meaning. **Inversion** is the reverse process: given a vector, recover the content that produced it. Researchers have demonstrated successful inversion across every major embedding modality. The techniques are well-documented in academic literature, publicly available, and increasingly effective: * **Publicly available** and require no special expertise to run * **Fast**: reconstructing a document takes only a few seconds * **Accurate**: achieving 95-99%+ fidelity with the original content This means that **anyone with access to your embeddings effectively has access to the original data**. ## 2. Inversion Across Modalities Embedding inversion is not limited to a single data type. Researchers have demonstrated successful attacks across text, images, audio, and even genomic data. ### Text Text embedding inversion is the most mature area of research. The landmark paper [Text Embeddings Reveal (Almost) As Much As Text](https://arxiv.org/abs/2310.06816) (Morris et al., EMNLP 2023) introduced [vec2text](https://github.com/jxmorris12/vec2text), an iterative hypothesis-and-correction approach that achieves **92% exact recovery** of 32-token inputs with a BLEU score of 97.3. The method successfully extracted full names from clinical note embeddings. Subsequent work has expanded the threat: * **[GEIA](https://arxiv.org/abs/2305.03010)** (Li et al., ACL 2023) uses a fine-tuned GPT-2 decoder to recover coherent sentences, including named entities, from sentence embeddings with only black-box model access. * **[Transferable Embedding Inversion](https://arxiv.org/abs/2406.10280)** (Huang et al., ACL 2024) trains an inverter on a surrogate model and transfers it to attack a different victim model the attacker cannot query - recovering 98% of age and 99% of sex information from clinical text embeddings. * **[Zero2Text](https://arxiv.org/abs/2602.01757)** (2026) requires no training at all, using LLM priors with dynamic ridge regression to invert even closed-source models like OpenAI's `text-embedding-3-small/large`. Standard defenses like differential privacy noise fail to stop it. * **[Multilingual inversion](https://arxiv.org/abs/2401.12192)** (ACL 2024) extends the threat beyond English to cross-lingual attacks. Earlier foundational work by [Song & Raghunathan (ACM CCS 2020)](https://arxiv.org/abs/2004.00053) first demonstrated systematic privacy leakage from embeddings, including authorship and stylometry information. ### Images Image embedding inversion has progressed from blurry reconstructions to near-photographic fidelity: * **Face recognition embeddings** are particularly vulnerable. [Diffusion-based attacks](https://arxiv.org/abs/2504.18015) (2025) achieve **98.55% attack accuracy** against ArcFace on the LFW dataset by using unconditional diffusion models as generative priors. Earlier work by [Fredrikson et al. (ACM CCS 2015)](https://dl.acm.org/doi/10.1145/2810103.2813677) showed that crowdworkers could identify individuals from reconstructed face images with 95% accuracy. * **CLIP embeddings** encode far more than intended. [Kazemi et al. (NeurIPS 2024)](https://arxiv.org/abs/2403.02580) demonstrated that pure gradient-based optimization against CLIP embeddings - with no decoder or training required - can reveal semantic content including concept blending and biases inherited from training data. * **Vision-language model features** can be inverted to recover image captions with up to 0.52 ROUGE-L scores and classification labels at 92.71% accuracy ([CapRecover, 2025](https://arxiv.org/html/2507.22828v2)). ### Audio and Speech Speaker embeddings carry enough information to reconstruct recognizable voice characteristics: * Voice style transfer techniques can [reconstruct speech from stolen speaker embeddings](https://ieeexplore.ieee.org/document/9648375/) that is convincing enough to spoof automatic speaker verification systems (IEEE 2021). * [Score-based impersonation attacks](https://arxiv.org/html/2603.02781v1) (2026) achieve a 91.65% success rate using only 50 queries to the target system. * Even [voice anonymization systems](https://www.researchgate.net/publication/355223468_On_the_invertibility_of_a_voice_privacy_system_using_embedding_alignement) can be inverted, recovering up to 62% of original speaker identities. ### Other Modalities The threat extends beyond the modalities above: * **DNA sequences**: [Ouaari et al. (2026)](https://arxiv.org/abs/2603.06950) achieved 99.8% nucleotide accuracy and 79.5% exact sequence matches when inverting genomic foundation model embeddings from models like Evo 2. * **Graph data**: Inference attacks can [extract private node and edge attributes](https://arxiv.org/pdf/2008.13072) from graph neural network embeddings, relevant to social networks and knowledge graphs. ## 3. Why It Matters The academic results above are not theoretical. The inversion tools are open-source and the techniques are reproducible. Organizations adopting RAG and other AI architectures centralize sensitive data from across multiple systems - HR records, financial data, medical information, legal documents - into a single vector database. If that database stores embeddings in plaintext, a single breach exposes intelligence from every connected system. ### Real-World Attack Results Testing against standard (unencrypted) vector databases demonstrates the severity: | Embedding Storage | Reconstruction Rate | Avg. Similarity | | - | - | - | | **Plaintext** (standard vector DBs) | 95-100% high-similarity reconstructions | >95% | | **Encrypted** (CyborgDB) | **0%** successful reconstructions | **0.0%** | Against unencrypted databases, inversion models routinely achieve near-exact reconstruction of the original content. Against CyborgDB's encrypted embeddings, the same models produce only empty results: the attack is completely ineffective. > [!NOTE] > > You can reproduce these results yourself using the [vectordb-inversion-demo](https://github.com/cyborginc/vectordb-inversion-demo) repository, which demonstrates embedding extraction and inversion against several popular vector databases and shows how CyborgDB's encryption prevents the attack entirely. ## 4. Attack Vectors Embedding inversion requires two steps: **extraction** and **inversion**. The inversion tooling is freely available - the attacker's only challenge is getting access to the raw embeddings. In practice, there are many ways this can happen. ```mermaid theme={null} graph LR A(Embedding Access) --> B(Inversion Model) B --> C(Reconstructed Content) style A fill:#ff6b6b,color:#fff style C fill:#ff6b6b,color:#fff ``` ### Storage-Level Extraction Most vector databases store embeddings as plaintext on disk - whether in database tables, flat files, or memory-mapped segments. These are accessible to anyone with file system access to the database storage, including cloud administrators, container escape exploits, or compromised backup systems. **This works even if the database is stopped or password-protected.** ### Memory-Level Extraction Embeddings in process memory can be dumped via `ptrace` system calls, core dumps, or direct reads of `/proc/{PID}/mem` on Linux. This is especially relevant in containerized environments where debugging capabilities may be enabled, and **completely bypasses** all authentication, network access controls, and application-level security. ### API and Credential Compromise Leaked or stolen API keys, database connection strings, or cloud credentials give attackers direct query access to the vector database - no file system exploit required. This includes: * **Leaked API keys**: Credentials accidentally committed to version control, exposed in logs, or stolen via phishing * **Compromised cloud credentials**: IAM roles, service account keys, or SSO tokens that grant access to managed database services * **Overly permissive access policies**: Database instances exposed to the public internet or accessible across network boundaries without proper segmentation With query access, an attacker can simply read embeddings through the database's own API, making storage-level protections irrelevant. ### Backup and Snapshot Exposure Database backups, cloud snapshots, and disaster recovery replicas often contain full copies of the embedding data. These are frequently stored with weaker access controls than the production database and may persist long after the original data has been rotated or deleted. ### Supply Chain and Insider Access Cloud providers, managed database operators, and third-party infrastructure vendors may have access to the underlying storage or compute environment. A compromised or malicious insider at any layer of the stack can extract embeddings without triggering application-level monitoring. ### The Common Thread All of these vectors share the same fundamental problem: if the embeddings are stored or processed in plaintext at any point, they are vulnerable to extraction and inversion. This is why [encryption in use](./encryption) - not just encryption at rest or in transit - is essential to mitigating the inversion threat. ## 5. Limitations of Common Security Measures While important as part of a defense-in-depth strategy, several common security measures **do not directly address** the embedding inversion threat: > [card] Network Access Controls > > Important for perimeter security, but do not protect against file system or memory-level extraction > [card] Database Authentication > > Controls who can query the database, but does not encrypt the underlying storage > [card] TLS / Encryption in Transit > > Protects data between client and server, but not data at rest or in use > [card] Application-Layer Auth > > Governs application access, but does not prevent direct storage-level reads These controls remain valuable - but as long as **the embeddings themselves are stored in plaintext**, the inversion risk persists. ## 6. How CyborgDB Prevents Inversion CyborgDB eliminates the inversion attack surface by ensuring embeddings are **never stored in plaintext**: * **Encryption at rest**: All embeddings are encrypted with AES-256-GCM before being written to the backing store * **Encryption in use**: Embeddings remain encrypted during search, except the candidates being scored * **Per-record IVs**: Each record uses a unique initialization vector, preventing cross-record correlation * **Customer key control**: Encryption keys are managed by the customer, not the database operator * **KMS integration**: CyborgDB Service can protect index keys with AWS KMS or AWS Secrets Manager, including keys in a customer-owned AWS account Because the backing store only ever contains ciphertext, an attacker who gains full access to the database - whether through file system access, storage snapshots, or a compromised backing store - obtains only encrypted data that is computationally infeasible to invert. > [!TIP] > > For full details on CyborgDB's cryptographic implementation, see the [Encryption](./encryption) guide. ## 7. Further Reading > [card] [Security Overview](./security-overview) > > CyborgDB's defense-in-depth security architecture > [card] [Threat Model](./threat-model) > > Adversary model, attack surfaces, and mitigation mapping # Encryption Source: https://docs.cyborg.co/versions/latest/intro/encryption CyborgDB encrypts **all sensitive data** — including embeddings, document IDs, contents, and metadata — **end-to-end**, ensuring that nothing is stored or processed in plaintext without authorization. This section details the cryptographic design, the indexing scheme, and how forward privacy is achieved. > [!TIP] > > The technology discussed in this guide is covered by Cyborg's IP portfolio, including US Patents [12,164,664](https://patents.google.com/patent/US12164664), [11,860,875](https://patents.google.com/patent/US11860875), [11,423,028](https://patents.google.com/patent/US11423028) and [10,977,315](https://patents.google.com/patent/US10977315), among others. Any use is subject to licensing agreements. ## 1. Data Encryption All stored records in CyborgDB are encrypted using: * AES-256 (A symmetric encryption algorithm with a 256-bit key size, considered secure against brute-force attacks) in GCM mode (Galois/Counter Mode — a block cipher mode that provides both confidentiality and integrity (authenticated encryption)) * Per-record unique IVs (Initialization Vectors — random values used to ensure distinct ciphertexts for identical plaintexts.) to prevent ciphertext pattern reuse * Authenticated encryption, ensuring both confidentiality and tamper detection This symmetric encryption is applied to: > [card] Vector Embeddings > [card] Document IDs > [card] Document Contents > [card] Metadata Fields This guarantees that even with full disk access, data remains encrypted and cannot be modified undetected. ## 2. Forward-Secure Cryptographic Indexing CyborgDB also encrypts the **search index** used for approximate nearest neighbor (ANN) retrieval. The index is constructed using a **forward-secure** cryptographic scheme inspired by research in forward-private searchable encryption, combined with Cyborg's patented enhancements. > [!NOTE] > > Forward privacy ensures that newly inserted entries cannot be linked to prior search queries, even if the index is compromised later. ### Key Concepts 1. **Per-cluster seeds via HMAC**\ Each ANN cluster is assigned a unique seed derived from the master key using HMAC (A keyed-hash message authentication code — provides both message integrity and authentication.)(MasterKey, ClusterID). 2. **Binary tree indexing with SHA-3**\ The ANN cluster is represented as a binary tree. Internal node keys are derived from their children using SHA-3 (A cryptographic hash function standardized by NIST). 3. **Token-scoped search**\ Search queries produce tokens that only target the minimal set of node keys required to execute the query. Unnecessary index nodes are ignored. 4. **In-use encryption**\ Queries are executed over ciphertext nodes and only decrypt the candidates they score. ### Cryptographic Vector Indexing Flow Below is an overview of how CyborgDB indexes vectors cryptographically: ```mermaid theme={null} graph TD A(Vector Embedding) -->|"Clustering Model"| B(Cluster Assignment) MK(Master Key) -->|"HMAC(MasterKey,ClusterID)"| C(Cluster Seed) B --> C CM(Insertion Counter) --> D(Seed + Counter) C --> D D -->|"SHA-3(left)"| E1(Node Key L) D -->|"SHA-3(right)"| E2(Node Key R) E1 --> F1(KV Store Key) E2 --> F2(Encrypted Embedding + Metadata) A --> |"AES(Node Key R)"| F2 ``` This flow demonstrates how CyborgDB transforms a single vector embedding into multiple encrypted components: 1. **Vector clustering**: The clustering model assigns each embedding to an optimal cluster for efficient ANN search 2. **Deterministic key derivation**: The master key and cluster ID generate a unique seed for this cluster 3. **Forward privacy**: A per-cluster insertion counter ensures identical embeddings get different cryptographic treatment on each insertion 4. **Dual-purpose keys**: SHA-3 produces two keys serving different functions - one for storage indexing, one for encryption 5. **Secure storage**: The final encrypted embedding can only be decrypted with the derived Node Key R This design ensures that even identical vector embeddings result in different ciphertexts and index entries, preventing correlation attacks across insertions. ## 3. Cryptographic Approximate Nearest Neighbor Search CyborgDB's search execution maintains cryptographic protection throughout the entire query process, leveraging the cryptographic index discussed [above](#2-forward-secure-cryptographic-indexing). ### Token Generation When a client initiates a query: 1. **Query vector preparation**: The search vector undergoes the same clustering model to determine target clusters 2. **Search token derivation**: For each target cluster, the client recreates the cryptographic key hierarchy 3. **Minimal key generation**: Only the node keys required for the query path are computed ```mermaid theme={null} graph TD A(Query Vector) -->|"Clustering Model"| B(Target Cluster IDs) MK(Master Key) -->|"HMAC(MasterKey,ClusterID)"| C(Cluster Seeds) B --> C CM(Insertion Counter) --> ITER{{"For each occurrence"}} C --> ITER ITER -->|"SHA-3(left)"| E1(Node Key L) ITER -->|"SHA-3(right)"| E2(Node Key R) E1 --> F(Search Tokens) E2 --> G(Decryption Keys) ``` This process generates the exact same keys used during indexing, but only for the clusters relevant to the query. The client now possesses the minimal set of tokens needed to decrypt the required index nodes. > [!NOTE] > > This token-scoped approach ensures that irrelevant index nodes remain opaque ciphertexts, minimizing information leakage. ### Encrypted Index Traversal With search tokens in hand, the server executes the query while maintaining cryptographic protection: ```mermaid theme={null} graph LR A(Search Tokens) --> B(KV Store Lookup) B --> C(Encrypted Index Nodes) D(Decryption Keys) --> E(Optional Decryption) C --> E E --> F(Decrypted Embeddings) ``` The retrieval and decryption process: 1. **Token-based retrieval**: Search tokens are used as lookup keys in the encrypted KV store 2. **Optional decryption**: Embeddings can be decrypted for final distance computation This ensures that the server can execute efficient ANN search while never having persistent access to plaintext embeddings or the ability to decrypt irrelevant index nodes. ## 4. Security Benefits CyborgDB's multi-layered cryptographic design provides comprehensive protection against various threat scenarios, leveraging Cyborg's patented technology to achieve security properties impossible with traditional approaches. ### Threat Protection Matrix | Threat Scenario | Protection Mechanism | | - | - | | **Disk theft** | AES-256-GCM encryption at rest | | **Network interception** | TLS + AEAD encryption in transit | | **Server compromise** | In-use encryption limits plaintext to the candidates being scored | | **Index leakage** | Forward privacy hides relationship between new inserts and past searches | | **Embedding inversion** | Ciphertext embeddings are never exposed — inversion is not possible without keys | ### Security Properties | Property | Implementation | Benefit | | - | - | - | | **Query Privacy** | Token-scoped key derivation | Server never sees full index keys | | **Result Confidentiality** | End-to-end encryption | Results are only returned to callers holding the index key | | **Forward Security** | Counter-based key evolution | Past compromises don't affect future queries | | **Index Obfuscation** | Ciphertext-only storage | Unused index nodes remain opaque | | **Correlation Resistance** | Per-insertion randomization | Identical vectors produce different ciphertexts | > [!TIP] > > Traditional encrypted search schemes are vulnerable to statistical attacks. CyborgDB's forward-secure design prevents these correlation attacks. ## 5. Performance While comprehensive cryptographic protection typically comes with significant overhead, CyborgDB's implementation has been **extensively optimized** to achieve production-grade performance that rivals plaintext systems. ### Performance Optimizations CyborgDB achieves exceptional performance through several key optimizations: * **Hardware acceleration**: Leveraging AES-NI and SHA extensions available in modern processors * **Parallel key derivation**: Computing node keys concurrently across multiple clusters * **Lazy decryption**: Only decrypting index nodes when accessed during search traversal * **Vectorized operations**: Batch processing of similarity computations in encrypted space * **Cache-optimized layouts**: Organizing encrypted index structures for optimal memory access patterns These optimizations deliver industry-leading performance: > **>10,000 QPS** at **95% recall** for ANN search over encrypted embeddings\ > > > **Sub-10ms query latency** for typical workloads # Getting an API Key Source: https://docs.cyborg.co/versions/latest/intro/get-api-key An API key is optional. Without one, CyborgDB runs in free tier with a limit of 1,000,000 items per index. A paid API key removes that limit. This guide walks you through signing up and generating an API key. ## Overview CyborgDB offers both free and paid API keys: > [card] Free API Key > > *Perfect for evaluation and testing* > > * Up to 1M items per index > * Community support > [card] Paid API Key > > *Full production capabilities* > > * Unlimited items per index > * Priority support *** ## Step-by-Step Guide **1. Sign Up for CyborgDB** Visit [cyborgdb.co](https://cyborgdb.co/new) and create your account. 1. Click **"Sign Up"** in the top navigation 2. Enter your email address and create a secure password 3. Verify your email address by clicking the link sent to your inbox 4. Complete your profile setup > [!NOTE] > > Your account starts with access to free API keys by default. **2. Choose Your Plan (Optional)** If you need production capabilities, upgrade to a paid plan. 1. Navigate to the **"Billing"** section in your dashboard 2. Review the available plans and features 3. Select the plan that best fits your needs 4. Complete the payment setup > [!WARNING] > > **Plan Disclosure**: Paid plans remove the 1M item limit per index. Free plans and keyless use have a 1M item limit per index. You can always start free and upgrade later. **3. Generate Your API Key** Create a new API key from your dashboard. 1. In your CyborgDB dashboard, locate the **"API Keys"** section 2. Click the **"Add"** button next to "API Keys" ![Screenshot of CyborgDB Dashboard with API Keys 'Add' button highlighted](https://mintcdn.com/cyborg/kXyFWu9saA_TjOzS/images/cyborgdb-dashboard-create-api-key.png?fit=max\&auto=format\&n=kXyFWu9saA_TjOzS\&q=85\&s=92a9c1d24ff3c459a118eea46067980a) CyborgDB Dashboard - API Keys Section **4. Copy and Secure Your API Key** Your API key will be generated and displayed. ![Screenshot of CyborgDB Dashboard showing generated API key](https://mintcdn.com/cyborg/kXyFWu9saA_TjOzS/images/cyborgdb-dashboard-api-key-created.png?fit=max\&auto=format\&n=kXyFWu9saA_TjOzS\&q=85\&s=c58f991a49804f9f41f5ba416fe0c261) CyborgDB Dashboard - API Key Generated > [!WARNING] > > **Important**: Copy your API key immediately and store it securely. For security reasons, you won't be able to see the full key again after leaving this page. **Best Practices:** * Store your API key in environment variables, not in your code * Never commit API keys to version control * Use different keys for development and production environments * Rotate keys regularly for enhanced security *** ## Using Your API Key Once you have your API key, you can use it with any CyborgDB deployment. > [!NOTE] > > With CyborgDB Service, the API key is set on the server as `CYBORGDB_API_KEY`. Client SDKs do not send this key; when authentication is enabled, they authenticate to the service with the service root key or a per-user token. See [Environment Variables](../service/guides/advanced/env-vars). With the embedded library, pass it to `Client`: > [tab] Environment Variable (Recommended) > > Set your API key as an environment variable: > > ```bash theme={null} > export CYBORGDB_API_KEY="your-api-key-here" > ``` > > Then reference it in your code: > > ```python theme={null} > import os > from cyborgdb_core import Client, StorageConfig > > client = Client( > api_key=os.getenv("CYBORGDB_API_KEY", ""), > storage_config=StorageConfig.disk("/var/lib/cyborgdb"), > ) > ``` > [tab] Direct Usage > > Use your API key directly in your code (not recommended for production): > > ```python theme={null} > from cyborgdb_core import Client, StorageConfig > > client = Client( > api_key="your-api-key-here", > storage_config=StorageConfig.disk("/var/lib/cyborgdb"), > ) > ``` > [tab] Configuration File > > Store in a configuration file that's excluded from version control: > > ```python theme={null} > # config.py (add to .gitignore) > CYBORGDB_API_KEY = "your-api-key-here" > > # main.py > from config import CYBORGDB_API_KEY > from cyborgdb_core import Client, StorageConfig > > client = Client( > api_key=CYBORGDB_API_KEY, > storage_config=StorageConfig.disk("/var/lib/cyborgdb"), > ) > ``` *** ## Managing Your API Keys ### Dashboard Management From your CyborgDB dashboard, you can: * **View all API keys** - See all keys associated with your account * **Create new keys** - Generate additional keys for different projects * **Revoke keys** - Disable keys that are no longer needed * **Monitor usage** - Track API key usage and performance *** ## Next Steps > [card] [Start Building](./quickstart) > > *Jump into the quickstart guide* > > Use your new API key to get started with CyborgDB > [card] [Choose Deployment](./deployment-models) > > *Service vs Embedded* > > Decide between CyborgDB Service or Embedded libraries > [card] [Framework Integration](../integrations/langchain/introduction) > > *LangChain integration* > > Replace your existing vector store with CyborgDB Got your API key? You're ready to start building confidential AI applications! # Migrating from Another Vector Database Source: https://docs.cyborg.co/versions/latest/intro/migrate **CyborgDB Migrate** is a tool for migrating vector embeddings and metadata from popular vector databases into CyborgDB. It handles the full migration lifecycle: connect to source, batch-extract vectors, upsert into an encrypted CyborgDB index, checkpoint progress, and verify results. > [!NOTE] > > CyborgDB Migrate requires a running CyborgDB Service instance. See the [Python Quickstart](../service/guides/intro/quickstart-python) or [Docker Quickstart](../service/guides/intro/quickstart-docker) to get one running first. ## Supported Sources | Source | Install Extra | | - | - | | **Pinecone** | `pip install "cyborgdb-migrate[pinecone]"` | | **Qdrant** | `pip install "cyborgdb-migrate[qdrant]"` | | **Weaviate** | `pip install "cyborgdb-migrate[weaviate]"` | | **ChromaDB** | `pip install "cyborgdb-migrate[chromadb]"` | | **Milvus** | `pip install "cyborgdb-migrate[milvus]"` | To install support for all sources at once: ```bash theme={null} pip install "cyborgdb-migrate[all]" ``` *** ## Two Modes of Operation > [card] Interactive TUI > > *Step-by-step guided wizard* > > Launch the interactive terminal UI — select your source, enter credentials, configure your destination, and watch the migration in real time. > > ```bash theme={null} > cyborgdb-migrate > ``` > [card] Headless CLI > > *Scriptable & CI/CD friendly* > > Run non-interactively using a TOML config file. Supports resuming interrupted migrations. > > ```bash theme={null} > cyborgdb-migrate --config migration.toml > ``` *** ## Quickstart: Interactive TUI **1. Install cyborgdb-migrate** Install the package with the extra for your source database: ```bash theme={null} pip install "cyborgdb-migrate[pinecone]" # or qdrant, weaviate, chromadb, milvus, all ``` **2. Launch the wizard** ```bash theme={null} cyborgdb-migrate ``` The TUI will walk you through: 1. Selecting your source database type 2. Entering source credentials 3. Configuring your CyborgDB destination (host, API key, index name) 4. Live progress display with per-batch stats When complete, a spot-check verification is automatically run to confirm data integrity. *** ## Quickstart: Headless CLI **1. Install cyborgdb-migrate** ```bash theme={null} pip install "cyborgdb-migrate[pinecone]" # or your source ``` **2. Create a config file** Create a `migration.toml` file. Environment variable interpolation (`${VAR}`) is supported: ```toml theme={null} [source] type = "pinecone" # pinecone | qdrant | weaviate | chromadb | milvus api_key = "${PINECONE_API_KEY}" index = "my-source-index" # namespace = "..." # optional: Pinecone namespaces or Milvus partitions [destination] host = "http://localhost:8000" # your CyborgDB Service URL api_key = "${CYBORGDB_SERVICE_ROOT_KEY}" # service root key (needed to create indexes) index_name = "my-cyborgdb-index" create_index = true # set false to migrate into an existing index # kms_name = "aws-kms" # use a KMS-backed key instead of a generated one # index_key = "hex-encoded-key" # existing non-KMS index: its key (or key_file) # storage_precision = "float16" # float32 (default) | float16 | tq12 | tq8 | tq6 | tq4 # Full-text (BM25) search — fixed at index creation, immutable afterward. # text_fields = ["title", "body"] # metadata fields to make BM25-searchable # bm25_k1 = 1.2 # term-frequency saturation (default 1.2) # bm25_b = 0.75 # length normalization (default 0.75) # Per-field metadata indexing policy — fixed at index creation, immutable. # Fields left out are filterable by default. # [destination.metadata_schema] # title = { filterable = true, pattern = true } # blob = { filterable = false } # body = { full_text = true } # same as listing it in text_fields [options] batch_size = 200 # vectors per batch (default: 100) checkpoint_every = 10 # save checkpoint every N batches spot_check_per_batch = 4 # vectors sampled per batch for verification ``` See [example-config.toml](https://github.com/cyborginc/cyborgdb-migrate/blob/main/example-config.toml) for all available options. **3. Run the migration** ```bash theme={null} cyborgdb-migrate --config migration.toml ``` If the migration is interrupted, resume from where it left off: ```bash theme={null} cyborgdb-migrate --config migration.toml --resume ``` *** ## CLI Reference | Flag | Default | Description | | - | - | - | | `--config FILE` | — | TOML config file; activates non-interactive mode | | `--resume` | false | Resume from a saved checkpoint (requires `--config`) | | `--batch-size INT` | 100 | Vectors per batch | | `--log-file FILE` | `./cyborgdb-migrate.log` | Log file path | | `--quiet` | false | Minimal output | | `--version` | — | Print version and exit | *** ## How It Works * **Double-buffered pipeline**: one thread extracts the next batch while the previous batch's upsert is in flight, maximising throughput. * **Checkpointing**: progress is saved to disk every N batches so interrupted migrations can be resumed with `--resume`. * **Retry with backoff**: upserts retry with exponential backoff (1s → 2s → 4s) before failing a batch. * **Spot-check verification**: after migration, a random sample of vectors is fetched back from CyborgDB and compared to the source (within `atol=1e-6`) to confirm data integrity. Exit code `2` indicates migration completed but spot-check failed. *** ## Source-Specific Notes > [accordion] Pinecone > > Set `namespace` in `[source]` to migrate a specific Pinecone namespace. Omit to migrate the default namespace. > [accordion] Milvus > > Set `namespace` in `[source]` to migrate a specific partition. > [accordion] Weaviate > > Ensure your Weaviate instance has the `text2vec` module disabled or that raw vectors are accessible, as cyborgdb-migrate reads pre-computed vectors directly. # Open Source Source: https://docs.cyborg.co/versions/latest/intro/open-source ## Client SDKs All CyborgDB client SDKs are open source and available on GitHub. We welcome contributions, bug reports, and feature requests! > [card] [Python SDK](https://github.com/cyborginc/cyborgdb-py) > > View the source code or report issues on Github: > > `cyborginc/cyborgdb-py` > [card] [JavaScript SDK](https://github.com/cyborginc/cyborgdb-js) > > View the source code or report issues on Github: > > `cyborginc/cyborgdb-js` > [card] [TypeScript SDK](https://github.com/cyborginc/cyborgdb-js) > > View the source code or report issues on Github: > > `cyborginc/cyborgdb-js` > [card] [Go SDK](https://github.com/cyborginc/cyborgdb-go) > > View the source code or report issues on Github: > > `cyborginc/cyborgdb-go` ## Contributing We welcome contributions to all our SDKs! Here's how you can help: * **Report Issues**: Found a bug? Let us know by opening an issue on the relevant repository * **Request Features**: Have an idea for improvement? We'd love to hear it * **Submit PRs**: Ready to contribute code? Check out our contribution guidelines in each repository * **Improve Documentation**: Help us make the docs better by suggesting improvements # Quickstart Source: https://docs.cyborg.co/versions/latest/intro/quickstart ## Try CyborgDB in 5 minutes Run this end-to-end — install, create an encrypted index, upsert, and query — with no server to run. CyborgDB needs Python 3.10 or newer. The `python3` that ships with macOS is 3.9, so check `python3 --version` before installing. ```bash theme={null} pip install cyborgdb-core ``` ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb import secrets # Local disk backing store — no server required. client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb-quickstart")) # Generate an encryption key for the index. # WARNING: store this key securely — data encrypted with a lost key is unrecoverable. index_key = secrets.token_bytes(32) # Create an encrypted index. index = client.create_index(index_name="my_index", index_key=index_key) # Upsert some items (index_key is required on every data operation). items = [ {"id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Hello!"}, {"id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "contents": "Bonjour!"}, {"id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12], "contents": "Hola!"}, ] index.upsert(items, index_key=index_key) # Query the encrypted index — request distance and metadata. results = index.query( query_vectors=[0.1, 0.2, 0.3, 0.4], top_k=2, include=["distance", "metadata"], index_key=index_key, ) # Contents live in separately encrypted item records — retrieve them with get(). top_items = index.get([r["id"] for r in results], index_key=index_key) by_id = {item["id"]: item for item in top_items} for r in results: contents = by_id[r["id"]]["contents"].decode() print(f"ID: {r['id']} Distance: {r['distance']:.4f} Contents: {contents}") # Delete the index so the example can be run again (the key above is not saved). index.delete_index(index_key=index_key) ``` > [!WARNING] > > **Store `index_key` before you upsert any data.** CyborgDB has no key-recovery path — losing the key means losing the data. For anything past evaluation, keep the key in AWS Secrets Manager, Vault, or your KMS. See [Managing Keys](../embedded/guides/advanced/managing-keys). > [!NOTE] > > Without an API key the client runs in free-tier mode, capped at 1,000,000 items per index. Pass a key from the [CyborgDB Admin Dashboard](https://cyborgdb.co/new) as the first argument (`cyborgdb.Client(api_key, storage_config=...)`) to lift the cap. See [Get an API Key](./get-api-key). *** ## Deploying for real? Use the Service. Embedded is the fastest path to a first query; the Service is what you deploy. It's a self-hosted REST API with client SDKs for Python, JavaScript, Go, and REST. > [card] [Service Quickstart (Docker)](../service/guides/intro/quickstart-docker) > > Spin up the REST service in one `docker run` and reach a first query. > [card] [Service Quickstart (Python)](../service/guides/intro/quickstart-python) > > Same REST service via `pip install cyborgdb-service`. *** ## Migrating from another vector database Already on Pinecone, Qdrant, Weaviate, ChromaDB, or Milvus? Bring your workload over with **CyborgDB Migrate** — an interactive TUI wizard (or headless TOML config) that resumes on interrupt and preserves IDs and metadata. > [card] [CyborgDB Migrate](./migrate) > > ```bash theme={null} > pip install "cyborgdb-migrate[pinecone]" # or [qdrant], [weaviate], [chromadb], [milvus] > cyborgdb-migrate > ``` *** ## Framework integrations > [card] [LangChain Integration](../integrations/langchain/introduction) > > Drop-in replacement for existing vector stores: > > ```python theme={null} > from cyborgdb_core import StorageConfig > from cyborgdb_core.integrations.langchain import CyborgVectorStore > > store = CyborgVectorStore.from_texts( > texts=["hello world", "goodbye world"], > embedding="all-MiniLM-L6-v2", > index_key=CyborgVectorStore.generate_key(), # keep this key — a lost key means lost data > api_key="", # free tier > storage_config=StorageConfig.disk("/tmp/cyborgdb-langchain"), > ) > ``` > [card] [More Integrations Coming](../integrations/about) > > LlamaIndex, Haystack, Semantic Kernel, and custom frameworks. > [Request an integration →](https://www.cyborg.co/contact) *** ## Next steps > [card] [Learn the Concepts](./about) > > How CyborgDB enables confidential vector search. > [card] [Choose a Backing Store](./backing-stores) > > Local disk (default) or S3 — pick per environment. > [card] [Deployment Models](./deployment-models) > > Embedded vs. Service, and when to pick each for production. # Security Overview Source: https://docs.cyborg.co/versions/latest/intro/security-overview CyborgDB is designed to address one of the most urgent and overlooked risks in enterprise AI: **centralized AI data becoming a single, high-value breach target**. As enterprises adopt AI applications—especially those using Retrieval-Augmented Generation (RAG) and other data-intensive approaches—they centralize data from multiple systems (Finance, HR, CRM, Email, Documents) into a single vector database. While this boosts AI performance, it also creates a **single point of failure** with unprecedented blast radius potential. > [!TIP] > > A well-scoped threat model is essential to evaluate whether CyborgDB's security properties align with your risk profile. This page should be read alongside the detailed [Encryption](./encryption) and [Threat Model](./threat-model) sections. ## 1. The Centralized Intelligence Risk Before AI adoption, sensitive enterprise data was naturally segmented across multiple systems, each with independent security perimeters. AI fundamentally changes this landscape by requiring data centralization for optimal performance. ![Diagram showing the blast radius of a breach in a centralized vector database](https://mintcdn.com/cyborg/kXyFWu9saA_TjOzS/images/vector-db-blast-radius.png?fit=max\&auto=format\&n=kXyFWu9saA_TjOzS\&q=85\&s=cdbd01992fa77b3ba61752a09ca94728) This architectural shift creates a **concentration risk**: instead of requiring separate breaches of multiple systems, attackers need only compromise one vector database to access intelligence from across the entire organization. ### Vector Database Vulnerability Profile Standard vector databases exacerbate this risk through fundamental design choices: > [card] Plaintext Storage > > Embeddings stored without encryption, immediately exploitable upon access > [card] Dense Information > > Each vector encodes rich semantic content from source documents > [card] ML-Optimized Format > > Vector format specifically vulnerable to machine learning exploitation ## 2. Attack Mechanics When attackers compromise a traditional vector database, they can execute a systematic intelligence extraction process: ```mermaid theme={null} graph LR A(Database Access) --> B(Plaintext Extraction) B --> C(Inversion Models) C --> D(Content Reconstruction) D --> E(Cross-System Correlation) E --> F(Complete Intelligence Profile) ``` **Attack timeline on standard vector DB:** 1. **Initial access** (minutes): Exploit application vulnerabilities or cloud misconfigurations 2. **Data extraction** (minutes): Download plaintext embeddings and metadata 3. **Inversion setup** (hours): Deploy transformer models or gradient optimization 4. **Content recovery** (hours to days): Reconstruct original documents with 80-99% fidelity 5. **Intelligence synthesis** (days): Correlate recovered data across enterprise systems > [!WARNING] > > Cyborg [demonstrated this complete attack chain](./threat-model#4-attack-demonstration) at the Confidential Computing Summit (June 2025), achieving 99.38% content reconstruction in under 5 minutes on a production-like database. ### Amplified Impact Vector database breaches differ qualitatively from traditional data breaches: | Traditional DB Breach | Vector DB Breach | Impact Multiplier | | - | - | - | | Single application data | Multi-system intelligence | **10-100x** | | Structured data theft | Semantic relationship exposure | **Qualitative difference** | | Point-in-time snapshot | Historical relationship mapping | **Temporal amplification** | ## 3. CyborgDB Security Architecture CyborgDB disrupts the attack chain through a **defense-in-depth** approach that renders vector database breaches non-exploitable. ```mermaid theme={null} graph TD A[CyborgDB Core Principles] --> B[Zero Plaintext Exposure] A --> C[Forward Privacy] A --> D[Key Isolation] B --> F[In-Use Encryption] B --> G[End-to-End Protection] C --> H[Query Unlinkability] C --> I[Insertion Privacy] D --> J[Customer Key Control] D --> K[AWS KMS Integration] ``` This security is achieved through several key mechanisms: * **In-use encryption**: Embeddings remain encrypted during computation, except the candidates being scored * **Query unlinkability**: Current searches cannot be correlated with historical patterns * **Insertion obfuscation**: New data additions reveal no information about existing content * **Temporal isolation**: Past compromises do not affect future security * **Customer key control**: Encryption keys remain under customer management * **No plaintext key storage**: CyborgDB never persists decryption keys in plaintext > [!TIP] > > To learn more about how CyborgDB implements these protections, read the [Encryption guide](./encryption). ## 4. Security Guarantees CyborgDB provides mathematically provable protections against the threat scenarios in the [threat model](./threat-model). | Attack Vector | Standard Vector DB | CyborgDB Protection | Security Guarantee | | - | - | - | - | | **Embedding extraction** | ❌ Immediate plaintext access | ✅ AES-256-GCM encrypted storage | Computational security (2^256 operations) | | **Memory scraping** | ❌ Plaintext in RAM | ✅ In-use encryption | Semantic security preservation | | **Inversion attacks** | ❌ Direct ML exploitation | ✅ Ciphertext-only exposure | Computational security | | **Query correlation** | ❌ Full access pattern visibility | ✅ Forward-private indexing | Unlinkability guarantee | | **Cross-system linking** | ❌ Trivial metadata correlation | ✅ Per-record IVs | Computational indistinguishability | ## 5. Getting Started CyborgDB makes securing your AI database as straightforward as deploying it: **1. Risk Assessment** Evaluate your current vector database security posture and compliance requirements **2. Try CyborgDB** [Get started in 5 minutes](./quickstart) to evaluate security and performance **3. Launch to Production** Migrate production workloads with full cryptographic protection By protecting data across its full lifecycle and designing for zero-plaintext exposure, CyborgDB ensures that you can innovate with AI without creating a breach magnet for your organization's most valuable intelligence. ## 6. Further Reading > [card] [Threat Model](./threat-model) > > Detailed adversary analysis and attack scenarios > [card] [Embedding Inversion](./embedding-inversion) > > How attackers reconstruct text from embeddings > [card] [Encryption](./encryption) > > Technical implementation of cryptographic protections # Threat Model Source: https://docs.cyborg.co/versions/latest/intro/threat-model CyborgDB's threat model defines the types of adversaries assumed, the attacks protected against, and the attacks explicitly not addressed. It guides the design of our encryption, key management, and system architecture. > [!TIP] > > A well-scoped threat model is essential to evaluate whether CyborgDB's security properties align with your risk profile. This page should be read alongside the [Encryption](./encryption) section. ## 1. Adversary Model The threat model assume adversaries can be: > [card] External Network Adversary > > Can intercept, modify, or replay traffic between client and server. > [card] Server-Side Adversary > > Has full read access to server memory, storage, and code execution environment. > [card] Insider Threat > > A privileged operator or cloud provider administrator with direct infrastructure access. > [card] Passive Data Analyst > > Can analyze access patterns, ciphertexts, and index structures over time. CyborgDB do **not** assume the client endpoint is compromised (see [Out of Scope](#6-out-of-scope)), nor does it defend against malicious users with valid credentials performing authorized actions. ## 2. Attack Surfaces Vector databases present a uniquely dangerous attack surface because they **centralize semantic intelligence** from across an organization's entire data ecosystem. Unlike traditional databases that contain data from a single application, vector databases aggregate embeddings from CRM systems, HR databases, financial records, email communications, and document repositories. Standard vector databases compound this risk by storing & using embeddings in **plaintext format**, making them immediately exploitable upon breach. Once an attacker gains access, they can directly extract dense vector representations and apply machine learning techniques to reconstruct the original sensitive content with high fidelity. This combination of centralized intelligence and plaintext storage transforms what should be isolated system breaches into organization-wide intelligence compromises. The following attack surfaces become particularly critical in this context: **1. Data at Rest** * Disk-level theft of database files * Cloud snapshot compromise * Backup leakage **2. Data in Transit** * Man-in-the-middle interception * Traffic replay or modification **3. Data in Use** * Memory scraping from compromised server * Runtime introspection of index structures * Retrieval of embeddings or keys from process space **4. Index & Query Metadata** * Frequency analysis of search tokens * Correlation between inserted embeddings and prior queries * Leakage via predictable index structures ## 3. Adversary Capabilities | Capability | Example Sources | | - | - | | **Full disk access** | Stolen storage volume, cloud snapshot | | **Full memory access** | Compromised hypervisor, malicious kernel module | | **Network interception** | BGP hijack, malicious ISP | | **Log & telemetry access** | Misconfigured logging, compromised SIEM | | **Code execution on server** | Supply chain attack, RCE in application stack | The **Server-Side Adversary** case — full memory, disk, and runtime access — is the primary driver for CyborgDB's *in-use encryption* and *forward-secure index* design. ## 4. Attack Demonstration Cyborg demonstrated the severity of vector database vulnerabilities at the Confidential Computing Summit (June 2025): * **Target**: Production-like vector DB with synthetic sensitive data (e.g., social security numbers, medical info) * **Attack time**: \< 5 minutes from access to sensitive data recovery * **Recovery rate**: 99.38% successful reconstruction of original documents [YouTube video player](https://www.youtube.com/embed/TK2L3P3k-EM?si=Xj_fKUo_gwtWHkjL\&start=270) For a deep dive on how embedding inversion works, the specific attack vectors, and comparative results across vector databases, see [Embedding Inversion](./embedding-inversion). ### Attack Flow ```mermaid theme={null} graph TD A(Database Breach) --> B(Embedding Extraction) B --> C{Inversion Attack} C --> D1[Gradient Optimization] C --> D2[Transformer Models] C --> D3[Custom ML Techniques] D1 --> E(Original Content Recovered) D2 --> E D3 --> E ``` ## 5. Mitigation Mapping The table below maps specific adversary actions to CyborgDB controls: | Attack Vector | Mitigation | Residual Risk | | - | - | - | | **Disk theft** | AES-256-GCM encryption at rest | Key theft from KMS would bypass | | **Memory scraping** | In-use encryption with ephemeral node keys | An attacker with live memory access can read keys in use and the entries being scored | | **Index structure analysis** | Forward privacy & per-insertion randomization | Search pattern leakage still possible within active session | | **Embedding inversion** | Embeddings never stored in plaintext | Compromised client or live process memory could still expose | | **Network interception** | TLS + AEAD | Endpoint compromise would still allow decryption | | **Query correlation** | Forward-secure cryptographic counters | Statistical attacks on *large* query volumes | | **Cross-system linking** | Per-record key derivation with unique IVs | Metadata correlation if encryption keys compromised | > [!NOTE] > > These controls assume standard cryptographic primitives — AES-256, SHA-3, HMAC — remain unbroken and that all encryption keys remain secret. If either assumption fails, the corresponding protections may no longer hold. ### Control Points in the Attack Chain ```mermaid theme={null} flowchart LR A[Adversary] -->|Exploit network| B[Intercept traffic] A -->|Steal disk snapshot| C[Access ciphertext at rest] A -->|Compromise server| D[Access memory & runtime] A -->|Analyze index| E[Pattern & correlation attacks] subgraph "CyborgDB Controls" F[TLS + AEAD] --> B G[AES-256-GCM] --> C H[In-use Encryption] --> D I[Forward Privacy] --> E J[Per-insertion Randomization] --> E end B --> K[Attack Blocked] C --> K D --> K E --> K ``` > [!TIP] > > To learn more about how CyborgDB implements these protections, read our [Encryption guide](./encryption). ## 6. Out of Scope CyborgDB **does not** protect against: * **Client endpoint compromise**: If the user's device is compromised, plaintext data may be exposed during normal operation * **Authorized insider misuse**: Valid users performing authorized but malicious actions within their permissions * **Social engineering**: Attacks targeting users to reveal credentials or perform unauthorized actions * **Physical access to client devices**: Direct access to unlocked client machines * **Key escrow attacks**: Government or legal compulsion to provide decryption keys (mitigated by BYOK) > [!WARNING] > > Organizations should implement complementary controls (endpoint protection, user training, access controls) to address these out-of-scope threat vectors. # Using the Docs Source: https://docs.cyborg.co/versions/latest/intro/using-docs This guide will help you navigate CyborgDB's documentation effectively and find the information you need quickly. ## Documentation Structure Our documentation is organized into four main sections: > [card] [Introduction](./about) > > *Core concepts and getting started* > > * Architecture and key concepts > * Deployment models (Service vs Embedded) > * Database integration options > * Quickstart guides > [card] [CyborgDB Service](../service/guides/intro) > > *Self-deployed REST API service* > > * REST API documentation > * Client SDKs (Python, JS/TS, Go) > * Docker and Python deployment > * Authentication and configuration > [card] [CyborgDB Embedded](../embedded/guides/intro) > > *Direct library integration* > > * Python library > * Installation and setup guides > * Performance tuning > * Advanced configuration > [card] [Integrations](../integrations/about) > > *Framework integrations* > > * LangChain integration > * Framework-specific guides > * Custom integrations *** ## Navigation Tips > [card] Quick Access > > * **Search** (Ctrl/Cmd + K) - Find topics instantly > * **Table of Contents** - Navigate within articles > * **Breadcrumbs** - Track your location > [card] Page Types > > * **Quickstart Guides** - Step-by-step tutorials > * **Conceptual Guides** - How things work > * **Reference Docs** - Complete API documentation > * **How-to Guides** - Practical solutions > [card] Code Examples > > * **Multiple Languages** - Python, JavaScript, TypeScript, Go > * **Copy Button** - One-click code copying > * **Runnable Examples** - Complete working code *** ## Conventions Used ### Code and Commands ```bash theme={null} # Terminal commands are shown in code blocks like this pip install cyborgdb-core ``` ```python theme={null} # Python code examples use syntax highlighting from cyborgdb_core import Client, StorageConfig client = Client(api_key="your-key", storage_config=StorageConfig.disk("/tmp/cyborgdb")) ``` ### Information Callouts > [!NOTE] > > **Notes** provide helpful context and additional information that's good to know. > [!TIP] > > **Tips** share best practices and insider knowledge to help you succeed. > [!WARNING] > > **Warnings** highlight important considerations that could affect your implementation. *** ## Finding What You Need > [tab] I'm new to CyborgDB > > **First time learning about confidential vector search** > > → Start with [About CyborgDB](./about) then try the [Quickstart Guide](./quickstart) > > Get oriented with core concepts and architecture before diving into implementation. > [tab] I want to get started quickly > > **Need something working fast** > > → Jump to the [Quickstart Guide](./quickstart) and choose your deployment path > > Follow step-by-step guides to get your first confidential vector search running. > [tab] I need specific information > > **Looking for API methods or configuration details** > > → Use search (Ctrl/Cmd + K) or browse the reference docs for your deployment model > > Find exact method signatures, parameters, and configuration options. > [tab] I'm migrating from another database > > **Moving from existing vector database** > > → Use the [migration guide](./migrate) to move your data with `cyborgdb-migrate` > > It supports Pinecone, Qdrant, Weaviate, ChromaDB, and Milvus as sources. ### Search Tips * **Exact phrases**: Use quotes for exact matches: `"create index"` * **Multiple terms**: Search for multiple concepts: `python authentication` * **Method names**: Search for specific functions: `similarity_search` *** ## Code Examples ### Language Tabs Many code examples include multiple language options: ```python Python theme={null} from cyborgdb_core import Client, StorageConfig client = Client(api_key="your-key", storage_config=StorageConfig.disk("/tmp/cyborgdb")) ``` ```javascript JavaScript theme={null} import { Client } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-key' }); ``` ### Runnable Examples Look for complete, runnable examples that you can copy and execute directly: ```python theme={null} # Complete working example import secrets from cyborgdb_core import Client, StorageConfig client = Client(storage_config=StorageConfig.disk("/tmp/cyborgdb-example")) # Create an index (store this key securely; it is required on every call) index_key = secrets.token_bytes(32) index = client.create_index(index_name="my-index", index_key=index_key, dimension=4) # Upsert vectors with metadata index.upsert( [{"id": "doc1", "vector": [0.1, 0.2, 0.3, 0.4], "metadata": {"doc": "example"}}], index_key=index_key, ) # Search for similar vectors results = index.query(query_vectors=[0.1, 0.2, 0.3, 0.4], top_k=5, index_key=index_key) print(results) ``` *** ## Getting Help > [card] [Contact Support](https://www.cyborg.co/contact) > > *General inquiries and enterprise support* > > Visit our contact page for sales, partnerships, and enterprise support requests > [card] [Email Support](mailto:help@cyborg.co) > > *Direct technical support* > > Email us directly at [help@cyborg.co](mailto:help@cyborg.co) for technical questions and support > [card] [Priority Support](https://cyborgdb.co/new) > > *Get faster support when logged in* > > Log into the CyborgDB dashboard for priority support and account-specific help # Configure an Encrypted Index Source: https://docs.cyborg.co/versions/latest/service/guides/advanced/configure-index > [!NOTE] > > CyborgDB Service uses a single IVF index type; there are no separate `IVFFlat`, `IVFPQ`, or `IVFSQ` types and no `index_config` argument. Configuration is expressed as flat parameters on `create_index`. CyborgDB Service stores every encrypted index as an inverted-file (IVF) index whose data is persisted by the service's configured storage backend (`disk` or `s3`). The four knobs you control at create time are: | Parameter | Default | What it controls | | - | - | - | | `dimension` | auto-detect | Vector dimensionality. If you omit it, the server fixes the dimension to whatever shape the **first upsert** uses. | | `metric` | `euclidean` | Distance function used for similarity search. Accepts `euclidean`, `squared_euclidean`, or `cosine`. | | `embedding_model` | unset | Optional built-in embedding model name. When set, the service generates embeddings server-side from `contents` on upsert/query; `dimension` is inferred from the model. | | `storage_precision` | `float32` | On-disk rerank-vector dtype. `float32` is highest recall; `float16` halves on-disk storage at the cost of small recall loss; the TurboQuant tiers `tq12`/`tq8`/`tq6`/`tq4` compress further (12, 8, 6, or 4 bits per component). | Two more parameters control key management — they are mutually exclusive, and exactly one must be supplied: | Parameter | When to use it | | - | - | | `index_key` | SDK-supplied KEK path. You generate and persist a 32-byte key locally; the service records the index as `provider: none`. The same key must be supplied again when you load the index (and on every REST call). | | `kms_name` | KMS-backed path. References a named entry in the service YAML's `kms.registry` (e.g. `aws-kms` or `aws`). The service generates the KEK, wraps it via the named provider, and persists the envelope. The SDK never sees the plaintext key. | See [KMS & BYOK](./kms-byok) for the registry schema and [Managing Encryption Keys](./managing-keys) for the SDK-supplied path. ## Distance metric ```python Python SDK icon="python" theme={null} from cyborgdb import Client client = Client(base_url='http://localhost:8000', api_key='your-api-key') index_key = client.generate_key() index = client.create_index( 'documents', index_key=index_key, dimension=384, metric='cosine', ) ``` ```typescript TypeScript SDK icon="code" theme={null} import { Client } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); const indexKey = client.generateKey(); const index = await client.createIndex({ indexName: 'documents', indexKey, dimension: 384, metric: 'cosine', }); ``` ```go Go SDK icon="golang" theme={null} import "github.com/cyborginc/cyborgdb-go" client, _ := cyborgdb.NewClient("http://localhost:8000", "your-api-key") indexKey, _ := cyborgdb.GenerateKey() dimension := int32(384) metric := "cosine" params := &cyborgdb.CreateIndexParams{ IndexName: "documents", IndexKey: indexKey, Dimension: &dimension, Metric: &metric, } index, _ := client.CreateIndex(context.Background(), params) ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "documents", "index_key": "your_64_character_hex_key_here", "dimension": 384, "metric": "cosine" }' ``` Supported values: * `euclidean` — L2 distance. Default if omitted. * `squared_euclidean` — L2 without the square root; faster, ordering identical to `euclidean`. * `cosine` — cosine distance. Use with normalized vectors. ## `storage_precision`: from float32 to TurboQuant `storage_precision` selects the dtype used for the on-disk rerank vectors. Reranking happens after IVF candidate retrieval to recover recall; storing rerank vectors at lower precision shrinks the on-disk footprint with a small recall trade-off. | Value | On-disk size | Recall | When to use | | - | - | - | - | | `float32` (default) | 4 bytes / element | Highest | Most workloads, especially small/medium indexes | | `float16` | 2 bytes / element | Small recall loss | Large indexes where disk footprint matters more than the last 1–2% of recall | | `tq12` / `tq8` / `tq6` / `tq4` | 12 / 8 / 6 / 4 bits / element | Decreases with tier | TurboQuant tiers for maximum compression — `tq4` is the most aggressive (\~8x smaller than `float32`, \~94% recall\@100). All tiers work with every metric. | ```python Python SDK icon="python" theme={null} # 50% smaller on-disk footprint index = client.create_index( 'compact_documents', index_key=index_key, dimension=768, storage_precision='float16', ) ``` ```typescript TypeScript SDK icon="code" theme={null} const index = await client.createIndex({ indexName: 'compact_documents', indexKey, dimension: 768, storagePrecision: 'float16', }); ``` ```go Go SDK icon="golang" theme={null} dimension := int32(768) precision := cyborgdb.StoragePrecisionFloat16 params := &cyborgdb.CreateIndexParams{ IndexName: "compact_documents", IndexKey: indexKey, Dimension: &dimension, StoragePrecision: &precision, } index, _ := client.CreateIndex(context.Background(), params) ``` ## Automatic embeddings (`embedding_model`) Pass a supported embedding model name and the server will embed text `contents` server-side on upsert and query. When `embedding_model` is set, `dimension` is inferred from the model and can be omitted. ```python Python SDK icon="python" theme={null} index = client.create_index( 'semantic_documents', index_key=index_key, embedding_model='all-MiniLM-L6-v2', ) ``` ```typescript TypeScript SDK icon="code" theme={null} const index = await client.createIndex({ indexName: 'semantic_documents', indexKey, embeddingModel: 'all-MiniLM-L6-v2', }); ``` ```go Go SDK icon="golang" theme={null} embeddingModel := "all-MiniLM-L6-v2" params := &cyborgdb.CreateIndexParams{ IndexName: "semantic_documents", IndexKey: indexKey, EmbeddingModel: &embeddingModel, } index, _ := client.CreateIndex(context.Background(), params) ``` > [!TIP] > > Embedding models are built into the service — no extra packages are required. List the supported models and their dimensions with [`GET /v1/embedding-models`](../../rest-api/client/list-embedding-models). ## Training the index The index needs to be trained once it has enough vectors. By default, the service trains it automatically once it holds more than 65,536 vectors and retrains it as it grows (see [How automatic training works](./train-index#how-automatic-training-works)) — most callers do not need to call `train()` explicitly. See [Train an Encrypted Index](./train-index) for the manual-training path and the tuning knobs (`n_lists`, `batch_size`, `max_iters`, `tolerance`, `max_memory`). ## API reference > [card] [REST API Reference](../../rest-api/client/create-index) > > `POST /v1/indexes/create` > [card] [Python SDK Reference](../../python-sdk/client/create-index) > > `Client.create_index()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/client/create-index) > > `Client.createIndex()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/client/create-index) > > `Client.CreateIndex()` in Go # Environment Variables Source: https://docs.cyborg.co/versions/latest/service/guides/advanced/env-vars CyborgDB Service is configured through environment variables (or an optional [YAML config file](#yaml-configuration-file)). Every value below is settable in both places; environment variables override the file on conflict. > [!NOTE] > > **Storage surface.** The service exposes a single, flat storage > surface: `disk` or `s3` (AWS S3 or any S3-compatible > store). Configure it with `CYBORGDB_DB_TYPE` plus the matching > `CYBORGDB_DISK_PATH` / `CYBORGDB_S3_*` variables. ## API Key and Tiers | Variable | Description | Example | | - | - | - | | `CYBORGDB_API_KEY` | *(Optional)* Your CyborgDB license key, forwarded to the core engine. If unset, the service runs in **free tier** mode (per-index cap of 1,000,000 items). Set a paid key for unlimited usage. This is **not** a service-authentication credential — it does not gate access to the REST API. | `cyborg_abc123...` | > [!NOTE] > > **Free tier vs paid.** `CYBORGDB_API_KEY` is the single switch between the two: > > * **Unset** → free tier. cyborgdb-core enforces a 1M-item-per-index cap. At startup the service logs `CYBORGDB_API_KEY not set — the service will run in free tier`. For evaluation only. > * **Set to a paid key** (from the [CyborgDB dashboard](https://cyborgdb.co/new)) → unlimited items, full feature set. > * **Set to a demo key** (from `cyborgdb.get_demo_api_key()` / `getDemoApiKey()` / `cyborgdb.GetDemoAPIKey(...)`) → also free tier, time-limited. Useful for evaluating without dashboard signup. > > This key controls licensing only. Request authentication is a separate concern, gated by `CYBORGDB_SERVICE_ROOT_KEY` (see [RBAC / Multi-Tenancy](#rbac-multi-tenancy)). > [!WARNING] > > Storage configuration is optional — `disk` is used by default. ## RBAC / Multi-Tenancy `CYBORGDB_SERVICE_ROOT_KEY` is the single source of truth for request authentication. Leave it unset (the default) and authentication is disabled — every request is accepted, and the service logs a startup warning to that effect. Set it and authentication turns on: routes then accept only the root key or a per-user `cdbk_…` token minted under it, sent in the `X-API-Key` header. | Variable | Description | Default | | - | - | - | | `CYBORGDB_SERVICE_ROOT_KEY` | When set, enables authentication and RBAC. The holder of this key has full admin access and can mint per-user API keys via `POST /v1/indexes/{index_name}/users`. Per-user keys are scoped to one index with `read` / `write` permissions enforced cryptographically. When unset, authentication is disabled. | unset (auth off) | | `INDEX_KEK_CACHE_TTL_SECONDS` | TTL for plaintext index KEKs in the service-side cache. Shorter = faster KMS revocation propagation; longer = fewer KMS calls. | `60` | See the [Multi-Tenancy guide](./multi-tenancy) for the full operator playbook (key kinds, provisioning users, SDK-supplied indexes, revocation). ## Embedding Model Cache Text `embedding_model` indexes resolve and download their model on first use. These variables control where the model is cached and whether a cache miss is allowed to reach the model hub. | Variable | Description | Default | | - | - | - | | `CYBORGDB_EMBED_CACHE` | Directory where downloaded embedding models are cached. Mount this on persistent storage so models survive container restarts. | `/app/cyborgdb_data/embed-cache` in Docker; otherwise the embedding backend's default cache location | | `CYBORGDB_EMBED_OFFLINE` | When set to `1`, the service never calls out to the model hub. A cache miss fails the request instead of downloading. Set this on air-gapped deployments after pre-populating `CYBORGDB_EMBED_CACHE`. | unset (downloads allowed) | When a model is unavailable — the hub is unreachable, or `CYBORGDB_EMBED_OFFLINE=1` and the model is not in the cache — upsert and query calls that embed `contents`/`query_contents` return HTTP `503` with a `Retry-After: 30` header. Calls on pre-computed vectors are unaffected. ```bash theme={null} # Air-gapped: pre-populate the cache, then forbid downloads export CYBORGDB_EMBED_CACHE=/var/lib/cyborgdb/embed-cache export CYBORGDB_EMBED_OFFLINE=1 ``` List the models the service currently supports with [`GET /v1/embedding-models`](../../rest-api/client/list-embedding-models). ## Storage Backend Pick either `disk` or `s3`. If `CYBORGDB_DB_TYPE` is unset, the service defaults to `disk`. | Variable | Description | Default | Example | | - | - | - | - | | `CYBORGDB_DB_TYPE` | Storage backend: `disk` or `s3` | `disk` | `s3` | ### Disk (default) Persistent local key-value storage with no external dependency. | Variable | Description | Default | | - | - | - | | `CYBORGDB_DISK_PATH` | Data directory for the disk store | `~/.cyborgdb/data` (local) / `/app/cyborgdb_data` (Docker) | ```bash theme={null} export CYBORGDB_DB_TYPE=disk export CYBORGDB_DISK_PATH=/var/lib/cyborgdb # optional ``` ### S3 AWS S3 or any S3-compatible store (MinIO, Cloudflare R2, …). | Variable | Description | Required for S3 | | - | - | - | | `CYBORGDB_S3_BUCKET` | Bucket name | ✅ | | `CYBORGDB_S3_REGION` | Bucket region | Optional (defaults to `us-east-1`) | | `CYBORGDB_S3_PREFIX` | Key prefix for stored objects | Optional | | `CYBORGDB_S3_ENDPOINT` | Custom endpoint URL (MinIO, R2, …) | Required for non-AWS endpoints | | `CYBORGDB_S3_ACCESS_KEY` | S3 access key ID | Required with `CYBORGDB_S3_ENDPOINT` | | `CYBORGDB_S3_SECRET_KEY` | S3 secret access key | Required with `CYBORGDB_S3_ENDPOINT` | | `CYBORGDB_S3_SESSION_TOKEN` | Optional temporary session token | Optional | #### S3 credential resolution The S3 client resolves credentials independently of any KMS client: * **On AWS (EC2 / ECS / EKS), real S3.** Leave all `CYBORGDB_S3_*` credential variables unset. The AWS default credential provider chain picks up the instance/task role. * **Off AWS, real S3.** Provide `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (or a mounted AWS profile). The default chain picks them up. * **S3-compatible endpoint (MinIO, R2, …).** Set `CYBORGDB_S3_ENDPOINT` **plus** explicit `CYBORGDB_S3_ACCESS_KEY` / `CYBORGDB_S3_SECRET_KEY`. A custom endpoint is not AWS — the AWS chain is never used against it, and startup fails fast if the explicit keys are missing. The `CYBORGDB_S3_*` namespace is deliberately separate from `AWS_*` so storage credentials cannot collide with KMS credentials. ```bash theme={null} # AWS S3 with instance role export CYBORGDB_DB_TYPE=s3 export CYBORGDB_S3_BUCKET=my-bucket export CYBORGDB_S3_REGION=us-east-1 # MinIO export CYBORGDB_DB_TYPE=s3 export CYBORGDB_S3_BUCKET=my-bucket export CYBORGDB_S3_ENDPOINT=https://minio.internal:9000 export CYBORGDB_S3_ACCESS_KEY=minioadmin export CYBORGDB_S3_SECRET_KEY=minioadmin ``` ## Optional Environment Variables > [accordion] Service Configuration > > | Variable | Description | Default | > | - | - | - | > | `PORT` | HTTP port for the service | `8000` | > | `CYBORGDB_SERVICE_LOG_LEVEL` | Log level (`DEBUG`, `INFO`, `WARNING`, `ERROR`) | `INFO` | > > > [!WARNING] > > > > Request authentication is controlled solely by `CYBORGDB_SERVICE_ROOT_KEY` (see [RBAC / Multi-Tenancy](#rbac-multi-tenancy)). When it is unset, authentication is disabled and every request is accepted — the service logs a startup warning. When it is set, clients must send the root key or a `cdbk_` user token in the `X-API-Key` header, or the request is rejected with 401. This is independent of the free-tier / paid-tier distinction, which is gated only by `CYBORGDB_API_KEY`. > [accordion] TLS / HTTPS > > | Variable | Description | Default | > | - | - | - | > | `SSL_CERT_PATH` | Path to TLS certificate | unset (HTTP) | > | `SSL_KEY_PATH` | Path to TLS private key | unset (HTTP) | > > > [!NOTE] > > > > HTTPS is enabled automatically when both `SSL_CERT_PATH` and `SSL_KEY_PATH` are set and both files exist. Otherwise the service starts on HTTP. > [accordion] Per-keystore RAM cache > > Applied to every newly created index. `cyborgdb-core` caches > nothing by default; opt in here per keystore. > > | Variable | Description | Default | > | - | - | - | > | `CACHE_POLICY_VECTORS` | Cache vector payloads in RAM | `false` | > | `CACHE_POLICY_METADATA` | Cache metadata in RAM | `false` | > | `CACHE_POLICY_IDS` | Cache item IDs in RAM | `false` | > [accordion] Performance > > | Variable | Description | Default | > | - | - | - | > | `CPU_THREADS` | Worker threads. `0` = auto-detect | `0` | > | `GPU_OPERATIONS` | GPU-accelerated ops: `none`, `upsert`, `train`, `all`, or comma-separated (e.g. `upsert,train`) | `none` | > | `AUTO_TRAIN_MIN_VECTORS` | An untrained index is trained automatically once it holds more than this many vectors. Trained indexes are retrained automatically as they grow; see [How automatic training works](./train-index#how-automatic-training-works). | `65536` | > | `AUTO_TRAIN_DISABLED` | Fully disable post-upsert auto-training and retraining. Explicit `train()` / `POST /v1/indexes/train` still work. Useful for benchmarking a fixed index state or controlling training timing yourself. | `false` | > > > [!NOTE] > > > > GPU-accelerated query is not yet supported by `cyborgdb-core`. Passing `query` in `GPU_OPERATIONS` is silently ignored. > [accordion] Per-index KMS > > Per-index KMS (BYOK) is configured exclusively via the YAML > file's `kms.registry` block — see the > [KMS / BYOK guide](./kms-byok). The related environment > variable is documented above under **RBAC / Multi-Tenancy** (`INDEX_KEK_CACHE_TTL_SECONDS`). ## YAML Configuration File Every setting above is also expressible in a YAML file. The file is resolved in this order (first hit wins): 1. `CYBORGDB_CONFIG_FILE` environment variable 2. `./cyborgdb.yaml`, `./cyborgdb.yml`, `/etc/cyborgdb/cyborgdb.yaml` A missing file is fine — the service falls back to env-only. An explicit `CYBORGDB_CONFIG_FILE` path that doesn't exist is a hard error. ```yaml cyborgdb.yaml theme={null} service: port: 8000 cyborgdb_service_log_level: INFO # Optional: enable RBAC by setting a root API key. See ./multi-tenancy. # cyborgdb_service_root_key: ${CYBORGDB_SERVICE_ROOT_KEY} # Storage backend: disk | s3 (default: disk) cyborgdb_db_type: disk # cyborgdb_disk_path: /var/lib/cyborgdb # S3 settings (when cyborgdb_db_type: s3) # cyborgdb_s3_bucket: my-bucket # cyborgdb_s3_region: us-east-1 # cyborgdb_s3_endpoint: https://minio.internal:9000 # cyborgdb_s3_access_key: ${MINIO_ACCESS_KEY} # cyborgdb_s3_secret_key: ${MINIO_SECRET_KEY} cpu_threads: 0 index_kek_cache_ttl_seconds: 60 kms: registry: # See the KMS / BYOK guide for the full schema. # vendor-default: # provider: aws-kms # key_id: alias/cyborgdb-default # region: us-east-1 ``` **Precedence:** environment variables > `.env` > YAML file. **Env-var substitution.** Any string value in the YAML may reference an environment variable as `${VAR}` (required — startup fails if unset) or `${VAR:-default}` (uses `default` when unset). This lets you keep BYOK role ARNs / account IDs out of the checked-in file. A variable set to the empty string counts as **unset**. ## Configuration Examples > [accordion] Quick start (disk, default) > > ```bash theme={null} > export CYBORGDB_API_KEY="cyborg_your_api_key_here" > cyborgdb-service > # Data goes to ~/.cyborgdb/data > ``` > [accordion] S3 on AWS with instance role > > ```bash theme={null} > export CYBORGDB_API_KEY="cyborg_your_api_key_here" > export CYBORGDB_DB_TYPE=s3 > export CYBORGDB_S3_BUCKET=my-bucket > export CYBORGDB_S3_REGION=us-east-1 > # No explicit credentials — instance role picked up automatically > cyborgdb-service > ``` > [accordion] S3 on MinIO with explicit credentials > > ```bash theme={null} > export CYBORGDB_API_KEY="cyborg_your_api_key_here" > export CYBORGDB_DB_TYPE=s3 > export CYBORGDB_S3_BUCKET=my-bucket > export CYBORGDB_S3_ENDPOINT=https://minio.internal:9000 > export CYBORGDB_S3_ACCESS_KEY=minioadmin > export CYBORGDB_S3_SECRET_KEY=minioadmin > cyborgdb-service > ``` > [accordion] Production with HTTPS > > ```bash theme={null} > export CYBORGDB_API_KEY="cyborg_your_api_key_here" > export CYBORGDB_DB_TYPE=s3 > export CYBORGDB_S3_BUCKET=cyborgdb-prod > export CYBORGDB_S3_REGION=us-east-1 > export PORT=8443 > export SSL_CERT_PATH=/etc/ssl/certs/cyborgdb.crt > export SSL_KEY_PATH=/etc/ssl/private/cyborgdb.key > cyborgdb-service > ``` ### Docker Pass any of the variables above to `docker run` with `-e`: ```bash theme={null} docker run -p 8000:8000 \ -e CYBORGDB_API_KEY="cyborg_your_api_key_here" \ -e CYBORGDB_DB_TYPE=s3 \ -e CYBORGDB_S3_BUCKET=my-bucket \ -e CYBORGDB_S3_REGION=us-east-1 \ cyborginc/cyborgdb-service:latest ``` Or use an `--env-file`: ```bash theme={null} docker run -p 8000:8000 --env-file .env cyborginc/cyborgdb-service:latest ``` ## Troubleshooting > [accordion] Missing API key > > Set `CYBORGDB_API_KEY`. Check for typos. Keys start with > `cyborg_`. > [accordion] `Invalid CYBORGDB_DB_TYPE` > > CyborgDB accepts `disk` or `s3`. Set > `CYBORGDB_DISK_PATH` if you use a custom directory for the > disk store. > [accordion] S3 startup fails with missing credentials > > With `CYBORGDB_S3_ENDPOINT` set, the AWS default credential > chain is bypassed entirely. Provide > `CYBORGDB_S3_ACCESS_KEY` and `CYBORGDB_S3_SECRET_KEY` > explicitly. > [accordion] TLS not enabling > > Both `SSL_CERT_PATH` and `SSL_KEY_PATH` must be set **and > both files must exist on disk** before the service starts. > Missing either falls back to HTTP silently. # Per-Index KMS & BYOK Source: https://docs.cyborg.co/versions/latest/service/guides/advanced/kms-byok CyborgDB Service v0.18 supports per-index Key Management Service (KMS) integration: each index can be wrapped by its own operator-managed key, optionally living in a customer's own AWS account (Bring Your Own KMS). The SDK never holds long-term encryption keys for KMS-backed indexes. > [!NOTE] > > This page is service-only. The embedded libraries' KMS story is > covered separately under [Managing Encryption Keys](./managing-keys). > [!WARNING] > > **When KMS-backed, omit `index_key` everywhere.** Migrating an index from the SDK-supplied path to KMS-backed means **removing `index_key` from every call** — `create_index`, `load_index`, `describe_index`, `train`, `upsert`, `query`, `get`, `delete`, `list_ids`, `query_metadata`, `delete_index`, and the user-management calls. The service resolves the KEK server-side from the index's stored key envelope; supplying `index_key` for a KMS-backed index is rejected with HTTP 400. If your code still passes a key, the rejection is loud — but worth a single search-and-clean pass before you ramp. ## AWS access — what the service expects The service uses the **standard AWS credential provider chain** to reach `aws-kms` and `aws` (Secrets Manager) slots. The exact resolution depends on where you run it: | Environment | What you set | What the service uses | | - | - | - | | EC2 / ECS / EKS (same account) | Nothing — attach an IAM role to the instance/task with the required KMS or Secrets Manager permissions | Instance/task role via IMDS | | EC2 / ECS / EKS (cross-account, BYOK) | `role_arn` + `external_id` on the registry slot | Instance/task role → `sts:AssumeRole` into the customer role | | Off-AWS / local | `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (and optionally `AWS_SESSION_TOKEN`) env vars, or `AWS_PROFILE` pointing at `~/.aws/credentials` | Default chain picks them up | | Off-AWS, BYOK | Local credentials *plus* `role_arn` + `external_id` on the slot | Local creds → `sts:AssumeRole` | > [!NOTE] > > The `CYBORGDB_S3_*` storage credentials are deliberately **separate** from `AWS_*` KMS credentials. KMS uses the AWS default chain (or AssumeRole); S3 storage uses its own explicit keys when both `CYBORGDB_S3_ACCESS_KEY` and `CYBORGDB_S3_SECRET_KEY` are set. Set both for a non-AWS storage backend (MinIO, R2, etc.); if either is unset, storage falls back to the same AWS default chain that KMS uses. ### Required IAM permissions (per provider) **`provider: aws-kms`** — on the wrap key: ```json theme={null} { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": ["kms:Encrypt", "kms:Decrypt"], "Resource": "" }] } ``` For same-account setups, these permissions can live on the KMS key's **key policy** (preferred) or on the runtime principal's IAM policy. **`provider: aws`** (Secrets Manager) — on the secret: ```json theme={null} { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "secretsmanager:GetSecretValue", "Resource": "arn:aws:secretsmanager:::secret:-*" }] } ``` Secrets Manager appends 6 random characters to every secret ARN, so either use the secret's full ARN as-is, or the ARN up to the secret name followed by `-*` as shown. ## Model CyborgDB Service uses a two-key hierarchy per index: * **KEK** (Key-Encryption Key, 32 bytes) — per index. Resolved from the named KMS registry slot at index creation, then re-fetched (or unwrapped) on every load. Held in a short-lived in-process cache; the TTL is set by `INDEX_KEK_CACHE_TTL_SECONDS` (default 60 s). * **DEK** (Data-Encryption Key, 32 bytes) — per index. Generated internally at index-creation time, wrapped under the KEK with AES-GCM, and persisted alongside the index. Never leaves the service and is never returned to clients. There are exactly two ways to provision a CyborgDB index: | Mode | `kms_name` | `index_key` | KEK lives in… | SDK behavior | | - | - | - | - | - | | **KMS-backed** | a registry slot | omitted | the KMS provider | SDK omits `index_key` on every call; service resolves the KEK on demand. | | **SDK-supplied** | omitted | 32 bytes from caller | the SDK client only | SDK supplies the same `index_key` on every call. Persisted envelope records `provider: none`. | Supplying both `kms_name` **and** `index_key` is rejected with a 400. Supplying neither is also a 400. ## YAML Registry Per-index KMS slots live in the service YAML file (not environment variables) under `kms.registry`. Each slot is a named entry that `create_index(..., kms_name=)` can reference. ```yaml cyborgdb.yaml theme={null} kms: registry: vendor-default: provider: aws-kms key_id: alias/cyborgdb-default region: us-east-1 customer-acme: provider: aws key_id: customers/acme/kek # Secrets Manager name or ARN region: us-west-2 role_arn: ${ACME_BYOK_ROLE_ARN} # BYOK: customer's AWS role external_id: ${ACME_BYOK_EXTERNAL_ID} role_session_name: cyborgdb-acme # see note below ``` > [!NOTE] > > String values support env-var substitution: `${VAR}` (required, fails on startup if unset) and `${VAR:-default}` (uses the default when unset). Use this to keep BYOK role ARNs and external IDs out of the checked-in file. > [!NOTE] > > `role_session_name` defaults to `cyborgdb-` (with any `alias/` prefix removed). STS rejects session names containing `/` or `:`, so set `role_session_name` explicitly on any BYOK slot whose `key_id` is a path-style name (such as `customers/acme/kek`) or an ARN. ### Provider types The `provider` field selects how the KEK is wrapped: | Provider | Where the wrap key lives | KEK lifecycle | | - | - | - | | `aws-kms` | AWS KMS (HSM-managed) | Service generates a random KEK and calls `kms.Encrypt`. On load, calls `kms.Decrypt`. | | `aws` | AWS Secrets Manager | Service generates a random KEK and AES-GCM-wraps it under the Secrets Manager value. On load, fetches the secret and unwraps locally. | Both providers additionally accept `role_arn` + `external_id` for cross-account access (BYOK) — the service calls `sts:AssumeRole` before reaching the key. There is no registry slot for the SDK-supplied path. Omit `kms_name` entirely from `create_index` and supply `index_key` directly; the persisted envelope records `provider: none`. ### Caching and revocation The service caches plaintext KEKs in memory for `INDEX_KEK_CACHE_TTL_SECONDS` (default 60 s). Only KMS-derived KEKs are cached — the SDK-supplied path always passes through. Shorter TTLs propagate KMS revocations (key deletion, IAM policy detach, trust-policy edit) faster but cost more KMS calls. To force-revoke an index globally, revoke the wrap key in the KMS provider; cached KEKs expire within `INDEX_KEK_CACHE_TTL_SECONDS`. ## Creating a KMS-backed index The SDK call is unchanged except for swapping `index_key=` for `kms_name=`: ```python Python SDK icon="python" theme={null} from cyborgdb import Client client = Client(base_url="http://localhost:8000", api_key="your-api-key") # KMS-backed: service generates and wraps the KEK; SDK never sees it index = client.create_index( "documents", kms_name="vendor-default", dimension=384, metric="cosine", ) # All subsequent calls omit index_key entirely results = index.query(query_vectors=[0.1] * 384, top_k=5) ``` ```typescript JavaScript / TypeScript icon="js" theme={null} import { Client } from "cyborgdb"; const client = new Client({ baseUrl: "http://localhost:8000", apiKey: "your-api-key" }); // KMS-backed: service generates and wraps the KEK; SDK never sees it const index = await client.createIndex({ indexName: "documents", kmsName: "vendor-default", dimension: 384, metric: "cosine", }); // All subsequent calls omit indexKey entirely const results = await index.query({ queryVectors: new Array(384).fill(0.1), topK: 5 }); ``` ```go Go SDK icon="golang" theme={null} import ( "context" "log" "github.com/cyborginc/cyborgdb-go" ) ctx := context.Background() client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } // KMS-backed: service generates and wraps the KEK; SDK never sees it index, err := client.CreateIndex(ctx, &cyborgdb.CreateIndexParams{ IndexName: "documents", KmsName: cyborgdb.String("vendor-default"), Dimension: cyborgdb.Int32(384), Metric: cyborgdb.String("cosine"), }) if err != nil { log.Fatal(err) } // All subsequent calls omit the index key; reopen later with client.LoadIndex(ctx, "documents", nil) queryVector := make([]float32, 384) for i := range queryVector { queryVector[i] = 0.1 } results, err := index.Query(ctx, cyborgdb.QueryParams{QueryVector: queryVector, TopK: 5}) ``` ```bash cURL icon="rectangle-terminal" theme={null} # Create index — note: no index_key, just kms_name curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "documents", "kms_name": "vendor-default", "dimension": 384, "metric": "cosine" }' ``` On every subsequent request for this index — `load_index`, `upsert`, `query`, `delete` — the SDK omits `index_key`. The service looks up the index's persisted envelope, resolves the KEK via the named KMS slot (cache hit, or fresh wrap/unwrap on miss), and uses it to open the index. ## Bring Your Own KMS (cross-account) In BYOK, the wrap key lives in the **customer's** AWS account. CyborgDB Service holds no long-term credentials to that account — access flows through `sts:AssumeRole` with an `ExternalId` on every wrap or unwrap call. Setup is a two-party handshake: **1. Service operator: generate an ExternalId** Treat as a credential — it's the cryptographic gate preventing one customer's role ARN from being abused by another. ```bash theme={null} python3 -c "import uuid; print(uuid.uuid4())" ``` **2. Service operator: share three values with the customer** * The service's AWS principal ARN (the service's AWS identity). Get it with: ```bash theme={null} aws sts get-caller-identity --query 'Arn' --output text ``` * The `ExternalId` you generated. * The customer-facing setup steps (Step 3 below). **3. Customer: create the wrap key and IAM role** **1. Create the wrap key in Secrets Manager** (32 random bytes): ```bash theme={null} aws secretsmanager create-secret \ --name cyborgdb//wrap-key \ --secret-binary fileb://<(head -c 32 /dev/urandom) \ --region ``` > [!WARNING] > > Keep a backup. If this secret is deleted, every index wrapped under it becomes permanently unreadable. **2. Create an IAM role** with this trust policy (substituting the operator-supplied values): ```json theme={null} { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Principal": {"AWS": ""}, "Action": "sts:AssumeRole", "Condition": { "StringEquals": {"sts:ExternalId": ""} } }] } ``` **3. Attach an inline permission policy** for the secret: ```json theme={null} { "Version": "2012-10-17", "Statement": [{ "Effect": "Allow", "Action": "secretsmanager:GetSecretValue", "Resource": "arn:aws:secretsmanager:::secret:cyborgdb//wrap-key-*" }] } ``` Secrets Manager appends 6 random chars to every secret ARN, so either use the secret's full ARN as-is, or the ARN up to the secret name followed by `-*` as shown. Send three values back to the operator: **role ARN**, **secret name**, **region**. Never share AWS credentials. **4. Service operator: add the slot to YAML** Under `kms.registry:`: ```yaml theme={null} customer-acme: provider: aws key_id: region: role_arn: external_id: role_session_name: cyborgdb-acme # appears in customer's CloudTrail; required when key_id contains '/' ``` Then restart the service. On boot, look for: ``` KMS registry loaded (N entries: [..., 'customer-acme', ...]) ``` **5. (Optional) Verify the AssumeRole** From the same shell environment as the service: ```bash theme={null} aws sts assume-role \ --role-arn \ --role-session-name verify \ --external-id \ --query 'Credentials.AccessKeyId' --output text ``` Prints `ASIA...` → trust policy and ExternalId match. `AccessDenied` → the customer's trust policy is wrong; share the error. ### Revocation * **Pause access** — customer detaches the inline permission policy from the role. The service starts failing on the next cache miss (i.e. within `INDEX_KEK_CACHE_TTL_SECONDS`). * **Permanent revoke** — customer deletes the role or the secret. Note: deleting the secret renders every index wrapped under it permanently unreadable. ## Configuration changes after creation Changes to the YAML registry take effect only after a service restart. Each index remembers the `provider`, `key_id`, and `region` it was created with, and on restart the service handles changes as follows: * **`role_arn` / `external_id` / `role_session_name` changes** — picked up automatically. Nothing else to do. * **`provider` / `key_id` / `region` changes** — treated as a key rotation. The service re-wraps each affected index under the new key on startup. The **old** key must still be reachable with the slot's new `role_arn` / `external_id`, so change the account and the key in separate steps. If a rotation fails, the service still starts, but requests for that index fail until the issue is fixed; check the startup logs. * **Slot removed** — don't remove a slot while indexes still use it. Requests for those indexes fail with HTTP 401 until the slot is restored. ## Troubleshooting > [accordion] `AccessDenied` on sts:AssumeRole > > Trust policy mismatch. Either the `Principal` doesn't match > the service's AWS identity, or `sts:ExternalId` doesn't > match the operator-provided UUID. Re-run the manual verify > in Step 5 above and share the exact error with the customer. > [accordion] `AccessDenied` on GetSecretValue > > The permission policy on the customer's role doesn't cover > the secret, or the `Resource` ARN is missing the required > `-*` suffix (Secrets Manager appends 6 random chars). > [accordion] `Wrap key not present in secrets manager` > > The secret was deleted, or the `region` in the YAML slot > doesn't match the region where the secret lives. Seen as > HTTP 502 on index creation (`...; cannot wrap`) and HTTP 401 > on later requests (`...; cannot unwrap`). > [accordion] `Wrap key must be 32 bytes` > > The Secrets Manager value is the wrong size. Replace with > exactly 32 random bytes. > [accordion] Index creation: `index_key must not be supplied alongside kms_name` > > Supplying both fields is rejected with HTTP 400 regardless > of provider type. Pick one path per index. Supplying neither > is also a 400: `exactly one of kms_name or index_key must be > supplied`. > [accordion] `index '\' is KMS-backed ... do not supply index_key` > > A request for a KMS-backed index included `index_key` > (HTTP 400). Remove it from the call. > [accordion] `Unknown KMS registry entry` > > `kms_name` doesn't match any slot under `kms.registry` > (HTTP 400). The error lists the known slots. Check the > startup log line `KMS registry loaded (...)`. > [accordion] Cached KEK after revoking access > > Plaintext KEKs are cached for > `INDEX_KEK_CACHE_TTL_SECONDS` (default 60 s). For tighter > revocation windows, drop the TTL — at the cost of more KMS > calls. There is no live invalidation API in v0.18. ## See also * [Environment Variables](./env-vars) — full configuration reference, including `INDEX_KEK_CACHE_TTL_SECONDS`. * [Managing Encryption Keys](./managing-keys) — the SDK-supplied (`provider: none`) path and the legacy "client decrypts via KMS" pattern. * [Create Index](../encrypted-indexes/create-index) — the `kms_name` parameter and the SDK-supplied alternative. # Managing Encryption Keys Source: https://docs.cyborg.co/versions/latest/service/guides/advanced/managing-keys CyborgDB encrypts every index under a 256-bit AES key (the **index key**, also referred to as the KEK). Without that key it is impossible to read the index — you cannot query, list, upsert, or even safely delete its contents. CyborgDB Service supports two completely different ways to provision and hold that key. Pick one per index: | Mode | What you set on `create_index` | Who holds the plaintext key | Best for | | - | - | - | - | | **SDK-supplied** | `index_key` (32 bytes) | Your SDK / application | Development, evaluation, single-tenant deployments where you already have a secure key store | | **KMS-backed** | `kms_name` (registry slot) | The service's KMS (AWS KMS or Secrets Manager) | Production, multi-tenant, BYOK | This page covers the **SDK-supplied** path. For production, prefer the KMS-backed path — see [Per-Index KMS & BYOK](./kms-byok) for the end-to-end setup. > [!WARNING] > > **Do not commit, log, or check in `index_key` material**, and do not store it in plaintext on shared filesystems. Lost keys cannot be recovered — every index wrapped under a lost key becomes permanently unreadable. ## Generating a key for development For local development and evaluation, generate a 256-bit key locally and pass it as `index_key` (or the SDK's typed equivalent). ```bash OpenSSL icon="rectangle-terminal" theme={null} # 32 random bytes, hex-encoded (64 hex chars) openssl rand -hex 32 ``` ```python Python SDK icon="python" theme={null} from cyborgdb import Client client = Client(base_url='http://localhost:8000', api_key='your-api-key') # Generate a 32-byte key; `save=True` writes it to ~/.cyborgdb/index_key index_key = client.generate_key(save=False) ``` ```typescript TypeScript SDK icon="code" theme={null} import { Client } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); // Returns a fresh 32-byte Uint8Array const indexKey: Uint8Array = client.generateKey(); ``` ```go Go SDK icon="golang" theme={null} import "github.com/cyborginc/cyborgdb-go" // Returns ([]byte, error) indexKey, err := cyborgdb.GenerateKey() if err != nil { log.Fatal(err) } ``` ## Using the key The same `index_key` you passed to `create_index` must be re-supplied on **every** subsequent request for that index — `load_index`, `upsert`, `query`, `get`, `delete`, `delete_index`. The service stores only a hash to verify the key on each request; it never persists the plaintext. ```python Python SDK icon="python" theme={null} # Create index = client.create_index('my_index', index_key=index_key, dimension=384) # Subsequent calls — same key index = client.load_index('my_index', index_key=index_key) index.upsert([{'id': 'a', 'vector': [0.1] * 384}]) results = index.query(query_vectors=[0.1] * 384, top_k=5) ``` ```typescript TypeScript SDK icon="code" theme={null} // Create const index = await client.createIndex({ indexName: 'my_index', indexKey, dimension: 384, }); // Subsequent calls — same key const loaded = await client.loadIndex({ indexName: 'my_index', indexKey }); await loaded.upsert({ items: [{ id: 'a', vector: new Array(384).fill(0.1) }] }); const results = await loaded.query({ queryVectors: new Array(384).fill(0.1), topK: 5 }); ``` ```go Go SDK icon="golang" theme={null} dim := int32(384) // Create index, _ := client.CreateIndex(context.Background(), &cyborgdb.CreateIndexParams{ IndexName: "my_index", IndexKey: indexKey, Dimension: &dim, }) // Subsequent calls — same key loaded, _ := client.LoadIndex(context.Background(), "my_index", indexKey) _ = loaded.Upsert(context.Background(), cyborgdb.VectorItems{ {Id: "a", Vector: []float32{ /* 384 values */ }}, }) ``` ```bash cURL icon="rectangle-terminal" theme={null} INDEX_KEY=$(openssl rand -hex 32) # Create curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d "{ \"index_name\": \"my_index\", \"index_key\": \"$INDEX_KEY\", \"dimension\": 384 }" # Subsequent calls — same hex key curl -X POST "http://localhost:8000/v1/indexes/describe" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d "{ \"index_name\": \"my_index\", \"index_key\": \"$INDEX_KEY\" }" ``` ## Persisting the key The service never persists the plaintext key, so your application owns key storage. For development, the Python SDK's `generate_key(save=True)` will cache the generated key in `~/.cyborgdb/index_key` — useful for evaluation, **not for production**. For production: * Store the key in your platform's secret store (Vault, AWS Secrets Manager, GCP Secret Manager, Azure Key Vault, k8s Secret) and fetch it at runtime. * Or **switch to the KMS-backed path** so the SDK never holds a long-term key: see [Per-Index KMS & BYOK](./kms-byok). ## Migrating from SDK-supplied to KMS-backed You cannot rotate an index *in place* from `provider: none` to a real KMS provider — the wrapping model changes. The migration path is: 1. Create a new index with `kms_name` set instead of `index_key`. 2. Replay your data (`upsert`) into the new index. 3. Delete the old index. This is intentional: the persisted envelope for `provider: none` records no wrap key, so there is nothing for the KMS path to unwrap. Bulk re-encryption against a fresh DEK happens on the upsert. ## See also * [Per-Index KMS & BYOK](./kms-byok) — production setup with AWS KMS or Secrets Manager (preferred for production). * [Environment Variables](./env-vars) — `CYBORGDB_API_KEY` and other service-level configuration. * [Create an Encrypted Index](../encrypted-indexes/create-index) — full `create_index` reference, including `kms_name`. # Multi-Tenancy & RBAC Source: https://docs.cyborg.co/versions/latest/service/guides/advanced/multi-tenancy CyborgDB Service ships with an **operator-side multi-tenancy model** built on cryptographic isolation: each index is wrapped by its own key, and per-user API keys hold their own wrapped data-encryption keys (DEKs). Permissions aren't stored as a policy blob — the **set of wrapped DEKs a user holds *is* their permission set**, enforced cryptographically on every request. This page is the operator playbook: how to enable RBAC, mint and revoke users, and the constraints to be aware of. ## Modes | Mode | Enabled by | Who can call what | | - | - | - | | **Unauthenticated (default)** | `CYBORGDB_SERVICE_ROOT_KEY` unset | Authentication is disabled — every request is accepted, with or without an `X-API-Key` header. No user routes available. | | **RBAC** | `CYBORGDB_SERVICE_ROOT_KEY` set | The root key has admin (mint/list/revoke users, create/train/delete indexes). Per-user `cdbk_…` keys are scoped to one index with `read` / `write` permissions. | You enable RBAC by setting the root key at startup: ```bash theme={null} export CYBORGDB_SERVICE_ROOT_KEY=cyborg_your_root_key # opt-in: enables RBAC cyborgdb-service ``` Or via YAML: ```yaml cyborgdb.yaml theme={null} service: cyborgdb_service_root_key: ${CYBORGDB_SERVICE_ROOT_KEY} ``` > [!WARNING] > > The root key has admin privileges; treat it like a master credential. Pick a fresh value — don't reuse the `CYBORGDB_API_KEY` license key, which is a separate, non-authentication key (sending it as `X-API-Key` is rejected with 401). ## Key kinds When RBAC is on, the service classifies every `X-API-Key` request header: | Kind | Header value | What it can do | | - | - | - | | `root` | `CYBORGDB_SERVICE_ROOT_KEY` | Full admin: create/train/delete indexes; mint/list/revoke users; all data operations. | | `user` | A `cdbk_…` token minted via `POST /v1/indexes/{name}/users` | Data operations on **one** index, gated by the `read` / `write` permission set requested at mint time. Cannot create/delete indexes or manage users. | | *(anything else)* | Any other value — including the `CYBORGDB_API_KEY` license key — or no header at all | Rejected with `401`. (`GET /health` is exempt — it never requires a key.) | If `CYBORGDB_SERVICE_ROOT_KEY` is unset, authentication is disabled entirely — RBAC is strictly opt-in. ## Provisioning users A user is **scoped to exactly one index**, with a non-empty subset of `{"read", "write"}` permissions. Mint a user with the root key: ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/indexes/documents/users" \ -H "X-API-Key: $CYBORGDB_SERVICE_ROOT_KEY" \ -H "Content-Type: application/json" \ -d '{ "permissions": ["read", "write"] }' # Response (returned ONCE — capture it): # { "user_id": "ab12…", "api_key": "cdbk_…" } ``` ```python Python SDK icon="python" theme={null} from cyborgdb import Client admin = Client(base_url='http://localhost:8000', api_key=ROOT_KEY) index = admin.load_index('documents') # KMS-backed: no index_key result = index.create_user(permissions=['read', 'write']) user_id = result['user_id'] api_key = result['api_key'] # Hand `api_key` to the new user via a secure channel — it is never recoverable. # Avoid logging or printing it. ``` ```typescript TypeScript SDK icon="code" theme={null} import { Client } from 'cyborgdb'; const admin = new Client({ baseUrl: 'http://localhost:8000', apiKey: ROOT_KEY }); const index = await admin.loadIndex({ indexName: 'documents' }); const { userId, apiKey } = await index.createUser({ permissions: ['read', 'write'] }); // capture apiKey once — never recoverable ``` ```go Go SDK icon="golang" theme={null} admin, _ := cyborgdb.NewClient("http://localhost:8000", rootKey) index, _ := admin.LoadIndex(context.Background(), "documents", nil) user, _ := index.CreateUser(context.Background(), []string{"read", "write"}) // Hand user.APIKey to the new user via a secure channel — it is never recoverable. // Avoid logging or printing it. _ = user.UserID _ = user.APIKey ``` > [!WARNING] > > **The `api_key` is returned exactly once and is never stored by the service.** If you lose it, you must revoke the user and mint a new one. Hand it to the user securely (out-of-band, encrypted channel, secret store). The user authenticates by passing `cdbk_…` as `api_key` to their `Client` — they need **no index key** of their own (the token carries the user's key material, and the service opens the index via that user's wrapped DEK). ```python theme={null} # End user from cyborgdb import Client client = Client(base_url='http://localhost:8000', api_key='cdbk_…') index = client.load_index('documents') # no index_key argument index.query(query_vectors=[0.1]*384, top_k=5) ``` ## Listing and revoking users ```bash cURL icon="rectangle-terminal" theme={null} # List curl -X GET "http://localhost:8000/v1/indexes/documents/users" \ -H "X-API-Key: $CYBORGDB_SERVICE_ROOT_KEY" # Revoke curl -X DELETE "http://localhost:8000/v1/indexes/documents/users/ab12…" \ -H "X-API-Key: $CYBORGDB_SERVICE_ROOT_KEY" ``` ```python Python SDK icon="python" theme={null} users = index.list_users() for u in users: print(u['user_id'], u['permissions']) index.delete_user('ab12…') # cryptographic revocation ``` ```typescript TypeScript SDK icon="code" theme={null} const users = await index.listUsers(); await index.deleteUser({ userId: 'ab12…' }); ``` ```go Go SDK icon="golang" theme={null} users, _ := index.ListUsers(context.Background()) _ = index.DeleteUser(context.Background(), "ab12…") ``` Revocation is **cryptographic, not policy-based**: the service erases that user's wrapped DEK(s) for the index. On the next request, the service has nothing to unwrap for them — even a captured `cdbk_…` token becomes useless. There is no propagation lag. ## SDK-supplied indexes Per-user keys work on **both** key-management paths — KMS-backed indexes (`kms_name=…`) and SDK-supplied indexes (`index_key=…`). The index KEK is needed only at **mint time**, to unwrap the root DEK and re-wrap it under the new user: for KMS-backed indexes the service resolves the KEK server-side, while for SDK-supplied indexes you pass it on the `create_user` call (`index_key` in the POST body). From then on the user authenticates with their `cdbk_…` token alone — the service opens the index via the user's own wrapped DEK, so no index KEK is involved on their requests, on either path. One difference remains on SDK-supplied indexes: **auto-training after a user's upsert is skipped**, because the training job runs out-of-band with the index KEK and the service holds none for a `provider: none` index. The skip is per-caller, not per-index: a root upsert that supplies `index_key` still triggers auto-training on the same index. So to keep an SDK-supplied index trained under user writes, either train it explicitly with the root key (supplying `index_key`), upsert as root when practical, or migrate to KMS-backed (see [Managing Encryption Keys → Migrating](./managing-keys#migrating-from-sdk-supplied-to-kms-backed)). > [!NOTE] > > KMS-backed indexes stay the smoother fit for multi-tenancy: minting needs no key material in the request, and auto-training keeps working for user writes. But it is a recommendation, not a requirement. ## End-to-end example A typical operator workflow for onboarding a new tenant: **1. Provision a KMS slot** Add a registry entry to your service YAML — see [KMS & BYOK](./kms-byok). ```yaml cyborgdb.yaml theme={null} kms: registry: tenant-acme: provider: aws-kms key_id: alias/cyborgdb-acme region: us-east-1 ``` Restart the service. Look for `KMS registry loaded` in the logs. **2. Create the tenant's index (root)** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: $CYBORGDB_SERVICE_ROOT_KEY" \ -H "Content-Type: application/json" \ -d '{ "index_name": "acme-documents", "kms_name": "tenant-acme", "dimension": 384, "metric": "cosine" }' ``` **3. Mint a user key for the tenant (root)** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/acme-documents/users" \ -H "X-API-Key: $CYBORGDB_SERVICE_ROOT_KEY" \ -H "Content-Type: application/json" \ -d '{ "permissions": ["read", "write"] }' ``` Hand the returned `cdbk_…` to the tenant out-of-band. **4. Tenant uses the index** The tenant configures their SDK client with `api_key = "cdbk_…"` and operates only on `acme-documents`. They cannot list, describe, or touch any other tenant's index. **5. Revoke when access ends** ```bash theme={null} curl -X DELETE "http://localhost:8000/v1/indexes/acme-documents/users/" \ -H "X-API-Key: $CYBORGDB_SERVICE_ROOT_KEY" ``` Revocation is immediate — the tenant's next request fails with 401. ## Operational notes * **Read vs write semantics.** `read` covers `query`, `get`, `list_ids`, `describe`. `write` covers `upsert`, `delete`. Index lifecycle operations (`create`, `train`, `delete_index`) and user management are root-only — there's no "delegated admin" permission. * **KEK cache.** Plaintext index KEKs live in an in-process cache for `INDEX_KEK_CACHE_TTL_SECONDS` (default 60s). Revoking a user is immediate and cryptographic; revoking *KMS-level* access to the wrap key propagates within the cache TTL. * **Restarting the service.** User keys survive restart — the wrapped DEKs are persisted alongside the index envelope. The root key is read from env/YAML on every start. ## See also * [Per-Index KMS & BYOK](./kms-byok) — required for per-user keys. * [Environment Variables](./env-vars) — `CYBORGDB_SERVICE_ROOT_KEY`, `INDEX_KEK_CACHE_TTL_SECONDS`. * REST API: [Create User](../../rest-api/users/create-user), [List Users](../../rest-api/users/list-users), [Delete User](../../rest-api/users/delete-user). # Train an Encrypted Index Source: https://docs.cyborg.co/versions/latest/service/guides/advanced/train-index CyborgDB Service stores every encrypted index as an inverted-file (IVF) index whose clusters are produced by a training step. Training fits the clustering model to the actual vectors in your index so queries can probe a small number of clusters instead of scanning everything. In CyborgDB Service, training is handled automatically: by default, an index is trained once it holds more than 65,536 vectors, and retrained as it grows (see [How automatic training works](#how-automatic-training-works)). You can also trigger training explicitly once enough vectors have been added, for example to specify training parameters. ```python Python SDK icon="python" theme={null} # Train the encrypted index index.train() # Or train with a specific number of clusters index.train(n_lists=128) ``` ```javascript JavaScript SDK icon="js" theme={null} // Train the encrypted index await index.train(); // Or train with a specific number of clusters await index.train({ nLists: 128 }); ``` ```typescript TypeScript SDK icon="code" theme={null} // Train the encrypted index await index.train(); // Or train with a specific number of clusters await index.train({ nLists: 128 }); ``` ```go Go SDK icon="golang" theme={null} // Train the encrypted index err := index.Train(context.Background(), cyborgdb.TrainParams{}) // Or train with a specific number of clusters nLists := int32(128) err = index.Train(context.Background(), cyborgdb.TrainParams{ NLists: &nLists, }) ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/indexes/train" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' ``` > [!NOTE] > > Training requires at least 10,000 vectors **and** at least `2 * n_lists` vectors in the index (ingested via `upsert`). If the index has fewer, `train` does not return an error: the service logs a warning and the index stays untrained. Use `is_trained()` to check whether training took effect. ## Training Parameters Parameters are available to customize the training process: | Parameter | Type | Default | Description | | - | - | - | - | | `n_lists` | `int` | `None` (auto) | *(Optional)* Number of inverted index lists to create in the index. When `None` or omitted, auto-determines based on the number of vectors in the index. | | `batch_size` | `int` | `None` | *(Optional)* Number of vectors to process per training batch. When `None`, the server uses 2048. | | `max_iters` | `int` | `None` | *(Optional)* Maximum number of training iterations. When `None`, the server uses 100. | | `tolerance` | `float` | `None` | *(Optional)* Convergence tolerance for training completion. When `None`, the server uses 1e-6. | | `max_memory` | `int` | `None` (0) | *(Optional)* Maximum memory usage in MB. When `None` or 0, no memory limit is applied. | `n_lists` is the number of clusters into which each vector in the index can be categorized. Typically, the higher the value, the higher the recall (but also the slower the indexing process). As a good rule of thumb, `n_lists` should be: * A base-2 number (e.g., `2,048`, `4,096`). Not a requirement, but yields performance optimizations. * Each cluster should have between `100` - `10,000` vectors; so `n_lists` should be roughly between `1/100` - `1/10,000` of the total number of items which will be indexed. If not specified, CyborgDB will auto-determine the best `n_lists` value based on the number of vectors in the index. ## How automatic training works After each upsert, the service checks whether the index should be trained or retrained: * **First training.** An untrained index is trained automatically once it holds more than `AUTO_TRAIN_MIN_VECTORS` vectors (default `65536`). * **Retraining.** A trained index is retrained automatically when the optimal `n_lists` for its current vector count grows past the index's current `n_lists`. The optimal `n_lists` is the square root of the vector count, rounded to a power of two and capped at `65,536`. In practice, an index is retrained roughly each time its vector count grows about 4x. Automatic training uses the optimal `n_lists` for the vector count at the time it runs. Training runs in the background, so the upsert that triggers it returns immediately. For an index that was first trained automatically, the progression looks like this: | Vectors in index | Optimal `n_lists` | Automatic action | | - | - | - | | 65,536 or fewer | — | None (index stays untrained) | | 65,537 | 256 | First training | | 131,072 | 512 | Retrain | | 524,288 | 1,024 | Retrain | | 2,097,152 | 2,048 | Retrain | | 8,388,608 | 4,096 | Retrain | | 33,554,432 | 8,192 | Retrain | If you train with an explicit `n_lists`, the index is retrained automatically only once the optimal `n_lists` exceeds the value you chose. To change the first-training threshold, set `AUTO_TRAIN_MIN_VECTORS`. To turn off automatic training and retraining entirely, set `AUTO_TRAIN_DISABLED=true`; you then train indexes yourself with `train()`. See the [Environment Variables](./env-vars#optional-environment-variables) guide. ## Avoid the large-untrained-query warning While training is technically optional (you can use CyborgDB without ever calling `train`), it is recommended that you do so once you have a large number of vectors in the index (e.g., `> 50,000`). If you don't, and you call `query`, you will see a warning in the console, stating: ``` Warning: querying untrained index with more than 50000 indexed vectors. ``` ## API Reference For more information on training an encrypted index, refer to the API reference: > [card] [REST API Reference](../../rest-api/encrypted-index/train) > > REST API reference for `/v1/indexes/train` > [card] [Python SDK Reference](../../python-sdk/encrypted-index/train) > > API reference for `train()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/encrypted-index/train) > > API reference for `train()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/encrypted-index/train) > > API reference for `Train()` in Go # CyborgDB Usage Telemetry Source: https://docs.cyborg.co/versions/latest/service/guides/advanced/usage-telemetry Since version `v0.11.0`, CyborgDB uses privacy-preserving telemetry to track usage. This usage data is used in order to: * Bill paying customers based on their usage * Improve the product by understanding how it is used > [!TIP] > > No private data is ever collected or shared, and all telemetry data is encrypted before being sent to the server. ### What is Collected Below you can find a comprehensive list of the telemetry events that are collected: | Event Name | Description | | - | - | | `initialize` | Triggered when the CyborgDB library is initialized. | | `create_index` | Triggered when a new index is created. | | `delete_index` | Triggered when an index is deleted. | | `upsert` | Triggered when items are added to an index. A count of the items added is also included. | | `query` | Triggered when a query is performed on an index. Includes the top-k value. | | `delete` | Triggered when items are deleted from an index. A count of the items deleted is also included. | | `get` | Triggered when an item is retrieved from an index. | CyborgDB's usage telemetry was built from the ground up to be privacy-preserving, with data minimization and no third-party sharing. We do **NOT** collect any private data, such as raw content, embeddings, or queries. All telemetry is compliant with our [Privacy Policy](https://www.cyborg.co/privacy-policy). Should you have any questions, please [contact us](https://www.cyborg.co/contact). # YAML Configuration Reference Source: https://docs.cyborg.co/versions/latest/service/guides/advanced/yaml-reference CyborgDB Service can be configured entirely via environment variables, entirely via a YAML file, or any mix of the two. This page is the canonical, exhaustive YAML reference — every key the service understands, what it does, and what its default is. For prose explanations and end-to-end walkthroughs, see: * [Environment Variables](./env-vars) — the env-var equivalents of every key here. * [Per-Index KMS & BYOK](./kms-byok) — the `kms.registry` block, in depth. * [Multi-Tenancy & RBAC](./multi-tenancy) — the `cyborgdb_service_root_key` key and its operator implications. ## Resolution and precedence The service resolves a YAML file in this order (first hit wins): 1. The `CYBORGDB_CONFIG_FILE` environment variable. Missing path = hard error. 2. `./cyborgdb.yaml` 3. `./cyborgdb.yml` 4. `/etc/cyborgdb/cyborgdb.yaml` A missing file is fine — the service falls back to env-only. Settings precedence, highest to lowest: 1. Environment variables 2. `.env` file 3. YAML file ## Env-var substitution Any string value in the YAML may reference an environment variable: * `${VAR}` — required. Startup fails if `VAR` is unset. * `${VAR:-default}` — uses `default` when `VAR` is unset. A variable set to the **empty string counts as unset**. Use this pattern to keep BYOK role ARNs, account IDs, and credentials out of the checked-in YAML. ## Full schema ```yaml cyborgdb.yaml theme={null} service: # ---- Server ---- port: 8000 # int. Default: 8000. cyborgdb_service_log_level: INFO # DEBUG | INFO | WARNING | ERROR. Default: INFO. # ---- TLS / HTTPS (optional; both required, both must exist on disk) ---- ssl_cert_path: /etc/cyborgdb/tls/cert.pem # string. Default: unset (HTTP). ssl_key_path: /etc/cyborgdb/tls/key.pem # string. Default: unset (HTTP). # ---- Keys ---- cyborgdb_api_key: ${CYBORGDB_API_KEY} # string. Optional. Core license key — free tier # (1M items/index) when unset. NOT an # authentication credential. cyborgdb_service_root_key: ${CYBORGDB_SERVICE_ROOT_KEY} # string. Optional. When set, enables # authentication/RBAC: clients must send this # root key or a cdbk_ user token as X-API-Key. # When unset, no header is required. # See ./multi-tenancy. # ---- Storage backend ---- cyborgdb_db_type: disk # disk | s3. Default: disk. cyborgdb_disk_path: /var/lib/cyborgdb # string. disk only. Default: ~/.cyborgdb/data # (or /app/cyborgdb_data in Docker). # S3 settings (used only when cyborgdb_db_type: s3) cyborgdb_s3_bucket: my-bucket # string. REQUIRED for s3. cyborgdb_s3_region: us-east-1 # string. Optional. Default: us-east-1. cyborgdb_s3_prefix: cyborgdb/ # string. Optional. Default: unset. cyborgdb_s3_endpoint: https://minio.internal:9000 # string. Optional. Required for non-AWS endpoints. cyborgdb_s3_access_key: ${MINIO_ACCESS_KEY} # string. Required with cyborgdb_s3_endpoint. cyborgdb_s3_secret_key: ${MINIO_SECRET_KEY} # string. Required with cyborgdb_s3_endpoint. cyborgdb_s3_session_token: ${MINIO_SESSION_TOKEN} # string. Optional. # ---- Per-keystore RAM cache (applied to every newly created index) ---- cache_policy_vectors: false # bool. Default: false. cache_policy_metadata: false # bool. Default: false. cache_policy_ids: false # bool. Default: false. # ---- Performance ---- cpu_threads: 0 # int. 0 = auto-detect. Default: 0. gpu_operations: none # none | upsert | train | all | comma-list. # Default: none. (Query GPU not yet supported.) auto_train_min_vectors: 65536 # int. Default: 65536. An untrained index is # trained automatically once it holds more than # this many vectors. See ./train-index. auto_train_disabled: false # bool. Default: false. Set to true to fully # disable post-upsert auto-training and # retraining (explicit train() / # POST /v1/indexes/train still work). # ---- KMS cache ---- index_kek_cache_ttl_seconds: 60 # int. Default: 60. TTL for plaintext index KEKs # in the service-side cache. Shorter = faster # KMS revocation propagation; longer = fewer # KMS calls. # ---- Per-index KMS registry (optional; required only if any index uses kms_name) ---- kms: registry: # Each child is a named slot referenced by create_index(kms_name=...). : provider: aws-kms # aws-kms | aws. REQUIRED per slot. # aws-kms — AWS KMS (HSM-managed KEK). # aws — AWS Secrets Manager (KEK in # Secrets Manager; local AES-GCM). key_id: alias/cyborgdb-default # string. REQUIRED. KMS key id/ARN or # Secrets Manager name/ARN, depending on provider. region: us-east-1 # string. REQUIRED. # BYOK (cross-account access): optional triple. role_arn: ${ACME_BYOK_ROLE_ARN} # string. Optional. Service calls sts:AssumeRole. external_id: ${ACME_BYOK_EXTERNAL_ID} # string. Required if role_arn set. role_session_name: cyborgdb-acme # string. Optional. Appears in customer's CloudTrail. ``` ## Storage backend cheat sheet | Backend | Persistence | Required keys (beyond `cyborgdb_db_type`) | Credential source | | - | - | - | - | | `disk` (default) | Persistent store on local disk | `cyborgdb_disk_path` (optional) | n/a | | `s3` (AWS, instance role) | AWS S3 | `cyborgdb_s3_bucket` | AWS default credential provider chain (instance/task role, env, profile) | | `s3` (AWS, explicit keys) | AWS S3 | `cyborgdb_s3_bucket` + `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` env vars | AWS default chain | | `s3` (S3-compatible: MinIO, R2, …) | MinIO/R2 etc. | `cyborgdb_s3_bucket`, `cyborgdb_s3_endpoint`, `cyborgdb_s3_access_key`, `cyborgdb_s3_secret_key` | Explicit `CYBORGDB_S3_*` only — AWS chain bypassed | > [!NOTE] > > The `CYBORGDB_S3_*` namespace is deliberately separate from `AWS_*` so storage and KMS credentials cannot collide. KMS (under `kms.registry`) uses the standard AWS credential chain or `sts:AssumeRole`; S3 storage uses its own explicit keys (or the chain if no explicit keys are set). ## KMS provider matrix | Provider | Where the wrap key lives | KEK flow | When to choose | | - | - | - | - | | `aws-kms` | AWS KMS (HSM-managed) | Service generates KEK → `kms.Encrypt`. On load, `kms.Decrypt`. | HSM isolation; cleanest revocation semantics. | | `aws` | AWS Secrets Manager | Service generates KEK → AES-GCM-wraps under the Secrets Manager value. On load, fetches the secret and unwraps locally. | Cross-account BYOK where customers prefer Secrets Manager. | Both providers accept `role_arn` + `external_id` for cross-account (BYOK) access — the service calls `sts:AssumeRole` before reaching the key on every wrap or unwrap. ## Minimal viable configs **Dev — disk, no authentication:** ```yaml theme={null} service: cyborgdb_api_key: ${CYBORGDB_API_KEY} # optional license key; free tier when unset ``` **Production — S3 on AWS with instance role, TLS, RBAC:** ```yaml theme={null} service: port: 8443 cyborgdb_api_key: ${CYBORGDB_API_KEY} cyborgdb_service_root_key: ${CYBORGDB_SERVICE_ROOT_KEY} ssl_cert_path: /etc/ssl/certs/cyborgdb.crt ssl_key_path: /etc/ssl/private/cyborgdb.key cyborgdb_db_type: s3 cyborgdb_s3_bucket: cyborgdb-prod cyborgdb_s3_region: us-east-1 ``` **Production — MinIO + per-tenant BYOK:** ```yaml theme={null} service: cyborgdb_api_key: ${CYBORGDB_API_KEY} cyborgdb_service_root_key: ${CYBORGDB_SERVICE_ROOT_KEY} cyborgdb_db_type: s3 cyborgdb_s3_bucket: cyborgdb cyborgdb_s3_endpoint: https://minio.internal:9000 cyborgdb_s3_access_key: ${MINIO_ACCESS_KEY} cyborgdb_s3_secret_key: ${MINIO_SECRET_KEY} index_kek_cache_ttl_seconds: 30 kms: registry: vendor-default: provider: aws-kms key_id: alias/cyborgdb-default region: us-east-1 customer-acme: provider: aws key_id: customers/acme/wrap-key region: us-west-2 role_arn: ${ACME_BYOK_ROLE_ARN} external_id: ${ACME_BYOK_EXTERNAL_ID} ``` ## Validation behavior * Invalid `cyborgdb_db_type` (anything not in `disk | s3`) — startup fails fast with a clear error. * `CYBORGDB_CONFIG_FILE` set to a missing path — hard error. * `${VAR}` referencing an unset env var — hard error at parse time. * KMS slot with missing `provider`/`key_id`/`region` — load-time error when the first index references the slot. * `cyborgdb_s3_endpoint` set without explicit `cyborgdb_s3_access_key` + `cyborgdb_s3_secret_key` — startup fails (the AWS chain is bypassed for custom endpoints). ## See also * [Environment Variables](./env-vars) — every key here has an env-var equivalent. * [Per-Index KMS & BYOK](./kms-byok) — operator + customer setup, rotation, troubleshooting. * [Multi-Tenancy & RBAC](./multi-tenancy) — the `cyborgdb_service_root_key` operator playbook. # Add Items to an Encrypted Index Source: https://docs.cyborg.co/versions/latest/service/guides/data-operations/add-items Once you have created or connected to an encrypted index, you can add items to it. To do this, you can use the `upsert()` function: ```python Python SDK icon="python" theme={null} # Items to add to the encrypted index items = [ {"id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4]}, {"id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8]}, {"id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12]} ] # Add items to the encrypted index index.upsert(items) ``` ```javascript JavaScript SDK icon="js" theme={null} // Items to add to the encrypted index const items = [ {id: "item_1", vector: [0.1, 0.2, 0.3, 0.4]}, {id: "item_2", vector: [0.5, 0.6, 0.7, 0.8]}, {id: "item_3", vector: [0.9, 0.10, 0.11, 0.12]} ]; // Add items to the encrypted index await index.upsert({ items }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { VectorItem, UpsertRequest } from 'cyborgdb'; // Items to add to the encrypted index const items: VectorItem[] = [ {id: "item_1", vector: [0.1, 0.2, 0.3, 0.4]}, {id: "item_2", vector: [0.5, 0.6, 0.7, 0.8]}, {id: "item_3", vector: [0.9, 0.10, 0.11, 0.12]} ]; // Add items to the encrypted index const params: UpsertRequest = { items }; await index.upsert(params); ``` ```go Go SDK icon="golang" theme={null} package main import ( "context" "log" "github.com/cyborginc/cyborgdb-go" ) // Items to add to the encrypted index items := cyborgdb.VectorItems{ {Id: "item_1", Vector: []float32{0.1, 0.2, 0.3, 0.4}}, {Id: "item_2", Vector: []float32{0.5, 0.6, 0.7, 0.8}}, {Id: "item_3", Vector: []float32{0.9, 0.10, 0.11, 0.12}}, } // Add items to the encrypted index err := index.Upsert(context.Background(), items) if err != nil { log.Fatal(err) } ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/upsert" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "items": [ { "id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4] }, { "id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8] }, { "id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12] } ] }' ``` ## Adding Items with Contents It's also possible to store item contents alongside vectors. To do this, include `contents` in the `upsert()` call. The contents field accepts both strings and bytes. Bytes are automatically base64-encoded before encryption, while strings are passed as-is. All contents are encrypted before storage using the index key. In Python, contents are returned in their original format (string or bytes) when retrieved with `get()`. In JavaScript/TypeScript, contents are returned as decoded UTF-8 strings. In Go, contents are returned as string. ```python Python SDK icon="python" theme={null} # Items to add to the encrypted index items = [ {"id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Hello!"}, {"id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "contents": "World!"}, {"id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12], "contents": "Cyborg!"} ] # Add items to the encrypted index index.upsert(items) ``` ```javascript JavaScript SDK icon="js" theme={null} // Items to add to the encrypted index const items = [ {id: "item_1", vector: [0.1, 0.2, 0.3, 0.4], contents: "Hello!"}, {id: "item_2", vector: [0.5, 0.6, 0.7, 0.8], contents: "World!"}, {id: "item_3", vector: [0.9, 0.10, 0.11, 0.12], contents: "Cyborg!"} ]; // Add items to the encrypted index await index.upsert({ items }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { VectorItem, UpsertRequest } from 'cyborgdb'; // Items to add to the encrypted index const items: VectorItem[] = [ {id: "item_1", vector: [0.1, 0.2, 0.3, 0.4], contents: "Hello!"}, {id: "item_2", vector: [0.5, 0.6, 0.7, 0.8], contents: "World!"}, {id: "item_3", vector: [0.9, 0.10, 0.11, 0.12], contents: "Cyborg!"} ]; // Add items to the encrypted index const params: UpsertRequest = { items }; await index.upsert(params); ``` ```go Go SDK icon="golang" theme={null} // Items to add to the encrypted index items := cyborgdb.VectorItems{ {Id: "item_1", Vector: []float32{0.1, 0.2, 0.3, 0.4}, Contents: cyborgdb.NewNullableContents("Hello!")}, {Id: "item_2", Vector: []float32{0.5, 0.6, 0.7, 0.8}, Contents: cyborgdb.NewNullableContents("World!")}, {Id: "item_3", Vector: []float32{0.9, 0.10, 0.11, 0.12}, Contents: cyborgdb.NewNullableContents("Cyborg!")}, } // Add items to the encrypted index err := index.Upsert(context.Background(), items) if err != nil { log.Fatal(err) } ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/upsert" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "items": [ { "id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Hello!" }, { "id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "contents": "World!" }, { "id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12], "contents": "Cyborg!" } ] }' ``` ## Adding Items with Metadata CyborgDB also supports metadata storage, retrieval and filtering. To add metadata to an item, include `metadata` in the `upsert()` call. All metadata fields will be encrypted using the index key. ```python Python SDK icon="python" theme={null} # Items to add to the encrypted index items = [ {"id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "metadata": {"name": "Alice", "age": 30}}, {"id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "metadata": {"name": "Bob", "age": 40}}, {"id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12], "metadata": {"name": "Charlie", "age": 50}} ] # Add items to the encrypted index index.upsert(items) ``` ```go Go SDK icon="golang" theme={null} // Items to add to the encrypted index items := cyborgdb.VectorItems{ { Id: "item_1", Vector: []float32{0.1, 0.2, 0.3, 0.4}, Metadata: map[string]interface{}{"name": "Alice", "age": 30}, }, { Id: "item_2", Vector: []float32{0.5, 0.6, 0.7, 0.8}, Metadata: map[string]interface{}{"name": "Bob", "age": 40}, }, { Id: "item_3", Vector: []float32{0.9, 0.10, 0.11, 0.12}, Metadata: map[string]interface{}{"name": "Charlie", "age": 50}, }, } // Add items to the encrypted index err := index.Upsert(context.Background(), items) if err != nil { log.Fatal(err) } ``` ```javascript JavaScript SDK icon="js" theme={null} // Items to add to the encrypted index const items = [ {id: "item_1", vector: [0.1, 0.2, 0.3, 0.4], metadata: {name: "Alice", age: 30}}, {id: "item_2", vector: [0.5, 0.6, 0.7, 0.8], metadata: {name: "Bob", age: 40}}, {id: "item_3", vector: [0.9, 0.10, 0.11, 0.12], metadata: {name: "Charlie", age: 50}} ]; // Add items to the encrypted index await index.upsert({ items }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { VectorItem, UpsertRequest } from 'cyborgdb'; // Define metadata type (optional) interface PersonMetadata { name: string; age: number; } // Items to add to the encrypted index const items: VectorItem[] = [ {id: "item_1", vector: [0.1, 0.2, 0.3, 0.4], metadata: {name: "Alice", age: 30} as PersonMetadata}, {id: "item_2", vector: [0.5, 0.6, 0.7, 0.8], metadata: {name: "Bob", age: 40} as PersonMetadata}, {id: "item_3", vector: [0.9, 0.10, 0.11, 0.12], metadata: {name: "Charlie", age: 50} as PersonMetadata} ]; // Add items to the encrypted index const params: UpsertRequest = { items }; await index.upsert(params); ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/upsert" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "items": [ { "id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "metadata": {"name": "Alice", "age": 30} }, { "id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "metadata": {"name": "Bob", "age": 40} }, { "id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12], "metadata": {"name": "Charlie", "age": 50} } ] }' ``` For more info on metadata storage and filtering, see [Metadata Filtering](./metadata-filtering). ## Automatic Embedding Generation If you provided an `embedding_model` during index creation, you can automatically generate embeddings for items by providing `contents` to the `upsert()` call: ```python Python SDK icon="python" theme={null} # ... index creation and embedding model setup embedding_model = "all-MiniLM-L6-v2" index = client.create_index( index_name="my_index", index_key=index_key, embedding_model=embedding_model ) # Items to add to the encrypted index items = [ {"id": "item_1", "contents": "Hello, World!"}, {"id": "item_2", "contents": "Hello, Cyborg!"} ] # Add items to the encrypted index index.upsert(items) ``` ```javascript JavaScript SDK icon="js" theme={null} // ... index creation and embedding model setup const embeddingModel = "all-MiniLM-L6-v2"; const index = await client.createIndex({ indexName: "my_index", indexKey, embeddingModel }); // Items to add to the encrypted index const items = [ {id: "item_1", contents: "Hello, World!"}, {id: "item_2", contents: "Hello, Cyborg!"} ]; // Add items to the encrypted index await index.upsert({ items }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { VectorItem, UpsertRequest, EncryptedIndex, CreateIndexRequest } from 'cyborgdb'; // ... index creation and embedding model setup const embeddingModel: string = "all-MiniLM-L6-v2"; const indexParams: CreateIndexRequest = { indexName: "my_index", indexKey, embeddingModel }; const index: EncryptedIndex = await client.createIndex(indexParams); // Items to add to the encrypted index const items: VectorItem[] = [ {id: "item_1", contents: "Hello, World!"}, {id: "item_2", contents: "Hello, Cyborg!"} ]; // Add items to the encrypted index const params: UpsertRequest = { items }; await index.upsert(params); ``` ```go Go SDK icon="golang" theme={null} // Items to add to the encrypted index items := cyborgdb.VectorItems{ {Id: "item_1", Contents: cyborgdb.NewNullableContents("Hello, World!")}, {Id: "item_2", Contents: cyborgdb.NewNullableContents("Hello, Cyborg!")}, } // Add items to the encrypted index err := index.Upsert(context.Background(), items) if err != nil { log.Fatal(err) } ``` ```bash cURL icon="rectangle-terminal" theme={null} # For indexes created with embedding_model curl -X POST "http://localhost:8000/v1/vectors/upsert" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "items": [ { "id": "item_1", "contents": "Hello, World!" }, { "id": "item_2", "contents": "Hello, Cyborg!" } ] }' ``` In this example, the `embedding_model` will automatically generate embeddings for the `contents` field. The contents will also be stored alongside the generated embeddings. This feature uses various embedding models available through the service. You can use any model supported by the CyborgDB service, including models from the [HuggingFace Model Hub](https://huggingface.co/models). ## Automatic training on upsert `upsert` may trigger background training automatically: by default, an untrained index is trained once it holds more than 65,536 vectors, and a trained index is retrained as it grows. See [How automatic training works](../advanced/train-index#how-automatic-training-works) for the exact rules. When training is triggered, the upsert response carries two extra fields: ```json theme={null} { "status": "success", "message": "Upserted 5000 vectors", "training_triggered": true, "training_message": "Index training has been triggered (vectors: 70000)" } ``` Training runs asynchronously — the upsert itself does not block on it. Use `isTraining()` (per-index) or `GET /v1/indexes/training-status` (global) to poll progress. To disable this behavior — e.g. when benchmarking a fixed index state — set `AUTO_TRAIN_DISABLED=true` on the service. Explicit `train()` / `POST /v1/indexes/train` keep working in either mode. ## API Reference For more information on adding items to an encrypted index, refer to the API reference: > [card] [REST API Reference](../../rest-api/encrypted-index/upsert) > > REST API reference for `/v1/vectors/upsert` > [card] [Python SDK Reference](../../python-sdk/encrypted-index/upsert) > > API reference for `upsert()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/encrypted-index/upsert) > > API reference for `upsert()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/encrypted-index/upsert) > > API reference for `Upsert()` in Go # Full-Text and Hybrid Search Source: https://docs.cyborg.co/versions/latest/service/guides/data-operations/bm25-search CyborgDB supports **BM25 full-text search** on designated metadata fields, alongside vector search. This unlocks two new query paths on top of the existing vector query: | Query | Method | Ranks by | | - | - | - | | Full text (no vector) | `query_metadata()` with `text` | BM25 score | | Full text + metadata (no vector) | `query_metadata()` with `text` + `filters` | BM25 score over the filter's survivors | | Hybrid (BM25 + vector) | `query()` with `query_vectors` + `text` | weighted RRF of BM25 rank + vector rank | | Three-way (vector + BM25 + metadata) | `query()` with `query_vectors` + `text` + `filters` | weighted RRF over the filter's survivors | Text-search data is stored encrypted: the backing store never sees a readable term, which terms a document contains, or how many documents contain a given term. ## How It Works * **BM25 is enabled by designating fields, not by a flag.** An index with at least one `full_text` field supports text search. An index with none has no full-text overhead. * **Text is sourced from metadata field values**, not from `contents`. `contents` stays arbitrary binary and is never analyzed. * **English only (currently)**: lowercase → split on non-alphanumeric → stopword filter → Porter2 stem. * **Designations are fixed for the index's lifetime.** They currently cannot be changed after creation. * **Fusion is by rank, not score.** BM25 relevance and vector distance have no common unit, so hybrid queries fuse *positions*: `score(d) = Σ w_leg / (k + rank_leg(d))`. `alpha` sets the leg weights, `rrf_k` damps how much a single leg's top hit dominates, and `window_mult` sets how deep each leg retrieves before fusing. ## Designating Fields At index creation, mark fields as `full_text` in `metadata_schema` — or use the `text_fields` shorthand: ```python Python SDK icon="python" theme={null} from cyborgdb import Client client = Client(base_url='http://localhost:8000', api_key='your-api-key') index_key = client.generate_key(save=True) # Shorthand: text_fields=[...] marks each field full_text=True. index = client.create_index( 'articles', index_key=index_key, dimension=4, text_fields=['title', 'body'], ) ``` ```javascript JavaScript SDK icon="js" theme={null} import { Client } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); const indexKey = client.generateKey(); // Shorthand: textFields marks each field fullText: true. const index = await client.createIndex({ indexName: 'articles', indexKey, dimension: 4, textFields: ['title', 'body'], }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { Client, EncryptedIndex } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); const indexKey: Uint8Array = client.generateKey(); // Shorthand: textFields marks each field fullText: true. const index: EncryptedIndex = await client.createIndex({ indexName: 'articles', indexKey, dimension: 4, textFields: ['title', 'body'], }); ``` ```go Go SDK icon="golang" theme={null} client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } key, err := cyborgdb.GenerateKey() if err != nil { log.Fatal(err) } // Shorthand: TextFields marks each field full_text=true. dimension := int32(4) params := &cyborgdb.CreateIndexParams{ IndexName: "articles", IndexKey: key, Dimension: &dimension, TextFields: []string{"title", "body"}, } index, err := client.CreateIndex(context.Background(), params) if err != nil { log.Fatal(err) } ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "articles", "index_key": "your_64_character_hex_key_here", "dimension": 4, "text_fields": ["title", "body"] }' ``` The longhand — `metadata_schema={"title": {"full_text": true}}` — is equivalent, and is what you need when other fields want policy too (e.g. a `filterable` or `pattern` field alongside). The BM25 scoring constants can also be tuned at creation via `bm25_k1` (term-frequency saturation, default `1.2`) and `bm25_b` (length normalization, default `0.75`); both require at least one `full_text` field. > [!NOTE] > > `full_text: true` implies `filterable: false` and is incompatible with `pattern: true` — a field is either analyzed for BM25 or exact-match indexed, never both. Writing an explicit `filterable: true` alongside `full_text: true` is rejected. If a field needs to be both text-searchable and exact-match filterable, store it twice under two names. ## Ingesting Text Nothing special is needed at upsert — text comes from the designated fields' metadata values: ```python Python SDK icon="python" theme={null} index.upsert([ { 'id': 'a1', 'vector': [0.1, 0.2, 0.3, 0.4], 'metadata': { 'title': 'Encrypted vector search', 'body': 'Searching over encrypted embeddings without decrypting them.', 'author': 'ann', }, }, ]) ``` ```javascript JavaScript SDK icon="js" theme={null} await index.upsert([ { id: 'a1', vector: [0.1, 0.2, 0.3, 0.4], metadata: { title: 'Encrypted vector search', body: 'Searching over encrypted embeddings without decrypting them.', author: 'ann', }, }, ]); ``` ```typescript TypeScript SDK icon="code" theme={null} await index.upsert([ { id: 'a1', vector: [0.1, 0.2, 0.3, 0.4], metadata: { title: 'Encrypted vector search', body: 'Searching over encrypted embeddings without decrypting them.', author: 'ann', }, }, ]); ``` ```go Go SDK icon="golang" theme={null} items := cyborgdb.VectorItems{ { Id: "a1", Vector: []float32{0.1, 0.2, 0.3, 0.4}, Metadata: map[string]interface{}{ "title": "Encrypted vector search", "body": "Searching over encrypted embeddings without decrypting them.", "author": "ann", }, }, } err := index.Upsert(context.Background(), items) if err != nil { log.Fatal(err) } ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/upsert" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "articles", "index_key": "your_64_character_hex_key_here", "items": [ { "id": "a1", "vector": [0.1, 0.2, 0.3, 0.4], "metadata": { "title": "Encrypted vector search", "body": "Searching over encrypted embeddings without decrypting them.", "author": "ann" } } ] }' ``` A `full_text` field's value must be a string. Items where the field is missing or non-string (including a list of strings) are skipped for that field — the upsert still succeeds. An empty or all-stopword value is legal and simply contributes no terms. ## Full-Text Query — No Vector Pass `text` to `query_metadata()` to run a pure BM25 search. Rows come back as `{"id", "score"}`, descending by BM25 score: ```python Python SDK icon="python" theme={null} results = index.query_metadata(text='encrypted search', top_k=10) print(results) # [{"id": "a1", "score": 2.63}, {"id": "a2", "score": 1.15}, ...] ``` ```javascript JavaScript SDK icon="js" theme={null} const results = await index.queryMetadata({ text: 'encrypted search', topK: 10 }); console.log(results); // [{id: "a1", score: 2.63}, {id: "a2", score: 1.15}, ...] ``` ```typescript TypeScript SDK icon="code" theme={null} import { MetadataResult } from 'cyborgdb'; const results: MetadataResult[] = await index.queryMetadata({ text: 'encrypted search', topK: 10, }); console.log(results); // [{id: "a1", score: 2.63}, {id: "a2", score: 1.15}, ...] ``` ```go Go SDK icon="golang" theme={null} resp, err := index.QueryMetadata(context.Background(), cyborgdb.QueryMetadataParams{ Text: cyborgdb.String("encrypted search"), TopK: 10, }) if err != nil { log.Fatal(err) } for _, row := range resp.Results { fmt.Println(row.Id, row.GetScore()) } // a1 2.63 // a2 1.15 ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/query_metadata" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "articles", "index_key": "your_64_character_hex_key_here", "text": "encrypted search", "top_k": 10 }' ``` `score` is present only when there is one — a filter-only `query_metadata()` call has nothing to score, so the key is absent rather than null. Three optional knobs shape the text search: * `text_fields` — search only some of the designated fields (naming a non-`full_text` field is rejected). * `text_field_weights` — per-field weights, parallel to the searched fields (name them explicitly when weighting). * `require_all_terms` — require every term to match (AND) instead of any (OR, the default). ```python Python SDK icon="python" theme={null} # Weight title matches double, and require every term results = index.query_metadata( text='encrypted search', text_fields=['title', 'body'], text_field_weights=[2.0, 1.0], require_all_terms=True, ) ``` ```javascript JavaScript SDK icon="js" theme={null} // Weight title matches double, and require every term const results = await index.queryMetadata({ text: 'encrypted search', textFields: ['title', 'body'], textFieldWeights: [2.0, 1.0], requireAllTerms: true, }); ``` ```typescript TypeScript SDK icon="code" theme={null} // Weight title matches double, and require every term const results: MetadataResult[] = await index.queryMetadata({ text: 'encrypted search', textFields: ['title', 'body'], textFieldWeights: [2.0, 1.0], requireAllTerms: true, }); ``` ```go Go SDK icon="golang" theme={null} // Weight title matches double, and require every term resp, err := index.QueryMetadata(context.Background(), cyborgdb.QueryMetadataParams{ Text: cyborgdb.String("encrypted search"), TextFields: []string{"title", "body"}, TextFieldWeights: []float32{2.0, 1.0}, RequireAllTerms: cyborgdb.Bool(true), }) ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/query_metadata" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "articles", "index_key": "your_64_character_hex_key_here", "text": "encrypted search", "text_fields": ["title", "body"], "text_field_weights": [2.0, 1.0], "require_all_terms": true }' ``` A `filters` argument given alongside `text` acts as a **pre-filter** — it resolves first, then only its survivors are scored. Document frequency and per-field corpus stats stay corpus-global, so a document's score never depends on the filter. `order_by` is not supported together with `text` — text results rank by score. ## Hybrid Query — BM25 + Vector Set `text` on `query()` to fuse BM25 with vector similarity: ```python Python SDK icon="python" theme={null} query_vector = [0.5, 0.9, 0.2, 0.7] results = index.query( query_vectors=query_vector, text='encrypted search', top_k=10, alpha=0.5, # 0 = pure BM25, 1 = pure vector; default 0.5 include=['metadata'], ) print(results) # [{"id": "a1", "score": 0.0161, "metadata": {...}}, ...] ``` ```javascript JavaScript SDK icon="js" theme={null} const queryVector = [0.5, 0.9, 0.2, 0.7]; const response = await index.query({ queryVectors: queryVector, text: 'encrypted search', topK: 10, alpha: 0.5, // 0 = pure BM25, 1 = pure vector; default 0.5 include: ['metadata'], }); console.log(response.results); // [{id: "a1", score: 0.0161, metadata: {...}}, ...] ``` ```typescript TypeScript SDK icon="code" theme={null} import { QueryResponse } from 'cyborgdb'; const queryVector: number[] = [0.5, 0.9, 0.2, 0.7]; const params = { queryVectors: queryVector, text: 'encrypted search', topK: 10, alpha: 0.5, // 0 = pure BM25, 1 = pure vector; default 0.5 include: ['metadata'], }; const response: QueryResponse = await index.query(params); console.log(response.results); // [{id: "a1", score: 0.0161, metadata: {...}}, ...] ``` ```go Go SDK icon="golang" theme={null} queryVector := []float32{0.5, 0.9, 0.2, 0.7} params := cyborgdb.QueryParams{ QueryVector: queryVector, Text: cyborgdb.String("encrypted search"), TopK: int32(10), Alpha: cyborgdb.Float64(0.5), // 0 = pure BM25, 1 = pure vector Include: []string{"metadata"}, } results, err := index.Query(context.Background(), params) if err != nil { log.Fatal(err) } fmt.Println(results) // [{"id": "a1", "score": 0.0161, "metadata": {...}}, ...] ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "articles", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.5, 0.9, 0.2, 0.7], "text": "encrypted search", "top_k": 10, "alpha": 0.5, "include": ["metadata"] }' ``` Hybrid results carry `score` (fused relevance, larger = better) and **never** `distance` — a document matched by text alone has no vector distance to report. A query vector is required even at `alpha=0` — it fixes the batch shape. For text search with no vector, use `query_metadata()` with `text`. ## Three-Way Query — Vector + BM25 + Metadata Adding `filters` on top of a hybrid query composes all three legs in one request. The filter is resolved **once**, before retrieval, and the surviving IDs constrain both the vector and BM25 legs — so both rankings are computed over the same filtered candidate set, then fused by RRF. A filter that matches nothing short-circuits to an empty result without running either leg: ```python Python SDK icon="python" theme={null} results = index.query( query_vectors=query_vector, text='encrypted search', filters={'author': 'ann'}, # resolved first; both legs rank only its survivors top_k=10, alpha=0.5, include=['metadata'], ) print(results) # [{"id": "a1", "score": 0.0161, "metadata": {"author": "ann", ...}}, ...] ``` ```javascript JavaScript SDK icon="js" theme={null} const response = await index.query({ queryVectors: queryVector, text: 'encrypted search', filters: { author: 'ann' }, // resolved first; both legs rank only its survivors topK: 10, alpha: 0.5, include: ['metadata'], }); console.log(response.results); // [{id: "a1", score: 0.0161, metadata: {author: "ann", ...}}, ...] ``` ```typescript TypeScript SDK icon="code" theme={null} import { QueryResponse } from 'cyborgdb'; const params = { queryVectors: queryVector, text: 'encrypted search', filters: { author: 'ann' }, // resolved first; both legs rank only its survivors topK: 10, alpha: 0.5, include: ['metadata'], }; const response: QueryResponse = await index.query(params); console.log(response.results); // [{id: "a1", score: 0.0161, metadata: {author: "ann", ...}}, ...] ``` ```go Go SDK icon="golang" theme={null} params := cyborgdb.QueryParams{ QueryVector: queryVector, Text: cyborgdb.String("encrypted search"), // Resolved first; both legs rank only its survivors. Filters: map[string]interface{}{"author": "ann"}, TopK: int32(10), Alpha: cyborgdb.Float64(0.5), Include: []string{"metadata"}, } results, err := index.Query(context.Background(), params) if err != nil { log.Fatal(err) } fmt.Println(results) // [{"id": "a1", "score": 0.0161, "metadata": {"author": "ann", ...}}, ...] ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "articles", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.5, 0.9, 0.2, 0.7], "text": "encrypted search", "filters": {"author": "ann"}, "top_k": 10, "alpha": 0.5, "include": ["metadata"] }' ``` `alpha` still applies: `0` reduces the query to BM25 + metadata, `1` to vector + metadata, and either exact endpoint skips the dead leg's retrieval entirely. For BM25 + metadata with no vector at all, use `query_metadata()` with `text` and `filters` instead. > [!NOTE] > > Any query with `text` set accepts only filters the metadata index can resolve exactly. `$regex` on a non-`pattern` field, and any predicate on an explicitly non-`filterable` field, work in a pure `query()` but are rejected once `text` is set — otherwise those filters could not be applied to the full-text results, and they would be silently returned unfiltered. In the example above, `author` works because it is an ordinary filterable field, not a `full_text` one. ## Tuning | Knob | Set at | Raise it to | Lower it to | | - | - | - | - | | `bm25_k1` (1.2) | index creation | let repeated terms keep adding score | saturate sooner; 0 = presence/absence only | | `bm25_b` (0.75) | index creation | punish long documents harder; 1 = full normalization | ignore length; 0 = no normalization | | `alpha` (0.5) | per query | favor vector similarity | favor keyword relevance | | `rrf_k` (60) | per query | reward cross-leg agreement further down each list | trust each leg's top hits more | | `window_mult` (3) | per query | let documents deep in both legs still win on fusion | retrieve less per leg | Two non-obvious properties worth knowing before tuning: * **No positive `rrf_k` lets one leg's rank-1 outrank two legs' rank-2.** If you want a single leg to dominate, use `alpha`, not `rrf_k`. At `alpha=0` or `alpha=1` the dead leg's retrieval is skipped entirely. * **`rrf_k` is only meaningful as deep as the legs actually retrieved.** At `window_mult=3` and `top_k=10` each leg is 30 deep, and every value of `rrf_k` above \~28 makes the same decision — sweeping `rrf_k` alone at a shallow window will look like the knob does nothing. Sweep the two together. ## Reading Back the Config The recorded BM25 config — `k1`, `b`, and the `analyzer_version` the corpus was indexed with — is reported on the index handle, or `null` when the index has no `full_text` field: ```python Python SDK icon="python" theme={null} print(index.bm25) # {"k1": 1.2, "b": 0.75, "analyzer_version": "en/1;sw=...;snowball-english-utf8-3.0.1"} print(index.metadata_schema) # {"title": {"filterable": False, "pattern": False, "full_text": True}, ...} ``` ```javascript JavaScript SDK icon="js" theme={null} console.log(await index.bm25()); // {k1: 1.2, b: 0.75, analyzerVersion: "en/1;sw=...;snowball-english-utf8-3.0.1"} console.log(await index.metadataSchema()); // {title: {filterable: false, pattern: false, fullText: true}, ...} ``` ```typescript TypeScript SDK icon="code" theme={null} console.log(await index.bm25()); // {k1: 1.2, b: 0.75, analyzerVersion: "en/1;sw=...;snowball-english-utf8-3.0.1"} console.log(await index.metadataSchema()); // {title: {filterable: false, pattern: false, fullText: true}, ...} ``` ```go Go SDK icon="golang" theme={null} bm25, err := index.BM25(context.Background()) if err != nil { log.Fatal(err) } if bm25 != nil { fmt.Println(bm25.K1, bm25.B, bm25.GetAnalyzerVersion()) } schema, err := index.MetadataSchema(context.Background()) if err != nil { log.Fatal(err) } fmt.Println(schema) ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/indexes/describe" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "articles", "index_key": "your_64_character_hex_key_here" }' # Response includes: # "metadata_schema": {"title": {"filterable": false, "pattern": false, "full_text": true}, ...}, # "bm25": {"k1": 1.2, "b": 0.75, "analyzer_version": "en/1;sw=...;snowball-english-utf8-3.0.1"} ``` ## Constraints and Gotchas * **`full_text` + explicit `filterable: true` is an error**, and **`full_text` + `pattern: true` is an error always**. If you need a field both text-searchable and exact-match filterable, store it twice under two names. * **Designations are fixed for the index's lifetime.** They currently cannot be changed after creation. * **`order_by` cannot be combined with `text`.** Text results rank by score. * **Only single string values are analyzed.** A `full_text` field holding a number, boolean, object, or a *list of strings* is skipped for that item — join multi-part text into one string before upserting. * **Not currently supported:** phrase queries, `NOT`/exclusion, nested boolean expressions, non-English analysis, and dual-indexing a field as both analyzed and exact-match. * **The analyzer is versioned.** The pipeline version, stopword-list hash, and stemmer identity are stamped into the index at creation (see `analyzer_version` above). Opening an index with a build whose analyzer differs is a loud error, not silent recall loss. * **Multi-tenant guidance:** use index-per-tenant. Corpus statistics are per index, so co-mingling tenants behind a `tenant_id` filter gives every tenant blended term rarity — BM25 statistics are deliberately global and never scoped to a filtered subset. ## Common Errors Create-time schema violations are rejected by request validation (HTTP `422`); query-time and cross-parameter violations are enforced by the index core (HTTP `400`). The SDKs surface both as errors/exceptions with the reason. | Error | Cause | Fix | | - | - | - | | `text query requires an index with at least one full_text field` | No field designated | Designate at creation; it cannot be added later | | text query names a field that is not `full_text` | `text_fields` naming an undesignated field | Use a designated field, or drop the argument to search all | | text knobs require non-empty query text | `text_fields` / `text_field_weights` / `require_all_terms` set without `text` | Pass `text`, or drop the knob | | `full_text=true` is incompatible with an explicit `filterable=true` | Both written explicitly | Drop `filterable`, or use two fields | | `bm25_k1` / `bm25_b` require at least one `full_text` field | Tuning an index with no text | Designate a field, or drop the parameters | | `order_by is not supported together with query text` | Two ordering authorities | Drop `order_by` | | `rrf_k must be > 0` / `window_mult must be >= 1` | Explicit `0` passed | Omit the parameter for the default | | `hybrid query cannot filter on a non-indexed metadata field` | Filter on a non-`filterable` / non-`pattern` field with `text` set | Move the filter to a `filterable` / `pattern` field, or drop `text` | | Empty result, no error | Text analyzed to no terms (empty, punctuation, all stopwords), or no term matched | Expected: degenerate input is defined-empty | ## API Reference For more information on full-text and hybrid search, refer to the API reference: > [card] [REST API: Query](../../rest-api/encrypted-index/query) > > Hybrid query on `/v1/vectors/query` > [card] [REST API: Query Metadata](../../rest-api/encrypted-index/query-metadata) > > Full-text query on `/v1/vectors/query_metadata` > [card] [Python SDK Reference](../../python-sdk/encrypted-index/query) > > API reference for `query()` and `query_metadata()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/encrypted-index/query) > > API reference for `query()` and `queryMetadata()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/encrypted-index/query) > > API reference for `Query()` and `QueryMetadata()` in Go > [card] [Create Index (REST API)](../../rest-api/client/create-index) > > Designating `full_text` fields at creation # Delete Encrypted Items Source: https://docs.cyborg.co/versions/latest/service/guides/data-operations/delete-items You can delete items from an encrypted index using `delete()`: ```python Python SDK icon="python" theme={null} # IDs of items to delete ids_to_delete = ["item1", "item2", "item3"] # Delete items from the encrypted index index.delete(ids_to_delete) ``` ```javascript JavaScript SDK icon="js" theme={null} // IDs of items to delete const idsToDelete = ["item1", "item2", "item3"]; // Delete items from the encrypted index await index.delete({ ids: idsToDelete }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { DeleteParams } from 'cyborgdb'; // IDs of items to delete const idsToDelete: string[] = ["item1", "item2", "item3"]; // Delete items from the encrypted index const params: DeleteParams = { ids: idsToDelete }; await index.delete(params); ``` ```go Go SDK icon="golang" theme={null} // IDs of items to delete idsToDelete := []string{"item1", "item2", "item3"} // Delete items from the encrypted index err := index.Delete(context.Background(), idsToDelete) if err != nil { log.Fatal(err) } ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/delete" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "ids": ["item1", "item2", "item3"] }' ``` > [!WARNING] > > This operation is irreversible. Once you delete an item, you cannot recover it. ## API Reference For more information on deleting items from an encrypted index, refer to the API reference: > [card] [REST API Reference](../../rest-api/encrypted-index/delete) > > REST API reference for `/v1/vectors/delete` > [card] [Python SDK Reference](../../python-sdk/encrypted-index/delete) > > API reference for `delete()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/encrypted-index/delete) > > API reference for `delete()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/encrypted-index/delete) > > API reference for `Delete()` in Go # Get Encrypted Items Source: https://docs.cyborg.co/versions/latest/service/guides/data-operations/get-items You can retrieve specific items from the index by their IDs using the `get()` method: ```python Python SDK icon="python" theme={null} # IDs of items to retrieve ids = ["item_20", "item_11"] include = ["contents", "metadata"] # Retrieve items from the encrypted index items = index.get(ids, include) print(items) # Example items (contents returned in their original format - string or bytes) # [{"id": "item_20", "contents": "Hello, World!", "metadata": {"type": "txt"}}, # {"id": "item_11", "contents": "Hello, Cyborg!", "metadata": {"type": "md"}}] ``` ```javascript JavaScript SDK icon="js" theme={null} // IDs of items to retrieve const ids = ["item_20", "item_11"]; const include = ["contents", "metadata"]; // Retrieve items from the encrypted index const items = await index.get({ ids, include }); console.log(items); // Example items (contents returned as decoded UTF-8 strings) // [{id: "item_20", contents: "Hello, World!", metadata: {type: "txt"}}, // {id: "item_11", contents: "Hello, Cyborg!", metadata: {type: "md"}}] ``` ```typescript TypeScript SDK icon="code" theme={null} import { GetRequest, GetResultItem } from 'cyborgdb'; // IDs of items to retrieve const ids: string[] = ["item_20", "item_11"]; const include: string[] = ["contents", "metadata"]; // Retrieve items from the encrypted index const params: GetRequest = { ids, include }; const items: GetResultItem[] = await index.get(params); console.log(items); // Example items (contents returned as decoded UTF-8 strings) // [{id: "item_20", contents: "Hello, World!", metadata: {type: "txt"}}, // {id: "item_11", contents: "Hello, Cyborg!", metadata: {type: "md"}}] ``` ```go Go SDK icon="golang" theme={null} // IDs of items to retrieve ids := []string{"item_20", "item_11"} include := []string{"contents", "metadata"} // Retrieve items from the encrypted index items, err := index.Get(context.Background(), ids, include) if err != nil { log.Fatal(err) } fmt.Println(items) // Example items (contents returned as string) // [{"id": "item_20", "contents": "Hello, World!", "metadata": {"type": "txt"}}, // {"id": "item_11", "contents": "Hello, Cyborg!", "metadata": {"type": "md"}}] ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/get" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "ids": ["item_20", "item_11"], "include": ["contents", "metadata"] }' ``` ## Include Fields You can specify which fields to include in the response: * **`vector`**: The vector data itself * **`contents`**: Content associated with the vector (returned in original format) * **`metadata`**: Structured metadata object > [!TIP] > > In Python, the `contents` field is returned in its original format (string or bytes) as it was stored. String contents remain strings, and bytes contents remain bytes after decryption. In JavaScript/TypeScript, contents are returned as decoded UTF-8 strings. In Go, contents are returned as string. If you don't specify `include`, the default is `["vector", "contents", "metadata"]`. Note: `id` is always included in results. ## API Reference For more information on getting items from an encrypted index, refer to the API reference: > [card] [REST API Reference](../../rest-api/encrypted-index/get) > > REST API reference for `/v1/vectors/get` > [card] [Python SDK Reference](../../python-sdk/encrypted-index/get) > > API reference for `get()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/encrypted-index/get) > > API reference for `get()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/encrypted-index/get) > > API reference for `Get()` in Go # Metadata Filtering Source: https://docs.cyborg.co/versions/latest/service/guides/data-operations/metadata-filtering CyborgDB supports metadata tagging and filtering, enabling fine-grained search filters in addition to encrypted vector search. Metadata, like vectors, are end-to-end encrypted and never exposed in plaintext outside of the client. ## Supported Metadata The following metadata types are supported: * Boolean * String * List of strings * Numbers (will be stored as fp64) ## Adding Items with Metadata To add items with metadata tags, you can pass a dictionary of key-value pairs to the `metadata` field during `upsert`: ```python Python SDK icon="python" theme={null} # Example data data = [ {"id": "item_1", "vector": [0.1, 0.1, 0.1, 0.1], "metadata": {"category": "dog"}}, {"id": "item_2", "vector": [0.2, 0.2, 0.2, 0.2], "metadata": {"category": "cat"}} ] # Upsert data with metadata index.upsert(data) ``` ```javascript JavaScript SDK icon="js" theme={null} // Example data const data = [ {id: "item_1", vector: [0.1, 0.1, 0.1, 0.1], metadata: {category: "dog"}}, {id: "item_2", vector: [0.2, 0.2, 0.2, 0.2], metadata: {category: "cat"}} ]; // Upsert data with metadata await index.upsert({ items: data }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { VectorItem } from 'cyborgdb'; // Example data const data: VectorItem[] = [ {id: "item_1", vector: [0.1, 0.1, 0.1, 0.1], metadata: {category: "dog"}}, {id: "item_2", vector: [0.2, 0.2, 0.2, 0.2], metadata: {category: "cat"}} ]; // Upsert data with metadata await index.upsert({ items: data }); ``` ```go Go SDK icon="golang" theme={null} package main import ( "context" "github.com/cyborginc/cyborgdb-go" ) // Example data items := cyborgdb.VectorItems{ { Id: "item_1", Vector: []float32{0.1, 0.1, 0.1, 0.1}, Metadata: map[string]interface{}{"category": "dog"}, }, { Id: "item_2", Vector: []float32{0.2, 0.2, 0.2, 0.2}, Metadata: map[string]interface{}{"category": "cat"}, }, } // Upsert data with metadata err := index.Upsert(context.Background(), items) ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/upsert" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "items": [ { "id": "item_1", "vector": [0.1, 0.1, 0.1, 0.1], "metadata": {"category": "dog"} }, { "id": "item_2", "vector": [0.2, 0.2, 0.2, 0.2], "metadata": {"category": "cat"} } ] }' ``` This metadata will be encrypted and stored in the index. > [!TIP] > > Metadata field names and string values are **case-sensitive**. Ensure that the metadata field names and values are consistent when filtering queries. ## Filtering Queries with Metadata CyborgDB supports a subset of [MongoDB's Query and Projection Operators](https://www.mongodb.com/docs/manual/reference/operator/query/). For more details, see [Metadata Query Operators](#metadata-query-operators) To filter a query with metadata, you can pass a dictionary of filters to the `filters` field during `query`: ```python Python SDK icon="python" theme={null} # Example query query_vector = [0.5, 0.9, 0.2, 0.7] top_k = 10 # Example filters filters = { "category": {"$in": ["dog", "cat"]} # Will match either 'dog' or 'cat' } # Perform query results = index.query( query_vectors=query_vector, top_k=top_k, filters=filters ) ``` ```javascript JavaScript SDK icon="js" theme={null} // Example query const queryVectors = [0.5, 0.9, 0.2, 0.7]; const topK = 10; // Example filters const filters = { category: {$in: ["dog", "cat"]} // Will match either 'dog' or 'cat' }; // Perform query const results = await index.query({ queryVectors, topK, filters }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { QueryResponse, FilterExpression } from 'cyborgdb'; // Example query const queryVectors: number[] = [0.5, 0.9, 0.2, 0.7]; const topK: number = 10; // Example filters const filters: FilterExpression = { category: {$in: ["dog", "cat"]} // Will match either 'dog' or 'cat' }; // Perform query const params = { queryVectors, topK, filters }; const response: QueryResponse = await index.query(params); ``` ```go Go SDK icon="golang" theme={null} // Example query queryVector := []float32{0.5, 0.9, 0.2, 0.7} topK := int32(10) // Example filters filters := map[string]interface{}{ "category": map[string]interface{}{"$in": []string{"dog", "cat"}}, // Will match either 'dog' or 'cat' } // Perform query results, err := index.Query(context.Background(), cyborgdb.QueryParams{ QueryVector: queryVector, TopK: topK, Filters: filters, }) ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.5, 0.9, 0.2, 0.7], "top_k": 10, "filters": { "category": {"$in": ["dog", "cat"]} } }' ``` ## Metadata Indexing By default, every metadata field is indexed using encrypted indexing, so filters on indexed fields are resolved from the index and are fast. You can opt individual fields out of indexing with `metadata_schema` at index creation (see [Metadata schema](../../python-sdk/client/create-index#metadata-schema)). Filters on non-indexed fields still work, but they are evaluated after decryption and are slower, as are `$regex` / `$contains` filters on fields not indexed for pattern matching. ## Metadata Query Operators CyborgDB supports a subset of [MongoDB's Query and Projection Operators](https://www.mongodb.com/docs/manual/reference/operator/query/). Specifically, the following operators are supported: | Filter | Types | Description | | :-: | :-: | - | | `$and` | `array` | Logical AND - matches vectors that satisfy all conditions in the array | | `$or` | `array` | Logical OR - matches vectors that satisfy at least one condition in the array | | `$not` | `object` | Logical NOT - matches vectors that do not satisfy the condition | | `$exists` | `boolean` | Matches vectors that have (or do not have) the specified field | | `$eq` | `Boolean`, `Number`, `String` | Matches vectors with the metadata that is equal to the filter value | | `$ne` | `Boolean`, `Number`, `String` | Matches vectors with the metadata that is not equal to the filter value | | `$in` | `Number`, `String` | Matches vectors with metadata that is in the filter array | | `$nin` | `Number`, `String` | Matches vectors with metadata that is not in the filter array | | `$gt` | `Number` | Matches vectors with metadata that is greater than the filter value | | `$gte` | `Number` | Matches vectors with metadata that is greater than or equal to the filter value | | `$lt` | `Number` | Matches vectors with metadata that is less than the filter value | | `$lte` | `Number` | Matches vectors with metadata that is less than or equal to the filter value | # Query Encrypted Index Source: https://docs.cyborg.co/versions/latest/service/guides/data-operations/query Once you've added items to an encrypted index, you can query the index to retrieve the items that match a given query. This is done via `query()`: ```python Python SDK icon="python" theme={null} # Example query query_vector = [0.5, 0.9, 0.2, 0.7] top_k = 10 # Perform query results = index.query(query_vectors=query_vector, top_k=top_k) print(results) # Example results (flat list for single query) # [{"id": "item_12", "distance": 0.01}, {"id": "item_7", "distance": 0.04}, ...] ``` ```javascript JavaScript SDK icon="js" theme={null} // Example query const queryVectors = [0.5, 0.9, 0.2, 0.7]; const topK = 10; // Perform query const response = await index.query({ queryVectors, topK }); console.log(response.results); // Example results (flat list for single query) // [{id: "item_12", distance: 0.01}, {id: "item_7", distance: 0.04}, ...] ``` ```typescript TypeScript SDK icon="code" theme={null} import { QueryResponse } from 'cyborgdb'; // Example query const queryVectors: number[] = [0.5, 0.9, 0.2, 0.7]; const topK: number = 10; // Perform query const params = { queryVectors, topK }; const response: QueryResponse = await index.query(params); console.log(response.results); // Example results (flat list for single query) // [{id: "item_12", distance: 0.01}, {id: "item_7", distance: 0.04}, ...] ``` ```go Go SDK icon="golang" theme={null} // Example query queryVector := []float32{0.5, 0.9, 0.2, 0.7} params := cyborgdb.QueryParams{ QueryVector: queryVector, TopK: int32(10), Include: []string{"distance"}, } // Perform query results, err := index.Query(context.Background(), params) if err != nil { log.Fatal(err) } fmt.Println(results) // Example results (flat list for single query) // [{"id": "item_12", "distance": 0.01}, {"id": "item_7", "distance": 0.04}, ...] ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.5, 0.9, 0.2, 0.7], "top_k": 10 }' ``` ## Query Parameters You can specify additional parameters for the query, such as: * `top_k`: the number of results to return. Default: `100`. * `n_probes`: the number of clusters to search for each query vector. Default: `None` (auto-determined by server). * `filters`: metadata filters to apply to the query (dictionary format). Default: `None`. * `include`: item fields to return (e.g., `["distance", "metadata"]`). Default: `[]` (only `id` is returned). Note: `id` is always included. * `greedy`: whether to use faster approximate search. Default: `None` (server default: `false`). ```python Python SDK icon="python" theme={null} # Example query with parameters query_vector = [0.5, 0.9, 0.2, 0.7] top_k = 10 n_probes = 5 filters = {"age": {"$gt": 18}} include = ["distance", "metadata"] # Perform query results = index.query( query_vectors=query_vector, top_k=top_k, n_probes=n_probes, filters=filters, include=include ) print(results) # Example results (flat list for single query) # [{"id": "item_12", "distance": 0.01, "metadata": {"age": 25}}, ...] ``` ```javascript JavaScript SDK icon="js" theme={null} // Example query with parameters const queryVectors = [0.5, 0.9, 0.2, 0.7]; const topK = 10; const nProbes = 5; const filters = {age: {$gt: 18}}; const include = ["distance", "metadata"]; // Perform query const response = await index.query({ queryVectors, topK, nProbes, filters, include }); console.log(response.results); // Example results (flat list for single query) // [{id: "item_12", distance: 0.01, metadata: {age: 25}}, ...] ``` ```typescript TypeScript SDK icon="code" theme={null} import { QueryResponse, FilterExpression } from 'cyborgdb'; // Example query with parameters const queryVectors: number[] = [0.5, 0.9, 0.2, 0.7]; const topK: number = 10; const nProbes: number = 5; const filters: FilterExpression = {age: {$gt: 18}}; const include: string[] = ["distance", "metadata"]; // Perform query const params = { queryVectors, topK, nProbes, filters, include }; const response: QueryResponse = await index.query(params); console.log(response.results); // Example results (flat list for single query) // [{id: "item_12", distance: 0.01, metadata: {age: 25}}, ...] ``` ```go Go SDK icon="golang" theme={null} // Example query with parameters queryVector := []float32{0.5, 0.9, 0.2, 0.7} nProbes := int32(5) params := cyborgdb.QueryParams{ QueryVector: queryVector, TopK: int32(10), NProbes: &nProbes, Filters: map[string]interface{}{"age": map[string]interface{}{"$gt": 18}}, Include: []string{"distance", "metadata"}, } // Perform query results, err := index.Query(context.Background(), params) if err != nil { log.Fatal(err) } fmt.Println(results) // Example results (flat list for single query) // [{"id": "item_12", "distance": 0.01, "metadata": {"age": 25}}, ...] ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.5, 0.9, 0.2, 0.7], "top_k": 10, "n_probes": 5, "filters": { "age": {"$gt": 18} }, "include": ["distance", "metadata"] }' ``` ## Batched Queries It's also possible to perform batch queries by passing multiple query vectors to `query()`: ```python Python SDK icon="python" theme={null} # Example batch query query_vectors = [[0.5, 0.9, 0.2, 0.7], [0.1, 0.3, 0.8, 0.6]] top_k = 10 # Perform batch query results = index.query( query_vectors=query_vectors, top_k=top_k ) print(results) # Returns nested results: one list per query vector # [[results_for_query_1], [results_for_query_2]] ``` ```javascript JavaScript SDK icon="js" theme={null} // Example batch query const queryVectors = [[0.5, 0.9, 0.2, 0.7], [0.1, 0.3, 0.8, 0.6]]; const topK = 10; // Perform batch query const response = await index.query({ queryVectors, topK }); console.log(response.results); // Returns nested results: one list per query vector // [[results_for_query_1], [results_for_query_2]] ``` ```typescript TypeScript SDK icon="code" theme={null} import { QueryResponse } from 'cyborgdb'; // Example batch query const queryVectors: number[][] = [[0.5, 0.9, 0.2, 0.7], [0.1, 0.3, 0.8, 0.6]]; const topK: number = 10; // Perform batch query const params = { queryVectors, topK }; const response: QueryResponse = await index.query(params); console.log(response.results); // Returns nested results: one list per query vector // [[results_for_query_1], [results_for_query_2]] ``` ```go Go SDK icon="golang" theme={null} // Example batch query queryVectors := [][]float32{ {0.5, 0.9, 0.2, 0.7}, {0.1, 0.3, 0.8, 0.6}, } params := cyborgdb.QueryParams{ BatchQueryVectors: queryVectors, TopK: int32(10), } // Perform batch query results, err := index.Query(context.Background(), params) if err != nil { log.Fatal(err) } fmt.Println(results) // Returns nested results: one list per query vector // [[results_for_query_1], [results_for_query_2]] ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [ [0.5, 0.9, 0.2, 0.7], [0.1, 0.3, 0.8, 0.6] ], "top_k": 10 }' ``` ## Querying with Metadata Filters You can filter query results based on metadata fields. For example, to filter items where the `age` field is greater than `18`, you can use the following filter: ```json theme={null} {"age": {"$gt": 18}} ``` This filter will return items where the `age` field is greater than `18`. You can also use other comparison operators such as `$lt`, `$gte`, `$lte`, `$eq`, and `$ne`. For more details on metadata filters, see the [Metadata Filtering](./metadata-filtering) guide. ## Automatic Embedding Generation > [!TIP] > > To use automatic embedding generation, use the [Docker Service](../intro/quickstart-docker) or install with `pip install "cyborgdb-service[embeddings]"` If you provided an `embedding_model` during index creation, you can automatically generate embeddings for queries by providing `query_contents` to the `query()` call: ```python Python SDK icon="python" theme={null} # ... index creation and embedding model setup embedding_model = "all-MiniLM-L6-v2" index = client.create_index("my_index", index_key=index_key, embedding_model=embedding_model) # ... Add items to the encrypted index ... # Example semantic query query_contents = "What is the capital of France?" top_k = 10 # Perform query results = index.query(query_contents=query_contents, top_k=top_k) ``` ```javascript JavaScript SDK icon="js" theme={null} // ... index creation and embedding model setup const embeddingModel = "all-MiniLM-L6-v2"; const index = await client.createIndex({ indexName: "my_index", indexKey, embeddingModel }); // ... Add items to the encrypted index ... // Example semantic query const queryContents = "What is the capital of France?"; const topK = 10; // Perform query const results = await index.query({ queryContents, topK }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { QueryResponse, EncryptedIndex } from 'cyborgdb'; // ... index creation and embedding model setup const embeddingModel: string = "all-MiniLM-L6-v2"; const index: EncryptedIndex = await client.createIndex({ indexName: "my_index", indexKey, embeddingModel }); // ... Add items to the encrypted index ... // Example semantic query const queryContents: string = "What is the capital of France?"; const topK: number = 10; // Perform query const params = { queryContents, topK }; const response: QueryResponse = await index.query(params); ``` ```go Go SDK icon="golang" theme={null} // Example semantic query queryContents := "What is the capital of France?" params := cyborgdb.QueryParams{ QueryContents: &queryContents, TopK: int32(10), } // Perform query results, err := index.Query(context.Background(), params) if err != nil { log.Fatal(err) } fmt.Println(results) ``` ```bash cURL icon="rectangle-terminal" theme={null} # For indexes with embedding_model curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_contents": "What is the capital of France?", "top_k": 10 }' ``` This feature allows you to perform semantic search using natural language queries. The service will automatically generate embeddings for your query text using the specified embedding model. ## Hybrid Search (BM25 + Vector) If the index was created with at least one `full_text` metadata field, passing `text` alongside `query_vectors` turns the query into a **hybrid** query: BM25 full-text ranking is fused with the vector ranking, and each result carries a `score` (fused relevance, larger = better) instead of a `distance`: ```python Python SDK icon="python" theme={null} # Requires an index created with text_fields=[...] (or full_text in metadata_schema) results = index.query( query_vectors=query_vector, text="encrypted search", top_k=10, alpha=0.5, # 0 = pure BM25, 1 = pure vector; default 0.5 ) # [{"id": "a1", "score": 0.0161}, ...] ``` ```javascript JavaScript SDK icon="js" theme={null} // Requires an index created with textFields (or fullText in metadataSchema) const queryVector = [0.5, 0.9, 0.2, 0.7]; const response = await index.query({ queryVectors: queryVector, text: "encrypted search", topK: 10, alpha: 0.5, // 0 = pure BM25, 1 = pure vector; default 0.5 }); // [{id: "a1", score: 0.0161}, ...] ``` ```typescript TypeScript SDK icon="code" theme={null} import { QueryResponse } from 'cyborgdb'; // Requires an index created with textFields (or fullText in metadataSchema) const queryVector: number[] = [0.5, 0.9, 0.2, 0.7]; const params = { queryVectors: queryVector, text: "encrypted search", topK: 10, alpha: 0.5, // 0 = pure BM25, 1 = pure vector; default 0.5 }; const response: QueryResponse = await index.query(params); // [{id: "a1", score: 0.0161}, ...] ``` ```go Go SDK icon="golang" theme={null} // Requires an index created with TextFields (or full_text in MetadataSchema) params := cyborgdb.QueryParams{ QueryVector: queryVector, Text: cyborgdb.String("encrypted search"), TopK: int32(10), Alpha: cyborgdb.Float64(0.5), // 0 = pure BM25, 1 = pure vector } results, err := index.Query(context.Background(), params) if err != nil { log.Fatal(err) } // [{"id": "a1", "score": 0.0161}, ...] ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.5, 0.9, 0.2, 0.7], "text": "encrypted search", "top_k": 10, "alpha": 0.5 }' ``` Adding `filters` on top composes a **three-way** query (vector + BM25 + metadata). The filter is resolved first, and both legs rank only its survivors: ```python Python SDK icon="python" theme={null} results = index.query( query_vectors=query_vector, text="encrypted search", filters={"author": "ann"}, # resolved first; constrains both legs top_k=10, ) ``` ```javascript JavaScript SDK icon="js" theme={null} const response = await index.query({ queryVectors: queryVector, text: "encrypted search", filters: { author: "ann" }, // resolved first; constrains both legs topK: 10, }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { QueryResponse } from 'cyborgdb'; const params = { queryVectors: queryVector, text: "encrypted search", filters: { author: "ann" }, // resolved first; constrains both legs topK: 10, }; const response: QueryResponse = await index.query(params); ``` ```go Go SDK icon="golang" theme={null} params := cyborgdb.QueryParams{ QueryVector: queryVector, Text: cyborgdb.String("encrypted search"), // Resolved first; constrains both legs. Filters: map[string]interface{}{"author": "ann"}, TopK: int32(10), } results, err := index.Query(context.Background(), params) if err != nil { log.Fatal(err) } ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.5, 0.9, 0.2, 0.7], "text": "encrypted search", "filters": {"author": "ann"}, "top_k": 10 }' ``` > [!NOTE] > > A query with `text` set accepts only filters the metadata index can resolve exactly — `$regex` on a non-`pattern` field, or any predicate on a `filterable: false` field, is rejected once `text` is present. For full-text search without a vector, field designation at index creation, tuning knobs (`alpha`, `rrf_k`, `window_mult`), and constraints, see the [Full-Text and Hybrid Search](./bm25-search) guide. ## Retrieving Items Post-Query In certain applications, such as RAG, it may be desirable to retrieve matching items after a query. This is possible via `get()`, which retrieves and decrypts item added via `upsert()`. For more details, see the [Get Items](./get-items) guide. ## Index Training for Optimal Performance Training improves query speed and accuracy. The CyborgDB service trains your index automatically once it holds enough vectors (more than 65,536 by default) and retrains it as it grows, so you usually don't need to train it yourself. Until the index is trained, queries use exhaustive search, which is fine for small datasets. You can also train explicitly, for example to choose training parameters. For more details, see [Training an Encrypted Index](../advanced/train-index). ## API Reference For more information on querying encrypted indexes, refer to the API reference: > [card] [REST API Reference](../../rest-api/encrypted-index/query) > > REST API reference for `/v1/vectors/query` > [card] [Python SDK Reference](../../python-sdk/encrypted-index/query) > > API reference for `query()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/encrypted-index/query) > > API reference for `query()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/encrypted-index/query) > > API reference for `Query()` in Go # Create Client Source: https://docs.cyborg.co/versions/latest/service/guides/encrypted-indexes/create-client The `Client` class provides an interface to connect to the CyborgDB service and manage encrypted indexes. It allows you to create, list, and interact with encrypted indexes through the CyborgDB REST API. ## Creating the Client To create the client, provide the service URL. An API key is only needed when the service has authentication enabled (see [API Key Authentication](#api-key-authentication) below); against a service running with auth disabled — the default — you can omit it: ```python Python SDK icon="python" theme={null} from cyborgdb import Client # Auth disabled (default): no API key needed client = Client(base_url='http://localhost:8000') # Auth enabled: pass the root key or a cdbk_ user token client = Client( base_url='http://localhost:8000', api_key='your-api-key' ) ``` ```javascript JavaScript SDK icon="js" theme={null} import { Client } from 'cyborgdb'; // Create client with API key const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { Client } from 'cyborgdb'; // Create client with API key const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); ``` ```go Go SDK icon="golang" theme={null} package main import ( "log" "github.com/cyborginc/cyborgdb-go" ) func main() { // Create client with API key client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } } ``` ```bash cURL icon="rectangle-terminal" theme={null} # Test connection with health check curl -X GET "http://localhost:8000/v1/health" # All subsequent API calls will use this pattern: # curl -H "X-API-Key: your-api-key" "http://localhost:8000/v1/..." ``` > [!TIP] > > If using the REST API directly, you don't need to create a client. You can make HTTP requests directly to the [service endpoints](../../rest-api/introduction). ## API Key Authentication Request authentication is controlled by the service, not the client. When the service is started with `CYBORGDB_SERVICE_ROOT_KEY` set, every request must carry a credential in the `X-API-Key` header: either that root key or a per-user `cdbk_` token minted under it. When the service runs without `CYBORGDB_SERVICE_ROOT_KEY` (the default), authentication is disabled and the `api_key` argument can be omitted. Pass the credential as `api_key` at construction and the client attaches the `X-API-Key` header to every request automatically. Note this is distinct from the service's `CYBORGDB_API_KEY` license key, which is not an authentication credential. See [Managing Keys](../advanced/managing-keys) for how to mint user tokens. ## Health Checking You can verify the service connection and health: ```python Python SDK icon="python" theme={null} # Check service health try: health = client.get_health() print("Service status:", health["status"]) except Exception as e: print(f"Service unavailable: {e}") ``` ```javascript JavaScript SDK icon="js" theme={null} // Check service health try { const health = await client.getHealth(); console.log('Service status:', health); } catch (error) { console.error('Service unavailable:', error.message); } ``` ```typescript TypeScript SDK icon="code" theme={null} // Check service health try { const health = await client.getHealth(); console.log('Service status:', health); } catch (error) { console.error('Service unavailable:', error.message); } ``` ```go Go SDK icon="golang" theme={null} package main import ( "context" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { // Create client client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } // Check service health ctx := context.Background() health, err := client.GetHealth(ctx) if err != nil { fmt.Printf("Service unavailable: %v\n", err) return } fmt.Printf("Service status: %+v\n", health) } ``` ```bash cURL icon="rectangle-terminal" theme={null} # Check service health (no API key required) curl -X GET "http://localhost:8000/v1/health" # Expected response: # {"status": "healthy", "api_version": "v1", "version": "0.18.0"} ``` ## API Reference For more information on the `Client` class, refer to the API Reference: > [card] [Python SDK Reference](../../python-sdk/client/client) > > API reference for `Client` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/client/client) > > API reference for `Client` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/client/client) > > API reference for `Client` in Go # Create a New Encrypted Index Source: https://docs.cyborg.co/versions/latest/service/guides/encrypted-indexes/create-index To create an encrypted index, you need to specify an index name (must be unique) and an index key: ```python Python SDK icon="python" theme={null} from cyborgdb import Client # Create a client client = Client( base_url='http://localhost:8000', api_key='your-api-key' ) # Generate an encryption key for the index index_key = client.generate_key(save=False) # Create an encrypted index index = client.create_index( index_name="my_index", index_key=index_key ) ``` ```javascript JavaScript SDK icon="js" theme={null} import { Client } from 'cyborgdb'; // Create a client const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); // Generate an encryption key for the index const indexKey = client.generateKey(); // Create an encrypted index const index = await client.createIndex({ indexName: "my_index", indexKey }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { Client, EncryptedIndex, CreateIndexRequest } from 'cyborgdb'; // Create a client const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); // Generate an encryption key for the index const indexKey: Uint8Array = client.generateKey(); // Create an encrypted index const params: CreateIndexRequest = { indexName: "my_index", indexKey }; const index: EncryptedIndex = await client.createIndex(params); ``` ```go Go SDK icon="golang" theme={null} package main import ( "context" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { // Create client client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } // Generate encryption key indexKey, err := cyborgdb.GenerateKey() if err != nil { log.Fatal(err) } // Create encrypted index params := &cyborgdb.CreateIndexParams{ IndexName: "my_index", IndexKey: indexKey, } ctx := context.Background() index, err := client.CreateIndex(ctx, params) if err != nil { log.Fatal(err) } log.Printf("Created index: %s", index.GetIndexName()) } ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' ``` This creates a new encrypted IVF index, the single index type CyborgDB Service uses. For details on configuration knobs (`dimension`, `metric`, `storage_precision`, `embedding_model`), see [Configure an Encrypted Index](../advanced/configure-index). > [!NOTE] > > There is no `index_config` argument and no `IndexIVFFlat` / `IndexIVFPQ` / `IndexIVFSQ` constructors. Optional parameters — `metric` (`"euclidean"`, `"squared_euclidean"`, `"cosine"`), `dimension`, `embedding_model`, `storage_precision`, and `kms_name` — are flat keyword arguments on `create_index`. See the [API Reference](#api-reference) for details. > [!WARNING] > > The example above creates a random 32 byte (256-bit) index key. > This is fine for evaluation purposes, but for production use, we recommend that you use an HSM or KMS solution. > For more details, see [Managing Encryption Keys](../advanced/managing-keys). ## Index Caching The service-based SDKs handle caching automatically on the server side. Unlike the embedded SDKs, you don't need to specify cache sizes when creating indexes. The CyborgDB service optimizes query performance through: * Automatic index caching based on usage patterns * Server-side query optimization * Efficient index loading and memory management ## Automatic Embedding Generation All Client SDKs support automatic embedding generation. You can specify an embedding model when creating the index: ```python Python SDK icon="python" theme={null} from cyborgdb import Client # Create a client client = Client( base_url='http://localhost:8000', api_key='your-api-key' ) # Generate an encryption key for the index. # `save=True` is available for local evaluation (caches the key under ~/.cyborgdb/); # leave it as `save=False` (default) and persist the key in your own secret store. index_key = client.generate_key(save=False) # Set embedding model (from HuggingFace) embedding_model = "all-MiniLM-L6-v2" # Create an encrypted index with managed embedding generation index = client.create_index( index_name="my_index", index_key=index_key, embedding_model=embedding_model ) ``` ```javascript JavaScript SDK icon="js" theme={null} import { Client } from 'cyborgdb'; // Create a client const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); // Generate an encryption key for the index const indexKey = client.generateKey(); // Set embedding model (from HuggingFace) const embeddingModel = "all-MiniLM-L6-v2"; // Create an encrypted index with managed embedding generation const index = await client.createIndex({ indexName: "my_index", indexKey, embeddingModel }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { Client, EncryptedIndex, CreateIndexRequest } from 'cyborgdb'; // Create a client const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); // Generate an encryption key for the index const indexKey: Uint8Array = client.generateKey(); // Set embedding model (from HuggingFace) const embeddingModel: string = "all-MiniLM-L6-v2"; // Create an encrypted index with managed embedding generation const params: CreateIndexRequest = { indexName: "my_index", indexKey, embeddingModel }; const index: EncryptedIndex = await client.createIndex(params); ``` ```go Go SDK icon="golang" theme={null} package main import ( "context" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { // Create client client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } // Generate encryption key indexKey, err := cyborgdb.GenerateKey() if err != nil { log.Fatal(err) } // Set embedding model embeddingModel := "all-MiniLM-L6-v2" // Create encrypted index with managed embedding generation params := &cyborgdb.CreateIndexParams{ IndexName: "my_index", IndexKey: indexKey, EmbeddingModel: &embeddingModel, } ctx := context.Background() index, err := client.CreateIndex(ctx, params) if err != nil { log.Fatal(err) } log.Printf("Created index with embeddings: %s", index.GetIndexName()) } ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "embedding_model": "all-MiniLM-L6-v2" }' ``` ## API Reference For more information on creating encrypted indexes, refer to the API reference: > [card] [REST API Reference](../../rest-api/client/create-index) > > REST API reference for `/v1/indexes/create` > [card] [Python SDK Reference](../../python-sdk/client/create-index) > > API reference for `create_index()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/client/create-index) > > API reference for `createIndex()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/client/create-index) > > API reference for `CreateIndex()` in Go # Delete an Encrypted Index Source: https://docs.cyborg.co/versions/latest/service/guides/encrypted-indexes/delete-index > [!WARNING] > > This action is irreversible. Proceed with caution. To delete an existing encrypted index, you can connect to it and then call the `delete_index()` method. ```python Python SDK icon="python" theme={null} from cyborgdb import Client # Create a client client = Client( base_url='http://localhost:8000', api_key='your-api-key' ) # Provide the same index key and config used when creating the index index_key = your_existing_32_byte_key # Must be the same key used originally # Connect to the existing index index = client.load_index( index_name="my_index", index_key=index_key ) # Delete the index index.delete_index() ``` ```javascript JavaScript SDK icon="js" theme={null} import { Client } from 'cyborgdb'; // Create a client const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); // Provide the same index key and config used when creating the index const indexKey = yourExisting32ByteKey; // Must be the same key used originally // Connect to the existing index const index = await client.loadIndex({ indexName: "my_index", indexKey }); // Delete the index await index.deleteIndex(); ``` ```typescript TypeScript SDK icon="code" theme={null} import { Client } from 'cyborgdb'; // Create a client const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); // Provide the same index key and config used when creating the index const indexKey = yourExisting32ByteKey; // Must be the same key used originally // Connect to the existing index const index = await client.loadIndex({ indexName: "my_index", indexKey }); // Delete the index await index.deleteIndex(); ``` ```go Go SDK icon="golang" theme={null} package main import ( "context" "log" "github.com/cyborginc/cyborgdb-go" ) // Create client client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } // Provide the same index key used when creating the index indexKey := []byte("your-existing-32-byte-key") // Must be the same key used originally // Connect to the existing index index, err := client.LoadIndex(context.Background(), "my_index", indexKey) if err != nil { log.Fatal(err) } // Delete the index err = index.DeleteIndex(context.Background()) if err != nil { log.Fatal(err) } ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X POST "http://localhost:8000/v1/indexes/delete" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' ``` ## API Reference For more information on deleting an encrypted index, refer to the API reference: > [card] [REST API Reference](../../rest-api/encrypted-index/delete-index) > > REST API reference for `/v1/indexes/delete` > [card] [Python SDK Reference](../../python-sdk/encrypted-index/delete-index) > > API reference for `delete_index()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/encrypted-index/delete-index) > > API reference for `deleteIndex()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/encrypted-index/delete-index) > > API reference for `DeleteIndex()` in Go # Introduction to Encrypted Indexes Source: https://docs.cyborg.co/versions/latest/service/guides/encrypted-indexes/introduction Encrypted Indexes are the main organizational unit of CyborgDB. One encrypted index is secured with one index key, which provides useful segmentation: * **Cryptographic isolation**: each index is isolated via encryption keys, making it impossible to query/view the contents of an index without proper access/authorization. * **Multi-tenancy**: this separation makes it easy to separate data scopes (e.g., tenants) in a robust and secure manner. One client can manage an arbitrary number of indexes, and an index can contain an arbitrary amount of items/vectors. All contents of the index are end-to-end encrypted, meaning that they remain encrypted throughout their lifecycle (at-rest and in-use). # List Encrypted Indexes Source: https://docs.cyborg.co/versions/latest/service/guides/encrypted-indexes/list-indexes To see which existing encrypted indexes are available to your CyborgDB client, you can use `list_indexes`: ```python Python SDK icon="python" theme={null} from cyborgdb import Client # Create a client client = Client( base_url='http://localhost:8000', api_key='your-api-key' ) # List all available indexes indexes = client.list_indexes() print(indexes) # Example output: # ["index_one", "index_two", "index_three"] ``` ```javascript JavaScript SDK icon="js" theme={null} import { Client } from 'cyborgdb'; // Create a client const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); // List all available indexes const indexes = await client.listIndexes(); console.log(indexes); // Example output: // ["index_one", "index_two", "index_three"] ``` ```typescript TypeScript SDK icon="code" theme={null} import { Client } from 'cyborgdb'; // Create a client const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); // List all available indexes const indexes: string[] = await client.listIndexes(); console.log(indexes); // Example output: // ["index_one", "index_two", "index_three"] ``` ```go Go SDK icon="golang" theme={null} package main import ( "context" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) // Create client client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } // List all indexes ctx := context.Background() indexes, err := client.ListIndexes(ctx) if err != nil { log.Fatal(err) } fmt.Println(indexes) // Example output: ["index_one", "index_two", "index_three"] ``` ```bash cURL icon="rectangle-terminal" theme={null} curl -X GET "http://localhost:8000/v1/indexes/list" \ -H "X-API-Key: your-api-key" # Response: # { # "indexes": ["index_one", "index_two", "index_three"] # } ``` This returns an array of index names that are available to your API key. ## API Reference For more information on listing encrypted indexes, refer to the API reference: > [card] [REST API Reference](../../rest-api/client/list-indexes) > > REST API reference for `/v1/indexes/list` > [card] [Python SDK Reference](../../python-sdk/client/list-indexes) > > API reference for `list_indexes()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/client/list-indexes) > > API reference for `listIndexes()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/client/list-indexes) > > API reference for `ListIndexes()` in Go # Load an Existing Encrypted Index Source: https://docs.cyborg.co/versions/latest/service/guides/encrypted-indexes/load-index If you've previously created an encrypted index, you can connect to it to add, query or delete data from it. You will need to know the index's name as well as its key to do so: > [!NOTE] > > This is only applicable to the CyborgDB SDKs. The REST API is stateless, so you don't need to load indexes explicitly. ```python Python SDK icon="python" theme={null} from cyborgdb import Client # Create a client client = Client( base_url='http://localhost:8000', api_key='your-api-key' ) # Provide the same index key used when creating the index index_key = your_existing_32_byte_key # Connect to existing index index = client.load_index( index_name="my_index", index_key=index_key ) ``` ```javascript JavaScript SDK icon="js" theme={null} import { Client } from 'cyborgdb'; // Create a client const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); const indexKey = yourExisting32ByteKey; // Must be the same key used originally // Connect to existing index const index = await client.loadIndex({ indexName: "my_index", indexKey }); ``` ```typescript TypeScript SDK icon="code" theme={null} import { Client, EncryptedIndex, LoadIndexParams } from 'cyborgdb'; // Create a client const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); const indexKey: Uint8Array = yourExisting32ByteKey; // Must be the same key used originally // Connect to existing index const params: LoadIndexParams = { indexName: "my_index", indexKey }; const index: EncryptedIndex = await client.loadIndex(params); ``` ```go Go SDK icon="golang" theme={null} package main import ( "context" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { // Create client client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } // Provide the same index key used when creating the index indexKey := yourExisting32ByteKey // Must be the same key used originally // Connect to existing index ctx := context.Background() index, err := client.LoadIndex(ctx, "my_index", indexKey) if err != nil { log.Fatal(err) } log.Printf("Loaded index: %s", index.GetIndexName()) } ``` ```bash cURL icon="rectangle-terminal" theme={null} # The REST API is stateless - no explicit "load" needed # Simply use the index_name and index_key in subsequent operations # Example: Query an existing index directly curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.1, 0.2, 0.3, 0.4], "top_k": 5 }' ``` This connects to an existing encrypted index on the service. For more details on index types and configurations, see [Configure an Encrypted Index](../advanced/configure-index). > [!WARNING] > > You must provide the exact same index key that was used when the index was originally created. The index continues to use its original configuration; you do not provide that configuration again when loading it. > For production use, we recommend that you use an HSM or KMS solution for key management. > For more details, see [Managing Encryption Keys](../advanced/managing-keys). ## Index Caching Index caching is handled automatically by the CyborgDB service. The service optimizes performance through: * **Automatic Caching**: Frequently accessed indexes are cached automatically * **Smart Eviction**: Least recently used indexes are evicted when memory is needed * **Server-Side Optimization**: No client-side cache configuration required ## API Reference For more information on loading an encrypted index, refer to the API reference: > [card] [Python SDK Reference](../../python-sdk/client/load-index) > > API reference for `load_index()` in Python > [card] [JS/TS SDK Reference](../../js-ts-sdk/client/load-index) > > API reference for `loadIndex()` in JavaScript/TypeScript > [card] [Go SDK Reference](../../go-sdk/client/load-index) > > API reference for `LoadIndex()` in Go # CyborgDB Service Source: https://docs.cyborg.co/versions/latest/service/guides/intro/about CyborgDB Service provides a self-hosted microservice deployment with REST API and client SDKs. This model offers the perfect balance between control and convenience - you maintain ownership of your infrastructure while enjoying the benefits of a service-oriented architecture. ## Why Choose CyborgDB Service? **Faster Development**\ REST API and multi-language SDKs accelerate development across different teams and technology stacks. **Built for Scale**\ Designed for high-throughput production workloads, with multi-threaded CPU and optional GPU acceleration and connection pooling. **DevOps Friendly**\ Docker-based deployment with comprehensive monitoring, logging, and operational tooling built-in. **Multi-Language Support**\ Native SDKs for Python, JavaScript/TypeScript, and Go - use your preferred language stack. *** ## Deployment Options > [card] [Docker Deployment](./quickstart-docker) > > *Containerized service deployment* > > * Self-contained Docker image > * Easy Kubernetes integration > * Production-ready configuration > * Automatic dependency management > * Best for: Production deployments, containerized environments > [card] [Python Service](./quickstart-python) > > *Direct Python installation* > > * Pip-installable service package > * Custom Python environment control > * Lightweight alternative to Docker > * Direct dependency management > * Best for: Python-centric environments, development *** ## Client SDKs Access CyborgDB Service from any language using our comprehensive SDK collection: > [card] [Python SDK](../../python-sdk/introduction) > > *Full-featured Python client* > > Complete client with async support and type hints > [card] [JavaScript/TypeScript SDK](../../js-ts-sdk/introduction) > > *Modern web and Node.js client* > > Promise-based API with TypeScript definitions > [card] [Go SDK](../../go-sdk/introduction) > > *Native Go client* > > Efficient and idiomatic Go API for CyborgDB *** ## Quick Start Paths > [card] [Docker Quickstart](./quickstart-docker) > > *Deploy in 5 minutes* > > Get CyborgDB Service running with Docker and start building immediately. > [card] [Python Service Quickstart](./quickstart-python) > > *Python-native deployment* > > Install and run CyborgDB as a Python service with pip. ### API Key Limitations > [!NOTE] > > **Free API Key Users**: If you're using a free API key, CyborgDB Service will have 1M item limit per index. > > Upgrade to a [paid plan](https://www.cyborg.co/pricing) to unlock `cyborgdb-core` with unlimited vectors, all backing stores, GPU acceleration, and full performance capabilities. ## Architecture Overview CyborgDB Service runs as a containerized microservice in your infrastructure: ```mermaid theme={null} flowchart TB subgraph Your_Applications [Your Application] PythonSDK("Python SDK") JSSDK("JavaScript SDK") TSSDK("TypeScript SDK") GoSDK("Go SDK") end PythonSDK --> RESTAPI JSSDK --> RESTAPI TSSDK --> RESTAPI GoSDK --> RESTAPI RESTAPI("REST API") RESTAPI --> CyborgDB("CyborgDB Service") CyborgDB --> Disk CyborgDB --> S3 Disk("Disk (local)") S3("Amazon S3 / MinIO") ``` **Key Benefits:** * Language-agnostic API access * Scales independently of your application * Operational monitoring and logging * Production-ready deployment patterns *** ## When to Use Service vs Embedded > [tab] Choose CyborgDB Service > > * **Multi-language teams** - Need to support different programming languages > * **Microservice architecture** - Want to separate vector operations from application logic > * **Operational simplicity** - Prefer service-based deployment patterns > * **Independent scaling** - Need to scale vector operations independently of your application > * **Team collaboration** - Multiple teams need access to the same vector data > * **REST API preference** - Want standard HTTP endpoints for integration > [tab] Consider CyborgDB Embedded > > * **Maximum performance** - Need sub-millisecond latency with zero network overhead > * **Single-language environment** - Python applications exclusively > * **Air-gapped deployment** - No outbound network access (requires running without an API key) > * **Custom integration** - Require deep integration with existing systems > * **Resource optimization** - Want to eliminate network serialization overhead ## Production Considerations ### Scaling and Performance * **Scaling**: Running multiple service instances against the same storage target (disk path or S3 bucket/prefix) is not currently supported. Scale vertically (CPU threads, GPU), or shard indexes across separate service instances that each use their own storage target * **Caching**: Opt in to per-keystore RAM caches via `CACHE_POLICY_VECTORS`, `CACHE_POLICY_METADATA`, and `CACHE_POLICY_IDS` (see [Environment Variables](../advanced/env-vars)) * **GPU Acceleration**: Set `GPU_OPERATIONS=upsert,train` (or `all`) on a CUDA host to offload index ops * **Monitoring**: Enable telemetry and monitoring for production visibility ### Security * **API Key Management**: Rotate keys regularly and use environment variables * **Network Security**: Deploy within private networks or use TLS/SSL * **Storage & KMS Credentials**: Restrict S3 access via IAM and protect KMS provider credentials — see [Managing Encryption Keys](../advanced/managing-keys) * **Access Control**: Implement proper authentication and authorization ## Next Steps > [card] [Deploy with Docker](./quickstart-docker) > > Get CyborgDB Service running with Docker > [card] [Deploy with Python](./quickstart-python) > > Install and run CyborgDB as a Python service > [card] [Explore REST API](../../rest-api/introduction) > > Learn how to interact with CyborgDB Service via REST API Ready to deploy CyborgDB as a scalable service? Start with our [Docker Quickstart](./quickstart-docker) guide! # Docker Service Quickstart Source: https://docs.cyborg.co/versions/latest/service/guides/intro/quickstart-docker **CyborgDB** can be deployed as a standalone microservice using Docker. This allows you to run a fully self-contained encrypted vector search service on your own infrastructure with minimal setup. The service exposes a REST API for integration with any stack. > [!TIP] > > Looking to use the Python service? Check out our [Python Quickstart Guide](./quickstart-python). ## Overview The Docker service is ideal for teams looking to self-host CyborgDB in cloud, on-prem, or containerized environments. **1. Get an API Key (Optional)** The service runs without an API key — leave `CYBORGDB_API_KEY` unset and the core engine starts in free-tier mode, capped at 1,000,000 items per index. Set it to lift that cap. Get a key from the [CyborgDB Admin Dashboard](https://cyborgdb.co/new), or generate a temporary demo key with any of the SDKs: ```python Python theme={null} import cyborgdb print(cyborgdb.get_demo_api_key()) ``` ```javascript JavaScript theme={null} import { getDemoApiKey } from 'cyborgdb'; console.log(await getDemoApiKey()); ``` ```go Go theme={null} demoKey, _ := cyborgdb.GetDemoAPIKey("my demo app") fmt.Println(demoKey) ``` Pass the key as `CYBORGDB_API_KEY` when starting the service. This is the core license key, not a service-authentication credential — it does not gate access to the REST API. > [!NOTE] > > Service authentication is separate and controlled by `CYBORGDB_SERVICE_ROOT_KEY`. Leave it unset (the default) and the service accepts all requests. Set it to require callers to send the root key — or a `cdbk_` user token minted under it — in the `X-API-Key` header. See [Managing Keys](../advanced/managing-keys). **2. Choose Your Storage Backend (Optional)** The container ships with two storage backends. Skip this step and you get **disk** by default — persisted in `/app/cyborgdb_data` inside the container, which you'll typically bind to a host volume. * **Disk** (default) — persistent local disk, no external dependencies. * **S3** — AWS S3 or any S3-compatible store (MinIO, Cloudflare R2, …). Best for cloud-native deployments. For full details, see the [Backing Stores guide](../../../intro/backing-stores). **3. Pull the Docker Image** The CyborgDB service is available as a Docker image. You can pull it from Docker Hub: ```bash theme={null} docker pull cyborginc/cyborgdb-service:latest ``` This image contains everything you need to run the CyborgDB service, including all dependencies and configurations. **4. Run with Docker (Quick Start)** Evaluating? Use `docker run` below. Deploying? Use Docker Compose in the next step. > [tab] Disk (default) > > ```bash Linux theme={null} > # Minimal — no API key needed; disk is the default; bind the data dir to a host volume > docker run -it --rm --network host \ > -v cyborgdb_data:/app/cyborgdb_data \ > cyborginc/cyborgdb-service:latest > ``` > > ```bash macOS theme={null} > docker run -it -p 8000:8000 \ > -v cyborgdb_data:/app/cyborgdb_data \ > cyborginc/cyborgdb-service:latest > ``` > > > [!NOTE] > > > > Inside the container the disk path defaults to `/app/cyborgdb_data` — the `-v` mount above is what makes the data survive container recreation. Add `-e CYBORGDB_API_KEY=…` to lift the free-tier 1M-items-per-index cap. > [tab] S3 (AWS) > > ```bash Linux theme={null} > docker run -it --network host \ > -e CYBORGDB_DB_TYPE=s3 \ > -e CYBORGDB_S3_BUCKET=my-bucket \ > -e CYBORGDB_S3_REGION=us-east-1 \ > -e AWS_ACCESS_KEY_ID=AKID... \ > -e AWS_SECRET_ACCESS_KEY=... \ > cyborginc/cyborgdb-service:latest > ``` > > ```bash macOS theme={null} > docker run -it -p 8000:8000 \ > -e CYBORGDB_DB_TYPE=s3 \ > -e CYBORGDB_S3_BUCKET=my-bucket \ > -e CYBORGDB_S3_REGION=us-east-1 \ > -e AWS_ACCESS_KEY_ID=AKID... \ > -e AWS_SECRET_ACCESS_KEY=... \ > cyborginc/cyborgdb-service:latest > ``` > > > [!NOTE] > > > > On EC2/ECS/EKS the instance/task role is picked up automatically — drop the `AWS_*` vars. > [tab] S3 (MinIO / R2) > > ```bash Linux theme={null} > docker run -it --network host \ > -e CYBORGDB_DB_TYPE=s3 \ > -e CYBORGDB_S3_BUCKET=my-bucket \ > -e CYBORGDB_S3_ENDPOINT=http://minio:9000 \ > -e CYBORGDB_S3_ACCESS_KEY=minioadmin \ > -e CYBORGDB_S3_SECRET_KEY=minioadmin \ > cyborginc/cyborgdb-service:latest > ``` > > ```bash macOS theme={null} > docker run -it -p 8000:8000 \ > -e CYBORGDB_DB_TYPE=s3 \ > -e CYBORGDB_S3_BUCKET=my-bucket \ > -e CYBORGDB_S3_ENDPOINT=http://host.docker.internal:9000 \ > -e CYBORGDB_S3_ACCESS_KEY=minioadmin \ > -e CYBORGDB_S3_SECRET_KEY=minioadmin \ > cyborginc/cyborgdb-service:latest > ``` > > > [!NOTE] > > > > With a custom `CYBORGDB_S3_ENDPOINT` the AWS default credential chain is bypassed entirely — `CYBORGDB_S3_ACCESS_KEY` / `CYBORGDB_S3_SECRET_KEY` are required. > [!NOTE] > > **Platform Differences:** > > * **Linux** uses `--network host` because Docker runs natively and can directly access the host network > * **macOS** uses `-p 8000:8000` and `host.docker.internal` because Docker runs in a VM and needs port mapping **5. Run with Docker Compose (Recommended)** For a reproducible setup, use Docker Compose: > [tab] Disk (default) > > Create a `docker-compose.yml` file: > > ```yaml theme={null} > services: > cyborgdb: > image: cyborginc/cyborgdb-service:latest > ports: > - "8000:8000" > # No API key needed; add CYBORGDB_API_KEY to lift the free-tier cap: > # environment: > # - CYBORGDB_API_KEY=${CYBORGDB_API_KEY} > volumes: > - cyborgdb_data:/app/cyborgdb_data > - ./logs:/app/logs > > volumes: > cyborgdb_data: > ``` > > Then run: > > ```bash theme={null} > docker compose up -d > ``` > [tab] S3 (AWS) > > Create a `docker-compose.yml` file: > > ```yaml theme={null} > services: > cyborgdb: > image: cyborginc/cyborgdb-service:latest > ports: > - "8000:8000" > environment: > - CYBORGDB_API_KEY=${CYBORGDB_API_KEY} > - CYBORGDB_DB_TYPE=s3 > - CYBORGDB_S3_BUCKET=${CYBORGDB_S3_BUCKET} > - CYBORGDB_S3_REGION=${CYBORGDB_S3_REGION:-us-east-1} > - AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} > - AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} > ``` > > Then run: > > ```bash theme={null} > docker compose up -d > ``` > [tab] S3 (MinIO) > > Bring up MinIO + cyborgdb-service together: > > ```yaml theme={null} > services: > minio: > image: minio/minio:latest > command: server /data --console-address ":9001" > environment: > - MINIO_ROOT_USER=minioadmin > - MINIO_ROOT_PASSWORD=minioadmin > ports: > - "9000:9000" > - "9001:9001" > volumes: > - minio_data:/data > > cyborgdb: > image: cyborginc/cyborgdb-service:latest > ports: > - "8000:8000" > environment: > - CYBORGDB_API_KEY=${CYBORGDB_API_KEY} > - CYBORGDB_DB_TYPE=s3 > - CYBORGDB_S3_BUCKET=cyborgdb > - CYBORGDB_S3_ENDPOINT=http://minio:9000 > - CYBORGDB_S3_ACCESS_KEY=minioadmin > - CYBORGDB_S3_SECRET_KEY=minioadmin > depends_on: > - minio > > volumes: > minio_data: > ``` > > Then run: > > ```bash theme={null} > docker compose up -d > ``` > > > [!NOTE] > > > > Create the `cyborgdb` bucket once via the MinIO console (`http://localhost:9001`) before first use. **6. Verify Installation** Once the service is running, verify it's working correctly: **Health Check:** ```bash theme={null} curl http://localhost:8000/v1/health ``` **API Documentation:** Navigate to [http://localhost:8000/v1/docs](http://localhost:8000/v1/docs) to explore the interactive API documentation. You should see a response indicating the service is healthy and ready to accept requests. **7. Run Your First Query** With the service running, install the Python client and complete a full connect → index → upsert → query loop: ```bash theme={null} pip install cyborgdb ``` ```python Python icon="python" theme={null} import cyborgdb import secrets # Connect to the running service. client = cyborgdb.Client(base_url="http://localhost:8000") # Generate an encryption key for the index. # WARNING: store this key securely — data encrypted with a lost key is unrecoverable. index_key = secrets.token_bytes(32) # Create an encrypted index. index = client.create_index(index_name="my_index", index_key=index_key) # Upsert some items. items = [ {"id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Hello!"}, {"id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "contents": "Bonjour!"}, {"id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12], "contents": "Hola!"}, ] index.upsert(items) # Query — include distance + metadata, then chain get() for contents. results = index.query( query_vectors=[0.1, 0.2, 0.3, 0.4], top_k=2, include=["distance", "metadata"], ) top_items = index.get([r["id"] for r in results]) by_id = {item["id"]: item for item in top_items} for r in results: contents = by_id[r["id"]]["contents"] print(f"ID: {r['id']} Distance: {r['distance']:.4f} Contents: {contents}") ``` > [!WARNING] > > **Store `index_key` before you upsert any data.** CyborgDB has no key-recovery path — data encrypted with a lost key is unrecoverable. For anything past evaluation, keep the key in AWS Secrets Manager, Vault, or your KMS. See [Managing Keys](../advanced/managing-keys). > [!NOTE] > > `index_key` is a 32-byte per-index encryption key you generate and hold. It's separate from `CYBORGDB_API_KEY` (the core license key) and `CYBORGDB_SERVICE_ROOT_KEY` (service authentication). **8. Advanced Configuration** For production deployments, consider these additional configurations: > [tab] Environment Variables > > | Variable | Description | Required | Example | > | - | - | - | - | > | `CYBORGDB_API_KEY` | Core license key. Free tier (1M items/index) when unset | ❌ | `cyborg_abc123...` | > | `CYBORGDB_SERVICE_ROOT_KEY` | Service auth root (an operator-chosen secret). Auth disabled (all requests allowed) when unset | ❌ | `a-long-random-secret` | > | `CYBORGDB_DB_TYPE` | Storage backend (`disk`, `s3`) | ❌ (defaults to `disk`) | `s3` | > | `CYBORGDB_DISK_PATH` | Data directory for `disk` storage | ❌ | `/var/lib/cyborgdb` | > | `CYBORGDB_S3_BUCKET` | Bucket name for `s3` storage | Required for S3 | `my-bucket` | > | `CYBORGDB_S3_REGION` | Region for `s3` storage | ❌ | `us-east-1` | > | `PORT` | Service port | ❌ | `8000` | > | `SSL_CERT_PATH` | Path to SSL certificate file | ❌ | `/etc/ssl/certs/server.crt` | > | `SSL_KEY_PATH` | Path to SSL private key file | ❌ | `/etc/ssl/private/server.key` | > > > [!NOTE] > > > > None of these are required — the container starts with no configuration, using `disk` storage rooted at `/app/cyborgdb_data`, free-tier licensing, and authentication disabled. For the full list (including S3 credentials and KMS), see the [Environment Variables](../advanced/env-vars) guide. > [tab] HTTPS Configuration > > For production deployments, configure HTTPS by providing SSL certificates: > > **Environment Variables:** > > ```bash theme={null} > SSL_CERT_PATH=/path/to/certificate.crt > SSL_KEY_PATH=/path/to/private.key > ``` > > **Docker Run Example:** > > ```bash theme={null} > docker run -it -p 8000:8000 \ > -e CYBORGDB_API_KEY=cyborg_your_api_key_here \ > -e CYBORGDB_DB_TYPE=s3 \ > -e CYBORGDB_S3_BUCKET=cyborgdb-prod \ > -e CYBORGDB_S3_REGION=us-east-1 \ > -e SSL_CERT_PATH=/certs/server.crt \ > -e SSL_KEY_PATH=/certs/server.key \ > -v /host/path/to/certs:/certs \ > cyborginc/cyborgdb-service:latest > ``` > > **Docker Compose with SSL:** > > ```yaml theme={null} > services: > cyborgdb: > image: cyborginc/cyborgdb-service:latest > ports: > - "8000:8000" > environment: > - CYBORGDB_API_KEY=cyborg_your_api_key_here > - CYBORGDB_DB_TYPE=s3 > - CYBORGDB_S3_BUCKET=cyborgdb-prod > - CYBORGDB_S3_REGION=us-east-1 > - SSL_CERT_PATH=/certs/server.crt > - SSL_KEY_PATH=/certs/server.key > volumes: > - ./certs:/certs > ``` > > > [!NOTE] > > > > The server automatically switches to HTTPS when both certificate files are provided and exist. Without certificates, it starts in HTTP mode. **9. Next Steps** The Python client above is the fastest way to reach a first query. To integrate from another language, install the equivalent client SDK: ```bash JavaScript icon="js" theme={null} npm install cyborgdb ``` ```bash TypeScript icon="code" theme={null} npm install cyborgdb ``` ```bash Go icon="golang" theme={null} go get github.com/cyborginc/cyborgdb-go ``` > [card] [REST API Reference](../../rest-api/introduction) > > Learn how to use the REST API for direct integration > [card] [Python SDK Reference](../../python-sdk/introduction) > > Learn how to use the Python SDK for direct integration > [card] [JS/TS SDK Reference](../../js-ts-sdk/introduction) > > Learn how to use the JavaScript/TypeScript SDK for direct integration > [card] [Go SDK Reference](../../go-sdk/introduction) > > Learn how to use the Go SDK for direct integration > [accordion] Technical Specifications > > * **Base Image**: `python:3.14-slim` > * **Python Version**: 3.14 > * **Docker Image Size**: about 124 MB compressed (no PyTorch bundled; see the Docker Hub page for the current size) > * **Platform**: linux/amd64, linux/arm64 > * **Default Port**: 8000 > [accordion] Comparison with Python Service > > | Aspect | Python Service | Docker Service | > | - | - | - | > | **Installation** | `pip install` | `docker run` | > | **Dependencies** | Managed by pip/conda | Bundled in container | > | **Resource Usage** | Lower overhead | Higher overhead | > | **Environment Isolation** | Python virtualenv | Container isolation | > | **Deployment Complexity** | Simple Python deployment | Container orchestration | > | **Configuration** | Environment variables/files | Environment variables | > | **Best For** | Development, Python-heavy workflows | Production, cloud deployment | > > > [!TIP] > > > > Both approaches provide identical CyborgDB functionality. Choose based on your deployment preferences and infrastructure requirements. # Python Service Quickstart Source: https://docs.cyborg.co/versions/latest/service/guides/intro/quickstart-python **CyborgDB** can be deployed as a Python service using pip installation. This approach provides a lightweight alternative to Docker, allowing you to run the CyborgDB service directly in your Python environment with full control over dependencies and configuration. > [!TIP] > > Looking to use Docker? Check out our [Docker Quickstart Guide](./quickstart-docker). ## Overview The Python service is ideal for developers who prefer managing Python environments directly, need custom dependency management, or want to integrate CyborgDB service into existing Python applications. It provides the same REST API functionality as the Docker version. **1. Get an API Key (Optional)** The service runs without an API key — leave `CYBORGDB_API_KEY` unset and the core engine starts in free-tier mode, capped at 1,000,000 items per index. Set it to lift that cap. Get a key from the [CyborgDB Admin Dashboard](https://cyborgdb.co/new), or generate a temporary demo key with any of the SDKs: ```python Python theme={null} import cyborgdb print(cyborgdb.get_demo_api_key()) ``` ```javascript JavaScript theme={null} import { getDemoApiKey } from 'cyborgdb'; console.log(await getDemoApiKey()); ``` ```go Go theme={null} demoKey, _ := cyborgdb.GetDemoAPIKey("my demo app") fmt.Println(demoKey) ``` Pass the key as `CYBORGDB_API_KEY` when starting the service. This is the core license key, not a service-authentication credential — it does not gate access to the REST API. > [!NOTE] > > Service authentication is separate and controlled by `CYBORGDB_SERVICE_ROOT_KEY`. Leave it unset (the default) and the service accepts all requests. Set it to require callers to send the root key — or a `cdbk_` user token minted under it — in the `X-API-Key` header. See [Managing Keys](../advanced/managing-keys). **2. Check Prerequisites** Ensure you have the required Python version and environment tools: * **Python**: 3.10, 3.11, 3.12, 3.13, or 3.14 * **Package Manager**: conda (recommended) or pip with virtual environment > [!NOTE] > > While conda is mentioned in the build instructions, the wheel works with any Python environment manager including pip, pipenv, poetry, etc. **3. Choose Your Storage Backend (Optional)** The service ships with two storage backends. Skip this step and you get **disk** by default — the data directory is `~/.cyborgdb/data`. * **Disk** (default) — persistent local disk. No external dependencies. Best for single-node deployments and edge devices. * **S3** — AWS S3 or any S3-compatible store (MinIO, Cloudflare R2, …). Best for cloud-native deployments. For full details, see the [Backing Stores guide](../../../intro/backing-stores). **4. Install CyborgDB Service** Install the CyborgDB service package using conda and pip: ```bash Conda Environment (Recommended) theme={null} # Create conda environment conda create -n cyborgdb-service python=3.12 conda activate cyborgdb-service # Install the service pip install cyborgdb-service ``` ```bash Virtual Environment theme={null} # Create a virtual environment python -m venv cyborgdb-env source cyborgdb-env/bin/activate # Install the service pip install cyborgdb-service ``` ```bash System Python theme={null} # Install directly (not recommended for production) pip install cyborgdb-service ``` > [!WARNING] > > Using conda or a virtual environment is strongly recommended to avoid dependency conflicts with other Python packages. **5. Configure Environment Variables** Set the required environment variables for your deployment: > [tab] Disk (default) > > No environment variables are required — disk is the default and data goes to `~/.cyborgdb/data`. Set these only to override the defaults: > > ```bash Linux/macOS theme={null} > # Optional: lift the free-tier 1M-items-per-index cap > # export CYBORGDB_API_KEY=cyborg_your_api_key_here > # Optional: pin the data directory > # export CYBORGDB_DISK_PATH=/var/lib/cyborgdb > ``` > > ```bash .env File theme={null} > # CYBORGDB_API_KEY=cyborg_your_api_key_here > # CYBORGDB_DISK_PATH=/var/lib/cyborgdb > ``` > [tab] S3 (AWS) > > ```bash Linux/macOS theme={null} > export CYBORGDB_DB_TYPE=s3 > export CYBORGDB_S3_BUCKET=my-bucket > export CYBORGDB_S3_REGION=us-east-1 > # Optional: lift the free-tier 1M-items-per-index cap > # export CYBORGDB_API_KEY=cyborg_your_api_key_here > # On EC2/ECS/EKS the instance role is picked up automatically. > # Off AWS, set AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY instead. > ``` > > ```bash .env File theme={null} > CYBORGDB_DB_TYPE=s3 > CYBORGDB_S3_BUCKET=my-bucket > CYBORGDB_S3_REGION=us-east-1 > # CYBORGDB_API_KEY=cyborg_your_api_key_here > ``` > [tab] S3 (MinIO / R2) > > ```bash Linux/macOS theme={null} > export CYBORGDB_DB_TYPE=s3 > export CYBORGDB_S3_BUCKET=my-bucket > export CYBORGDB_S3_ENDPOINT=https://minio.internal:9000 > export CYBORGDB_S3_ACCESS_KEY=minioadmin > export CYBORGDB_S3_SECRET_KEY=minioadmin > # Optional: lift the free-tier 1M-items-per-index cap > # export CYBORGDB_API_KEY=cyborg_your_api_key_here > ``` > > ```bash .env File theme={null} > CYBORGDB_DB_TYPE=s3 > CYBORGDB_S3_BUCKET=my-bucket > CYBORGDB_S3_ENDPOINT=https://minio.internal:9000 > CYBORGDB_S3_ACCESS_KEY=minioadmin > CYBORGDB_S3_SECRET_KEY=minioadmin > # CYBORGDB_API_KEY=cyborg_your_api_key_here > ``` > > > [!NOTE] > > > > With a custom `CYBORGDB_S3_ENDPOINT` the AWS default credential chain is bypassed entirely — `CYBORGDB_S3_ACCESS_KEY` / `CYBORGDB_S3_SECRET_KEY` are required. > [!TIP] > > Using a `.env` file is the most convenient method as it persists your configuration and keeps sensitive data out of your shell history. For more information on environment variables, refer to [this guide](../advanced/env-vars). **6. Start the Service** Run the CyborgDB service using the installed command: ```bash theme={null} cyborgdb-service ``` The service will start and display startup information including: * Configured storage backend (`disk` or `s3`) * Server URL (default: `http://localhost:8000`) * Available API endpoints > [!NOTE] > > For additional configuration options, run `cyborgdb-service --help` to see all available command-line arguments. **7. Verify Installation** Once the service is running, verify it's working correctly: **Health Check:** ```bash theme={null} curl http://localhost:8000/v1/health ``` **API Documentation:** Navigate to [http://localhost:8000/v1/docs](http://localhost:8000/v1/docs) to explore the interactive API documentation. You should see a response indicating the service is healthy and ready to accept requests. **8. Run Your First Query** With the service running, install the Python client and complete a full connect → index → upsert → query loop: ```bash theme={null} pip install cyborgdb ``` ```python Python icon="python" theme={null} import cyborgdb import secrets # Connect to the running service. client = cyborgdb.Client(base_url="http://localhost:8000") # Generate an encryption key for the index. # WARNING: store this key securely — data encrypted with a lost key is unrecoverable. index_key = secrets.token_bytes(32) # Create an encrypted index. index = client.create_index(index_name="my_index", index_key=index_key) # Upsert some items. items = [ {"id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Hello!"}, {"id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "contents": "Bonjour!"}, {"id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12], "contents": "Hola!"}, ] index.upsert(items) # Query — include distance + metadata, then chain get() for contents. results = index.query( query_vectors=[0.1, 0.2, 0.3, 0.4], top_k=2, include=["distance", "metadata"], ) top_items = index.get([r["id"] for r in results]) by_id = {item["id"]: item for item in top_items} for r in results: contents = by_id[r["id"]]["contents"] print(f"ID: {r['id']} Distance: {r['distance']:.4f} Contents: {contents}") ``` > [!WARNING] > > **Store `index_key` before you upsert any data.** CyborgDB has no key-recovery path — data encrypted with a lost key is unrecoverable. For anything past evaluation, keep the key in AWS Secrets Manager, Vault, or your KMS. See [Managing Keys](../advanced/managing-keys). > [!NOTE] > > `index_key` is a 32-byte per-index encryption key you generate and hold. It's separate from `CYBORGDB_API_KEY` (the core license key) and `CYBORGDB_SERVICE_ROOT_KEY` (service authentication). **9. Advanced Configuration** For production deployments, consider these additional configurations: > [tab] Environment Variables > > | Variable | Description | Required | Example | > | - | - | - | - | > | `CYBORGDB_API_KEY` | Core license key. Free tier (1M items/index) when unset | ❌ | `cyborg_abc123...` | > | `CYBORGDB_SERVICE_ROOT_KEY` | Service auth root (an operator-chosen secret). Auth disabled (all requests allowed) when unset | ❌ | `a-long-random-secret` | > | `CYBORGDB_DB_TYPE` | Storage backend (`disk`, `s3`) | ❌ (defaults to `disk`) | `s3` | > | `CYBORGDB_DISK_PATH` | Data directory for `disk` storage | ❌ | `/var/lib/cyborgdb` | > | `CYBORGDB_S3_BUCKET` | Bucket name for `s3` storage | Required for S3 | `my-bucket` | > | `CYBORGDB_S3_REGION` | Region for `s3` storage | ❌ | `us-east-1` | > | `PORT` | Service port | ❌ | `8000` | > | `SSL_CERT_PATH` | Path to SSL certificate file | ❌ | `/etc/ssl/certs/server.crt` | > | `SSL_KEY_PATH` | Path to SSL private key file | ❌ | `/etc/ssl/private/server.key` | > > > [!NOTE] > > > > None of these are required — the service starts with no configuration, using `disk` storage rooted at `~/.cyborgdb/data`, free-tier licensing, and authentication disabled. For the full list (including S3 credentials and KMS), see the [Environment Variables](../advanced/env-vars) guide. > [tab] Production Deployment > > For production environments, consider using a process manager: > > ```bash theme={null} > # Using gunicorn (install separately) > pip install gunicorn > gunicorn cyborgdb_service.main:app --port 8000 > > # Using systemd service (Linux) > sudo systemctl enable cyborgdb-service > sudo systemctl start cyborgdb-service > ``` > [tab] HTTPS Configuration > > For production deployments, configure HTTPS by providing SSL certificates: > > **Environment Variables:** > > ```bash theme={null} > export SSL_CERT_PATH=/path/to/certificate.crt > export SSL_KEY_PATH=/path/to/private.key > ``` > > **Complete Production Example:** > > ```bash theme={null} > # Set all required environment variables including SSL > export CYBORGDB_API_KEY=cyborg_your_api_key_here > export CYBORGDB_DB_TYPE=s3 > export CYBORGDB_S3_BUCKET=cyborgdb-prod > export CYBORGDB_S3_REGION=us-east-1 > export SSL_CERT_PATH=/etc/ssl/certs/server.crt > export SSL_KEY_PATH=/etc/ssl/private/server.key > > # Start service (will automatically use HTTPS) > cyborgdb-service > ``` > > **Using .env File with SSL:** > > ```bash theme={null} > # Create a .env file with SSL configuration > cat > .env << EOF > CYBORGDB_API_KEY=cyborg_your_api_key_here > CYBORGDB_DB_TYPE=s3 > CYBORGDB_S3_BUCKET=cyborgdb-prod > CYBORGDB_S3_REGION=us-east-1 > SSL_CERT_PATH=/path/to/certificate.crt > SSL_KEY_PATH=/path/to/private.key > EOF > > # Start service > cyborgdb-service > ``` > > **Using Let's Encrypt (Production):** > > ```bash theme={null} > # Install certbot (Ubuntu/Debian) > sudo apt-get install certbot > > # Generate certificate for your domain > sudo certbot certonly --standalone -d your-domain.com > > # Set environment variables to Let's Encrypt certificates > export SSL_CERT_PATH=/etc/letsencrypt/live/your-domain.com/fullchain.pem > export SSL_KEY_PATH=/etc/letsencrypt/live/your-domain.com/privkey.pem > > # Start service with HTTPS > cyborgdb-service > ``` > > > [!NOTE] > > > > The server automatically switches to HTTPS when both certificate files are provided and exist. Without certificates, it starts in HTTP mode. **10. Next Steps** The Python client above is the fastest way to reach a first query. To integrate from another language, install the equivalent client SDK: ```bash JavaScript icon="js" theme={null} npm install cyborgdb ``` ```bash TypeScript icon="code" theme={null} npm install cyborgdb ``` ```bash Go icon="golang" theme={null} go get github.com/cyborginc/cyborgdb-go ``` > [card] [REST API Reference](../../rest-api/introduction) > > Learn how to use the REST API for direct integration > [card] [Python SDK Reference](../../python-sdk/introduction) > > Learn how to use the Python SDK for direct integration > [card] [JS/TS SDK Reference](../../js-ts-sdk/introduction) > > Learn how to use the JavaScript/TypeScript SDK for direct integration > [card] [Go SDK Reference](../../go-sdk/introduction) > > Learn how to use the Go SDK for direct integration > [accordion] Comparison with Docker Service > > | Aspect | Python Service | Docker Service | > | - | - | - | > | **Installation** | `pip install` | `docker run` | > | **Dependencies** | Managed by pip/conda | Bundled in container | > | **Resource Usage** | Lower overhead | Higher overhead | > | **Environment Isolation** | Python virtualenv | Container isolation | > | **Deployment Complexity** | Simple Python deployment | Container orchestration | > | **Configuration** | Environment variables/files | Environment variables | > | **Best For** | Development, Python-heavy workflows | Production, cloud deployment | > > > [!TIP] > > > > Both approaches provide identical CyborgDB functionality. Choose based on your deployment preferences and infrastructure requirements. # Client Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/client/client `Client` is the entry point of the CyborgDB JS/TS SDK. It connects to a running CyborgDB service and creates, loads, and lists encrypted indexes. Operations on an index, such as upsert and query, are methods of the `EncryptedIndex` it returns. ## Constructor ```typescript theme={null} new Client({ baseUrl: string, apiKey?: string, verifySsl?: boolean, }) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `baseUrl` | `string` | - | Base URL of the CyborgDB service, e.g. `'http://localhost:8000'`. Must use `http://` or `https://`. | | `apiKey` | `string` | `undefined` | *(Optional)* Service authentication credential, sent as the `X-API-Key` header. Required only when the service has authentication enabled. | | `verifySsl` | `boolean` | `undefined` (auto-detect) | *(Optional)* TLS certificate verification. See [TLS verification](#tls-verification). | > [!NOTE] > > `apiKey` is the service **authentication** credential: the root key or a per-user `cdbk_` token. It is required only when the service runs with `CYBORGDB_SERVICE_ROOT_KEY` set; against an unauthenticated service (the default), omit it. This is distinct from the service's `CYBORGDB_API_KEY` license key. See [Managing Keys](../../guides/advanced/managing-keys). The constructor throws `CyborgDBValidationError` if `baseUrl` can't be parsed or doesn't use `http://` or `https://`. ### Example Usage ```typescript theme={null} import { Client } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); ``` ## TLS verification `verifySsl` decides whether the SDK checks the service's TLS certificate: | `baseUrl` | `verifySsl` unset | `true` | `false` | | - | - | - | - | | `http://…` | No TLS | No TLS | No TLS | | `https://` with host `localhost`, `127.0.0.1`, or `::1` | Verification **off** | Verification on | Verification off | | Any other `https://` URL | Verification on | Verification on | Verification off | Turning verification off works on Node.js, where requests then go through the `node:https` module instead of `fetch`. It follows redirects and honors `AbortSignal`, and it times out a connection after 300 seconds of inactivity. Browsers and Edge runtimes can't turn verification off; `verifySsl: false` has no effect there. When verification is off, the SDK logs `console.warn` messages: on Node, one saying verification is disabled and a second saying the insecure transport is in use. The loopback auto-detect case logs its first message with `console.info`. A plain `http://` URL also logs "SSL verification is disabled", although there is no TLS to disable. ## Errors Failed requests throw a subclass of `CyborgDBError` chosen by HTTP status, such as `CyborgDBNotFoundError` for `404` or `CyborgDBAuthenticationError` for `401`. Arguments rejected inside the SDK, before a request is sent, throw `CyborgDBValidationError`. See [Errors](../errors) for the full list. ```typescript theme={null} import { Client, CyborgDBAuthenticationError } from 'cyborgdb'; try { await new Client({ baseUrl: 'http://localhost:8000', apiKey: 'wrong-key' }).listIndexes(); } catch (error) { console.log(error instanceof CyborgDBAuthenticationError); } // Output: true ``` ## Supported runtimes The package has no runtime dependencies and needs only `fetch` and Web Crypto, so it runs on: | Runtime | Notes | | - | - | | Node.js 18+ | Full functionality, including the on-disk [sample dataset](../load-sample-dataset) cache. | | Bun, Deno | Same as Node. | | Modern browsers | No sample-dataset cache. | | Vercel Edge Runtime, Cloudflare Workers | No sample-dataset cache. | # Create Index Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/client/create-index Creates a new encrypted index on the service and returns an `EncryptedIndex` bound to it. ```typescript theme={null} async createIndex({ indexName: string, indexKey?: Uint8Array, kmsName?: string, dimension?: number, metric?: 'euclidean' | 'squared_euclidean' | 'cosine', embeddingModel?: string, storagePrecision?: 'float32' | 'float16' | 'tq12' | 'tq8' | 'tq6' | 'tq4', metadataSchema?: { [field: string]: MetadataFieldPolicy }, textFields?: string[], bm25K1?: number, bm25B?: number, }): Promise ``` > [!NOTE] > > There is one index type, configured with flat fields. The earlier `IndexIVFFlat`, `IndexIVFPQ`, and `IndexIVFSQ` types and the `indexConfig` argument no longer exist. ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `indexName` | `string` | - | Unique name for the index. | | `indexKey` | `Uint8Array` | `undefined` | *(Optional)* 32-byte encryption key (SDK-supplied KEK). Pass either `indexKey` or `kmsName`, never both. | | `kmsName` | `string` | `undefined` | *(Optional)* Name of a `kms.registry` entry in the service YAML. The service generates the KEK and wraps it with that provider; the SDK never sees the plaintext key. | | `dimension` | `number` | `undefined` | *(Optional)* Vector dimensionality. When omitted, the service detects it from the first upsert. | | `metric` | `string` | `undefined` (service default: `'euclidean'`) | *(Optional)* `'euclidean'`, `'squared_euclidean'`, or `'cosine'`. | | `embeddingModel` | `string` | `undefined` | *(Optional)* Name of one of the service's built-in embedding models (listed by `GET /v1/embedding-models`), used for automatic embedding generation. When set, `dimension` is taken from the model. | | `storagePrecision` | `string` | `undefined` (service default: `'float32'`) | *(Optional)* Storage format for the index's stored vector embeddings. See [Storage precision](#storage-precision). | | `metadataSchema` | `{ [field: string]: MetadataFieldPolicy }` | `undefined` | *(Optional)* Per-field metadata indexing policy. Fixed at creation and cannot be changed later. See [Metadata schema](#metadata-schema). | | `textFields` | `string[]` | `undefined` | *(Optional)* Metadata fields to index for BM25 full-text search. Shorthand for `{ fullText: true }` in `metadataSchema`. Enables `text` on [`query()`](../encrypted-index/query) and [`queryMetadata()`](../encrypted-index/query-metadata). | | `bm25K1` | `number` | `undefined` (service default: `1.2`) | *(Optional)* BM25 term-frequency saturation, `>= 0`. Requires at least one full-text field. | | `bm25B` | `number` | `undefined` (service default: `0.75`) | *(Optional)* BM25 length-normalization strength, in `[0, 1]`. Requires at least one full-text field. | ### Key management Pass exactly one of `indexKey` or `kmsName`. The service rejects both together with `CyborgDBValidationError` (HTTP `400`), whatever the KMS provider. * **SDK-supplied KEK:** pass `indexKey`. Supply the same key again on every [`loadIndex()`](./load-index). * **KMS-backed:** pass `kmsName`. The service generates the key, wraps it with the named provider, and stores the wrapped key. Later calls omit `indexKey`. ### Storage precision `storagePrecision` sets the format used to store the index's vector embeddings. Every value works with every metric. | Value | Bits per dimension | | - | - | | `'float32'` | 32 | | `'float16'` | 16 | | `'tq12'` | 12 | | `'tq8'` | 8 | | `'tq6'` | 6 | | `'tq4'` | 4 | The `tq*` values are TurboQuant tiers; lower tiers use less storage in exchange for a small recall and latency cost. ### Metadata schema `metadataSchema` sets how each metadata field is indexed. Metadata itself stays schemaless: this controls indexing, not what may be stored. Fields left out get the default policy (indexed and filterable). Nested fields use dot-paths such as `'loc.city'`. ```typescript theme={null} const metadataSchema = { title: { filterable: true, pattern: true }, // regex-searchable internalBlob: { filterable: false }, // stored, not indexed body: { fullText: true }, // BM25 full-text search }; ``` Each field takes three settings (the [`MetadataFieldPolicy`](../types#metadatafieldpolicy) type): | Setting | Default | Effect | | - | - | - | | `filterable` | `true` | Indexes the field, so filters on it resolve from the index. `false` still stores the field but doesn't index it; see [Filters the index cannot answer](#filters-the-index-cannot-answer). | | `pattern` | `false` | Also builds a regex dictionary, so `$regex` and `$contains` resolve from the index. Requires `filterable: true`. | | `fullText` | `false` | Sends the field's text through the BM25 analyzer instead of exact-match indexing. Implies `filterable: false`, and can't be combined with `pattern: true`. | #### Filters the index cannot answer The index can answer a filter when the field is filterable and, for `$regex` or `$contains`, the field also has `pattern` set. Any other filter is handled differently depending on the call: | Call | Filter the index can't answer | | - | - | | [`query()`](../encrypted-index/query) without `text` | Still works, but slower: the filter is applied to the decrypted metadata after the search. | | [`query()`](../encrypted-index/query) with `text` | Rejected with `CyborgDBValidationError`. | | [`queryMetadata()`](../encrypted-index/query-metadata) | Rejected with `CyborgDBValidationError`. | With the schema above: ```typescript theme={null} { title: { $regex: '^Intro' } } // answerable: title is filterable and has pattern { internalBlob: 'abc' } // not answerable: internalBlob isn't filterable { author: { $regex: '^Ann' } } // not answerable: author is filterable by default, but has no pattern ``` The stored policy is returned by the [`metadataSchema()`](../getters#metadataschema) getter. ### Returns `Promise` bound to the new index. For KMS-backed indexes it holds no plaintext key. ### Exceptions > [accordion] CyborgDBValidationError > > * Neither `indexKey` nor `kmsName` is passed, or `indexKey` is not 32 bytes. Thrown before any request is sent. > * The service rejects the request (HTTP `400`/`422`): the index name already exists, both `indexKey` and `kmsName` were passed, the `kmsName` slot is unknown, `storagePrecision` isn't one of the six values, or `metadataSchema` combines settings that aren't allowed. > [accordion] CyborgDBAuthenticationError > > The client's `apiKey` is missing or invalid (HTTP `401`), or is a per-user key: creating an index requires the root key (HTTP `403`). > [accordion] CyborgDBServiceError > > The service returns `5xx`, including KMS wrap failures (`502`). > [accordion] CyborgDBTransportError > > The service can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage #### SDK-supplied key ```typescript theme={null} import { Client } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); const indexKey = Client.generateKey(); // The dimension is detected from the first upsert const index = await client.createIndex({ indexName: 'documents', indexKey }); ``` > [!NOTE] > > Store `indexKey` securely: it is needed to load the index again. See [Generate Key](./generate-key). #### Explicit dimension and metric ```typescript theme={null} const index = await client.createIndex({ indexName: 'documents_384', indexKey, dimension: 384, metric: 'cosine', }); ``` #### KMS-backed index ```typescript theme={null} // The service generates the key and wraps it with the 'prod-aws' registry slot. const index = await client.createIndex({ indexName: 'kms_documents', kmsName: 'prod-aws', dimension: 384, }); // Later calls, including loadIndex(), omit indexKey. ``` #### Automatic embeddings ```typescript theme={null} // The dimension is taken from the embedding model const index = await client.createIndex({ indexName: 'semantic_docs', indexKey, embeddingModel: 'all-MiniLM-L6-v2', }); ``` See [Auto-Generate Embeddings](../../guides/data-operations/add-items#automatic-embedding-generation). #### Reduced storage with TurboQuant ```typescript theme={null} const index = await client.createIndex({ indexName: 'compact_docs', indexKey, dimension: 768, storagePrecision: 'tq8', }); ``` #### Per-field metadata policy ```typescript theme={null} const index = await client.createIndex({ indexName: 'docs_index', indexKey, dimension: 4, metadataSchema: { title: { filterable: true, pattern: true }, internalBlob: { filterable: false }, }, }); await index.upsert({ items: [ { id: 'doc1', vector: [0.1, 0.2, 0.3, 0.4], metadata: { title: 'intro to encryption' } }, { id: 'doc2', vector: [0.5, 0.6, 0.7, 0.8], metadata: { title: 'advanced setup' } }, ], }); // $regex resolves from the index because 'title' has pattern: true console.log(await index.queryMetadata({ filters: { title: { $regex: '^intro' } } })); // Output: [ { id: 'doc1' } ] ``` #### Full-text search fields ```typescript theme={null} const index = await client.createIndex({ indexName: 'articles', indexKey, dimension: 4, textFields: ['body'], }); console.log(await index.bm25()); // Output: // { // k1: 1.2, // b: 0.75, // analyzerVersion: 'en/1;sw=2de831ef7be676b6;snowball-english-utf8-3.0.1' // } ``` # Generate Key Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/client/generate-key Generates a random 32-byte (256-bit) key for creating an encrypted index with an SDK-supplied key. ```typescript theme={null} static generateKey(): Uint8Array // Client.generateKey() generateKey(): Uint8Array // client.generateKey() ``` The static and instance forms are identical; use the static form when you don't have a client yet. ### Returns `Uint8Array`: 32 bytes from the runtime's Web Crypto `crypto.getRandomValues()`. This works the same on Node.js, browsers, and Edge runtimes, and throws if the runtime has no Web Crypto implementation. Unlike the Python SDK, there is no option to save the key to a file. > [!WARNING] > > An index created with an SDK-supplied key can only be opened with that exact key. If the key is lost, the index's data can't be decrypted. Store it in a secrets manager, or use a KMS-backed index. See [Managing Encryption Keys](../../guides/advanced/managing-keys). ### Example Usage ```typescript theme={null} import { Client } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); const indexKey = Client.generateKey(); console.log(indexKey.length); // Output: 32 const index = await client.createIndex({ indexName: 'my-secure-index', indexKey }); // Keep the key somewhere safe, e.g. as hex in a secrets manager const keyHex = Array.from(indexKey, (b) => b.toString(16).padStart(2, '0')).join(''); ``` # Get Health Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/client/get-health Returns the health status of the CyborgDB service, to check that it is reachable and running. ```typescript theme={null} async getHealth(): Promise ``` ### Returns `Promise`, an object with these keys: | Key | Description | | - | - | | `status` | Service health, `'healthy'` when the service is up. | | `api_version` | REST API version, e.g. `'v1'`. | | `version` | CyborgDB service version. | ### Exceptions > [accordion] CyborgDBServiceError > > The service returns `5xx`. > [accordion] CyborgDBTransportError > > The service can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage ```typescript theme={null} import { Client } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); const health = await client.getHealth(); console.log(health); // Output: { status: 'healthy', api_version: 'v1', version: '0.18.0' } ``` # List Indexes Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/client/list-indexes Returns the names of all indexes on the CyborgDB service. ```typescript theme={null} async listIndexes(): Promise ``` ### Returns `Promise`: index names. Empty when the service has no indexes. ### Exceptions > [accordion] CyborgDBAuthenticationError > > The client's `apiKey` is missing or invalid (HTTP `401`), or is a per-user key: listing indexes requires the root key (HTTP `403`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. > [accordion] CyborgDBTransportError > > The service can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage ```typescript theme={null} import { Client } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); const indexes = await client.listIndexes(); console.log(indexes); // Output: [ 'documents', 'embeddings', 'semantic-search' ] ``` # Load Index Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/client/load-index Loads an existing encrypted index and returns an `EncryptedIndex` bound to it. ```typescript theme={null} async loadIndex({ indexName: string, indexKey?: Uint8Array, }): Promise ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `indexName` | `string` | - | Name of an existing index. | | `indexKey` | `Uint8Array` | `undefined` | *(Optional)* The 32-byte key the index was created with. Required for SDK-supplied-key indexes; omit it for KMS-backed indexes (created with `kmsName`). | > [!WARNING] > > For SDK-supplied-key indexes, `indexKey` must be the exact key passed to `createIndex()`. A KMS-backed index fails to load if its `kmsName` slot is missing from the service YAML or its provider is unreachable, with `CyborgDBAuthenticationError` (HTTP `401`). ### Returns `Promise` bound to the loaded index. ### Exceptions > [accordion] CyborgDBValidationError > > `indexKey` is passed but is not 32 bytes. Thrown before any request is sent. > [accordion] CyborgDBNotFoundError > > No index named `indexName` exists, or `indexKey` doesn't match (HTTP `404`, in most cases). > [accordion] CyborgDBAuthenticationError > > `indexKey` doesn't match an index that has vectors and is already in the service's cache, or the client's `apiKey` is missing or invalid; or, for a KMS-backed index, its KMS slot is missing or the provider call fails (HTTP `401`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. > [accordion] CyborgDBTransportError > > The service can't be reached. See [Errors](../errors) for the full hierarchy. > [!NOTE] > > A wrong key returns `CyborgDBAuthenticationError` (HTTP `401`) when the index has vectors and the service already has it cached, and `CyborgDBNotFoundError` (HTTP `404`) otherwise, for example on an empty index or right after the service restarts. Catch both when checking for a bad key. ### Example Usage #### SDK-supplied-key index ```typescript theme={null} import { Client } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); // The same 32 bytes that were passed to createIndex(), e.g. stored as hex const indexKey = new Uint8Array(Buffer.from('your-64-character-hex-key', 'hex')); const index = await client.loadIndex({ indexName: 'my_index', indexKey }); console.log(await index.getIndexName()); // Output: my_index ``` `Buffer` is Node-only; in a browser or Edge runtime, decode the hex string with your own helper. #### KMS-backed index ```typescript theme={null} // No key needed: the service unwraps it with the index's KMS provider. const index = await client.loadIndex({ indexName: 'kms_index' }); ``` # Delete Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/encrypted-index/delete Permanently removes items from the index by ID, along with their contents and metadata. ```typescript theme={null} async delete({ ids: string[] }): Promise ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `ids` | `string[]` | - | IDs of the items to delete. An empty array is a no-op. | ### Returns `Promise` with `status` and `message`, e.g. `{ status: 'success', message: 'Deleted 2 vectors' }`. The count is the number of IDs sent, including IDs that don't exist. ### Exceptions > [accordion] CyborgDBValidationError > > The service rejects the request (HTTP `422`), for example when `ids` isn't an array of strings. > [accordion] CyborgDBAuthenticationError > > The `indexKey` or `apiKey` is invalid, or a read-only user key is used (HTTP `401`/`403`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. See [Errors](../errors) for the full hierarchy. ### Example Usage ```typescript theme={null} const result = await index.delete({ ids: ['doc1', 'doc2'] }); console.log(result); // Output: { status: 'success', message: 'Deleted 2 vectors' } console.log((await index.listIds()).ids); // Output: [ 'doc3' ] ``` # Delete Index Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/encrypted-index/delete-index > [!WARNING] > > Deleting an index is irreversible. Deletes the index and all of its data from the CyborgDB service. ```typescript theme={null} async deleteIndex(): Promise<{ status?: string; message: string }> ``` ### Returns `Promise<{ status, message }>`, e.g. `{ status: 'success', message: "Index 'temporary-index' deleted successfully" }`. ### Exceptions > [accordion] CyborgDBNotFoundError > > The index doesn't exist, for example because it was already deleted (HTTP `404`). > [accordion] CyborgDBAuthenticationError > > The `indexKey` or `apiKey` is invalid (HTTP `401`), or the client is using a per-user key: deleting an index requires the root key (HTTP `403`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. See [Errors](../errors) for the full hierarchy. ### Example Usage ```typescript theme={null} const result = await index.deleteIndex(); console.log(result.status); // Output: success console.log((await client.listIndexes()).includes(await index.getIndexName())); // Output: false ``` # Get Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/encrypted-index/get Retrieves items from the index by ID, with the fields you choose. ```typescript theme={null} async get({ ids: string[], include?: string[], // default: ['vector', 'contents', 'metadata'] }): Promise ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `ids` | `string[]` | - | IDs of the items to retrieve. | | `include` | `string[]` | `['vector', 'contents', 'metadata']` | *(Optional)* Fields to return besides `id`. Other values are ignored. | ### Returns `Promise`, one object per ID found. IDs that don't exist are left out of the result without an error, and an empty `ids` array returns `[]`. When `include` doesn't contain `'vector'`, an existing item that has none of the requested fields is also left out. ```typescript theme={null} { id: string, // Always returned vector?: number[], // When 'vector' is in include contents?: string, // When 'contents' is in include; '' if the item has no contents metadata?: object, // When 'metadata' is in include } ``` `contents` is always a `string`. Contents upserted as bytes come back as their base64 text; decode them with `Buffer.from(contents, 'base64')` on Node, or `atob()` elsewhere. ### Exceptions > [accordion] CyborgDBAuthenticationError > > The `indexKey` or `apiKey` is invalid (HTTP `401`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. See [Errors](../errors) for the full hierarchy. ### Example Usage ```typescript theme={null} const results = await index.get({ ids: ['doc1', 'doc2', 'missing-id'], include: ['contents', 'metadata'] }); for (const item of results) { console.log(item.id, JSON.stringify(item.contents), item.metadata); } // Output: // doc1 "First document" {} // doc2 "" { category: 'news' } ``` #### Decode bytes contents ```typescript theme={null} await index.upsert({ items: [{ id: 'img1', vector: [0.1, 0.2, 0.3, 0.4], contents: new Uint8Array([0x89, 0x50, 0x4e, 0x47]) }], }); const [item] = await index.get({ ids: ['img1'], include: ['contents'] }); const raw = Buffer.from(item.contents ?? '', 'base64'); console.log(raw); // Output: ``` # List IDs Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/encrypted-index/list-ids Returns every item ID in the index. ```typescript theme={null} async listIds(): Promise<{ ids: string[]; count: number }> ``` ### Returns `Promise<{ ids, count }>`: all IDs in the index and how many there are. ### Exceptions > [accordion] CyborgDBAuthenticationError > > The `indexKey` or `apiKey` is invalid (HTTP `401`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. See [Errors](../errors) for the full hierarchy. ### Example Usage ```typescript theme={null} const { ids, count } = await index.listIds(); console.log(count); // Output: 3 console.log(ids.includes('doc1')); // Output: true // Fetch items in batches of 100 for (let i = 0; i < ids.length; i += 100) { const items = await index.get({ ids: ids.slice(i, i + 100) }); } ``` # Query Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/encrypted-index/query Finds the nearest neighbors of one or more query vectors. With `queryContents`, the service embeds the text first (the index needs an `embeddingModel`). With `text`, the query becomes **hybrid**: BM25 full-text ranking is fused with the vector ranking. ```typescript theme={null} async query({ queryVectors?: number[] | number[][] | Float32Array, queryContents?: string, topK?: number, nProbes?: number, filters?: FilterExpression, include?: string[], greedy?: boolean, rerankMult?: number, dimension?: number, text?: string, textFields?: string[], textFieldWeights?: number[], requireAllTerms?: boolean, alpha?: number, rrfK?: number, windowMult?: number, }): Promise ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `queryVectors` | `number[]`, `number[][]`, or `Float32Array` | `undefined` | *(Optional)* One query vector, a batch, or a batch packed back to back in a `Float32Array` (sent in a faster binary format). | | `queryContents` | `string` | `undefined` | *(Optional)* Text for the service to embed and search with. Requires an index created with `embeddingModel`. | | `topK` | `number` | `undefined` (service default: `100`) | *(Optional)* Results to return per query. Must be at least `1`. | | `nProbes` | `number` | `undefined` (service default: auto) | *(Optional)* Clusters to probe. Higher values improve recall and add latency. | | `filters` | [`FilterExpression`](../types#filterexpression) | `undefined` | *(Optional)* Metadata filter. See [Metadata filtering](../types#metadata-filtering). | | `include` | `string[]` | `undefined` (service default: `[]`) | *(Optional)* Extra fields per result: `'distance'` and `'metadata'`. `id` is always returned. See [Result fields](#result-fields). | | `greedy` | `boolean` | `undefined` (service default: `false`) | *(Optional)* Use greedy search. | | `rerankMult` | `number` | `undefined` (service default: `50`) | *(Optional)* Stage 1 returns `topK * rerankMult` candidates before reranking narrows them to `topK`. Higher values trade latency for recall. | | `dimension` | `number` | `undefined` | Required when `queryVectors` is a `Float32Array`, to split it into vectors. Ignored otherwise. | | `text` | `string` | `undefined` | *(Optional)* Query text for a BM25 leg, which makes the query hybrid. Requires an index with at least one full-text field. `queryVectors` is still required. | | `textFields` | `string[]` | `undefined` (all full-text fields) | *(Optional)* Full-text fields the BM25 leg searches. Naming a field that isn't full-text throws `CyborgDBValidationError`. | | `textFieldWeights` | `number[]` | `undefined` (`1.0` each) | *(Optional)* Weight per searched field, in the same order as `textFields`. | | `requireAllTerms` | `boolean` | `undefined` (service default: `false`) | *(Optional)* Match only items containing every query term (AND) instead of any term (OR). | | `alpha` | `number` | `undefined` (service default: `0.5`) | *(Optional)* Blend of the two legs, in `[0, 1]`: `0` is pure BM25, `1` is pure vector. At exactly `0` or `1` the other leg isn't run. | | `rrfK` | `number` | `undefined` (service default: `60`) | *(Optional)* Reciprocal rank fusion smoothing constant. Must be `> 0`. | | `windowMult` | `number` | `undefined` (service default: `3`) | *(Optional)* Candidates retrieved per leg, as a multiple of `topK`. Must be `>= 1`. | ### Returns `Promise`, whose `results` is: * **One `number[]` query vector:** `QueryResultItem[]`, one item per neighbor. * **Two or more query vectors** (`number[][]` or `Float32Array`): `QueryResultItem[][]`, one inner array per query vector. A query with exactly one vector always returns single results, even when it's sent as a batch or through the binary path. `QueryResponse.results` is typed `QueryResultItem[] | QueryResultItem[][]`. Since the call shape decides which one you get, narrow it with a cast: `response.results as QueryResultItem[]` for one vector, or `as QueryResultItem[][]` for a batch. #### Result fields ```typescript theme={null} { id: string, // Always returned distance?: number, // Vector queries, when 'distance' is in include. Lower is closer. score?: number, // Hybrid queries only, instead of distance. Higher is more relevant. metadata?: object, // When 'metadata' is in include } ``` `query()` never returns `vector` or `contents`, even when they're listed in `include`. To read them, pass the result IDs to [`get()`](./get). ### Exceptions > [accordion] CyborgDBValidationError > > * Neither `queryVectors` nor `queryContents` is passed, or a `Float32Array` is passed without `dimension`. Thrown before any request is sent. > * The service rejects the query (HTTP `400`/`422`): wrong vector dimension, `text` on an index without full-text fields, or an out-of-range `alpha`, `rrfK`, or `windowMult`. Other numeric parameters aren't range-checked. > [accordion] CyborgDBAuthenticationError > > The `indexKey` or `apiKey` is invalid (HTTP `401`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. See [Errors](../errors) for the full hierarchy. ### Example Usage #### Single vector ```typescript theme={null} import type { QueryResultItem } from 'cyborgdb'; const response = await index.query({ queryVectors: [0.1, 0.2, 0.3, 0.4], topK: 2, include: ['distance', 'metadata'], }); const results = response.results as QueryResultItem[]; for (const r of results) { console.log(r.id, Number(r.distance?.toFixed(4)), r.metadata); } // Output: // doc1 0 { category: 'news' } // doc2 0.8 { category: 'research' } ``` #### Batch of vectors ```typescript theme={null} import type { QueryResultItem } from 'cyborgdb'; const response = await index.query({ queryVectors: [ [0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], ], topK: 1, }); const batch = response.results as QueryResultItem[][]; batch.forEach((results, i) => console.log(i, results.map((r) => r.id))); // Output: // 0 [ 'doc1' ] // 1 [ 'doc2' ] ``` #### Float32Array ```typescript theme={null} import type { QueryResultItem } from 'cyborgdb'; const queries = new Float32Array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]); const response = await index.query({ queryVectors: queries, dimension: 4, topK: 1 }); const batch = response.results as QueryResultItem[][]; console.log(batch.length); // Output: 2 ``` #### Text, embedded by the service ```typescript theme={null} import type { QueryResultItem } from 'cyborgdb'; // The index must have been created with embeddingModel const response = await index.query({ queryContents: 'machine learning in healthcare', topK: 3, }); console.log((response.results as QueryResultItem[]).map((r) => r.id)); ``` #### Hybrid (BM25 + vector) The index needs at least one full-text field, set with `textFields` or `{ fullText: true }` in [`createIndex()`](../client/create-index#metadata-schema). ```typescript theme={null} import type { QueryResultItem } from 'cyborgdb'; const response = await index.query({ queryVectors: [0.1, 0.2, 0.3, 0.4], text: 'encrypted search', topK: 2, alpha: 0.5, include: ['metadata'], }); for (const r of response.results as QueryResultItem[]) { console.log(r.id, Number(r.score?.toFixed(4))); } // Output: // doc1 0.0164 // doc2 0.0161 ``` #### Filters and search options ```typescript theme={null} import type { QueryResultItem } from 'cyborgdb'; const response = await index.query({ queryVectors: [0.1, 0.2, 0.3, 0.4], topK: 20, nProbes: 5, rerankMult: 20, greedy: true, filters: { category: 'news' }, include: ['distance', 'metadata'], }); for (const r of response.results as QueryResultItem[]) { console.log(r.id, r.metadata?.category); } // Output: doc1 news ``` # Query Metadata Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/encrypted-index/query-metadata Finds items by metadata alone, with no query vector. `queryMetadata()` resolves the filter against the encrypted metadata index and returns the matching IDs. With `text`, it also ranks matches by BM25 relevance. It works on untrained indexes. ```typescript theme={null} async queryMetadata({ filters?: FilterExpression, topK?: number, orderBy?: string | { [field: string]: number }, ascending?: boolean, text?: string, textFields?: string[], textFieldWeights?: number[], requireAllTerms?: boolean, } = {}): Promise ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `filters` | `FilterExpression` | `{}` | *(Optional)* Metadata filter; omitted or `{}` matches everything. See [Filter constraints](#filter-constraints). | | `topK` | `number` | `undefined` | *(Optional)* Maximum results; omit to return every match. Applied after `orderBy`. | | `orderBy` | `string` or `{ [field]: number }` | `undefined` | *(Optional)* Sort by a metadata field: a field name (direction set by `ascending`), or a single-field object such as `{ views: -1 }` for descending. Can't be combined with `text`. | | `ascending` | `boolean` | `true` | *(Optional)* Sort direction when `orderBy` is a field name. Ignored when `orderBy` is an object. | | `text` | `string` | `undefined` | *(Optional)* Query text for BM25 full-text ranking. Requires an index with at least one full-text field. Results then carry a `score`, sorted by relevance, and `filters` act as a pre-filter. | | `textFields` | `string[]` | `undefined` (all full-text fields) | *(Optional)* Full-text fields to search. | | `textFieldWeights` | `number[]` | `undefined` (`1.0` each) | *(Optional)* Weight per searched field, in the same order as `textFields`. | | `requireAllTerms` | `boolean` | `undefined` (service default: `false`) | *(Optional)* Match only items containing every query term. | > [!NOTE] > > * Without `orderBy` or `text`, results come back in no particular order. > * Items missing the `orderBy` field, or holding a non-scalar value in it, sort last. ### Filter constraints [`query()`](./query) falls back to a post-filter over decrypted metadata when the index can't answer a filter, for pure vector queries. `queryMetadata()` has no fallback, so every filter must be answerable from the index. The index's [`metadataSchema`](../client/create-index#metadata-schema) is therefore enforced here: * `$regex` and `$contains` need a field created with `pattern: true`. * A field created with `filterable: false` can't be filtered on. * `$type` isn't supported. Any of these throws `CyborgDBValidationError` (HTTP `400`) with the reason. Nested dot-paths such as `'loc.city'` are supported. ### Returns `Promise`: one object per match. ```typescript theme={null} { id: string, // Always returned score?: number, // Only when text is set. BM25 relevance; higher is more relevant. } ``` ### Exceptions > [accordion] CyborgDBValidationError > > * `orderBy` is an object with more than one key, or isn't a string or object. Thrown before any request is sent. > * The service rejects the query (HTTP `400`): see [Filter constraints](#filter-constraints). > [accordion] CyborgDBAuthenticationError > > The `indexKey` or `apiKey` is invalid (HTTP `401`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. See [Errors](../errors) for the full hierarchy. ### Example Usage #### Filter only ```typescript theme={null} const results = await index.queryMetadata({ filters: { label: 'dog' } }); console.log(results.map((r) => r.id).sort()); // unordered without orderBy // Output: [ '101', '102' ] ``` #### Operators and a result cap ```typescript theme={null} const results = await index.queryMetadata({ filters: { $and: [{ label: 'cat' }, { confidence: { $gte: 0.9 } }] }, topK: 10, }); console.log(results); // Output: [ { id: '201' } ] ``` #### Sorted by a field ```typescript theme={null} // Ascending by "views" const ascending = await index.queryMetadata({ filters: { label: 'dog' }, orderBy: 'views' }); // Descending by "views"; topK applies after the sort const top = await index.queryMetadata({ filters: { label: 'dog' }, orderBy: { views: -1 }, topK: 5, }); console.log(top.map((r) => r.id)); // Output: [ '102', '101' ] ``` #### Regex match ```typescript theme={null} // "title" must have been created with pattern: true const results = await index.queryMetadata({ filters: { title: { $regex: '^intro' } } }); ``` #### Full-text search ```typescript theme={null} // The index needs a full-text field, e.g. createIndex({ ..., textFields: ['body'] }) const results = await index.queryMetadata({ text: 'encrypted search', topK: 5 }); for (const r of results) { console.log(r.id, Number(r.score?.toFixed(4))); } ``` For filter syntax and operators, see [Metadata filtering](../types#metadata-filtering). # Train Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/encrypted-index/train Clusters the index's vectors into IVF lists so queries only scan the closest lists. `train()` waits until training finishes before returning. ```typescript theme={null} async train({ nLists?: number, batchSize?: number, maxIters?: number, tolerance?: number, maxMemory?: number, } = {}): Promise ``` > [!TIP] > > The service also trains indexes automatically. An untrained index is trained once it holds more than `AUTO_TRAIN_MIN_VECTORS` vectors (default `65536`), and a trained index is retrained when its size calls for more lists than it has. Set `AUTO_TRAIN_DISABLED=true` on the service to turn this off. Call `train()` yourself to train a smaller index, or to make sure training is finished before running queries or benchmarks. ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `nLists` | `number` | `undefined` (auto) | *(Optional)* Number of IVF lists. When omitted, the square root of the vector count, rounded to a power of two. | | `batchSize` | `number` | `undefined` (ignored) | *(Optional)* Vectors processed per training batch. | | `maxIters` | `number` | `undefined` (ignored) | *(Optional)* Maximum clustering iterations. | | `tolerance` | `number` | `undefined` (ignored) | *(Optional)* Convergence tolerance. | | `maxMemory` | `number` | `undefined` (ignored) | *(Optional)* Memory cap for training, in MB. | > [!WARNING] > > Only `nLists` affects training today. The service accepts `batchSize`, `maxIters`, `tolerance`, and `maxMemory` but doesn't pass them to training, so they have no effect. Parameter values aren't range-checked. An out-of-range value such as `nLists: 0` is accepted and training is skipped as described in [Requirements](#requirements); a negative `nLists` makes `train()` resolve with `status: 'error'`. ### Requirements Training only runs when all three hold: * The index has at least **10,000 vectors**. * It has at least twice as many vectors as `nLists`. * The vector dimension is a **multiple of 32**, such as 384, 768, or 1536. > [!WARNING] > > `train()` doesn't report a skipped or failed training run. If a requirement isn't met, `train()` still resolves with `{ status: 'success', message: "Index '...' trained successfully" }`. If training fails on the service, it resolves with `status: 'error'` instead of throwing. Either way, the index stays untrained. Check [`isTrained()`](../getters#istrained) after `train()` returns: an untrained index has `getNLists()` of `1`. Queries on an untrained index still work. ### Returns `Promise` with `status` and `message`. If the index is already training, `train()` waits for that run to finish, then trains again. ### Exceptions > [accordion] CyborgDBAuthenticationError > > The client isn't using the root key, or the `indexKey` is invalid (HTTP `401`/`403`). Training requires the root key. > [accordion] CyborgDBNotFoundError > > The index doesn't exist (HTTP `404`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. A failed training run doesn't throw; see [Requirements](#requirements). See [Errors](../errors) for the full hierarchy. ### Example Usage #### Default settings ```typescript theme={null} await index.train(); // train() doesn't throw if training is skipped, so check the result console.log(await index.isTrained(), await index.getNLists()); // Output: true 128 ``` #### Custom settings ```typescript theme={null} await index.train({ nLists: 128, batchSize: 4096, maxIters: 200, tolerance: 1e-7, }); ``` # Upsert Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/encrypted-index/upsert Adds vectors to the index, or replaces existing vectors with the same ID. `upsert()` takes either an array of items or parallel arrays: ```typescript theme={null} async upsert({ items?: VectorItem[], // Shape 1 ids?: string[], // Shape 2 vectors?: number[][] | Float32Array, // Shape 2 metadata?: (Record | null)[], // Shape 2, optional contents?: (string | null)[], // Shape 2, optional }): Promise ``` ### Parameters #### Shape 1: items | Parameter | Type | Default | Description | | - | - | - | - | | `items` | [`VectorItem[]`](../types#vectoritem) | - | One object per vector. | Each item can contain: | Field | Type | Required | Description | | - | - | - | - | | `id` | `string` | Yes | Unique identifier. | | `vector` | `number[]` | Unless the index has an embedding model and `contents` is set | Vector data. | | `contents` | `string` or bytes (`Uint8Array`, `Buffer`) | No | Encrypted before storage. | | `metadata` | `object` | No | Key-value pairs for filtering. | Strings in `contents` are stored as-is; bytes are base64-encoded first. [`get()`](./get) always returns `contents` as a `string`, so bytes come back as their base64 text. > [!TIP] > > Store dates in `metadata` as epoch milliseconds (`date.getTime()`) so range filters work on them. See [Dates](../types#dates). #### Shape 2: parallel arrays | Parameter | Type | Default | Description | | - | - | - | - | | `ids` | `string[]` | - | Unique identifier for each vector. | | `vectors` | `number[][]` or `Float32Array` | - | Vector data. A `Float32Array` holds all vectors back to back and is sent in a faster binary format. | | `metadata` | `(object \| null)[]` | `undefined` | *(Optional)* Metadata per vector, same length as `ids`. | | `contents` | `(string \| null)[]` | `undefined` | *(Optional)* Contents per vector, same length as `ids`. | > [!WARNING] > > Don't upsert vectors containing `NaN` or infinite values. The service stores them, and later `get` or `query` calls on that index that return vectors or distances fail with a `5xx` error. ### Returns `Promise` with `status` and `message`, e.g. `{ status: 'success', message: 'Upserted 2 vectors' }`. An empty `items` array returns `{ status: 'success', message: 'No items to upsert' }` without calling the service. ### Exceptions > [accordion] CyborgDBValidationError > > * The input matches neither shape, arrays differ in length, or an `items` or `number[][]` vector contains a non-finite number. Thrown before any request is sent. `Float32Array` input isn't checked. > * The service rejects the items (HTTP `400`), for example a vector with the wrong dimension. > [accordion] CyborgDBAuthenticationError > > The `indexKey` or `apiKey` is invalid, or a read-only user key is used (HTTP `401`/`403`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. See [Errors](../errors) for the full hierarchy. ### Example Usage #### Items ```typescript theme={null} const result = await index.upsert({ items: [ { id: 'doc1', vector: [0.1, 0.2, 0.3, 0.4], contents: 'First document' }, { id: 'doc2', vector: [0.5, 0.6, 0.7, 0.8], metadata: { category: 'news' } }, ], }); console.log(result); // Output: { status: 'success', message: 'Upserted 2 vectors' } ``` #### Parallel arrays ```typescript theme={null} await index.upsert({ ids: ['vec1', 'vec2', 'vec3'], vectors: [ [0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.9, 1.0, 1.1, 1.2], ], metadata: [{ category: 'news' }, { category: 'research' }, null], contents: ['First body', 'Second body', null], }); ``` #### Float32Array (binary) ```typescript theme={null} const dim = 4; const ids = ['vec4', 'vec5', 'vec6']; // All vectors back to back: ids.length * dim values const vectors = new Float32Array(ids.length * dim).map(() => Math.random()); await index.upsert({ ids, vectors }); ``` Use a `Float32Array` when the vectors already come from a model or buffer in that form. #### Replace an existing item ```typescript theme={null} await index.upsert({ items: [{ id: 'doc1', vector: [0.1, 0.2, 0.3, 0.4], metadata: { version: 1 } }] }); // Same ID: replaces the vector, contents, and metadata await index.upsert({ items: [{ id: 'doc1', vector: [0.2, 0.3, 0.4, 0.5], metadata: { version: 2 } }] }); const [item] = await index.get({ ids: ['doc1'], include: ['metadata'] }); console.log(item.metadata); // Output: { version: 2 } ``` # User Management (RBAC) Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/encrypted-index/users When the service runs with `CYBORGDB_SERVICE_ROOT_KEY` set, `EncryptedIndex` can create, list, and revoke per-index users. These methods require a client created with the root key. > [!NOTE] > > See [Multi-Tenancy & RBAC](../../guides/advanced/multi-tenancy) for the operator-side playbook (modes, key kinds, SDK-supplied indexes). ## createUser Creates a user scoped to this index and returns their API key. ```typescript theme={null} async createUser({ permissions: string[] }): Promise<{ userId: string; apiKey: string }> ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `permissions` | `string[]` | Non-empty subset of `['read', 'write']`. | ### Returns `Promise<{ userId, apiKey }>`: | Field | Type | Description | | - | - | - | | `userId` | `string` | Hex identifier for the new user. | | `apiKey` | `string` | The user's API key, starting with `cdbk_`. | > [!WARNING] > > The service returns `apiKey` only in this response and never stores it. Give it to the user over a secure channel and don't log it. If it's lost, delete the user and create a new one. ### Example ```typescript theme={null} import { Client } from 'cyborgdb'; const ROOT_KEY = 'your-service-root-key'; const indexKey = new Uint8Array(Buffer.from('your-64-character-hex-key', 'hex')); const admin = new Client({ baseUrl: 'http://localhost:8000', apiKey: ROOT_KEY }); const index = await admin.loadIndex({ indexName: 'documents', indexKey }); const user = await index.createUser({ permissions: ['read', 'write'] }); console.log(Object.keys(user).sort()); // Output: [ 'apiKey', 'userId' ] // The user connects with their own key const userClient = new Client({ baseUrl: 'http://localhost:8000', apiKey: user.apiKey }); ``` *** ## listUsers Lists the users created for this index. ```typescript theme={null} async listUsers(): Promise<{ userId: string; permissions: string[] }[]> ``` ### Returns An array of `{ userId, permissions }`, where `permissions` is a subset of `['read', 'write']`. ### Example ```typescript theme={null} await index.createUser({ permissions: ['read'] }); for (const u of await index.listUsers()) { console.log(u.permissions); } // Output: [ 'read' ] ``` > [!NOTE] > > Deleting an index doesn't delete its user records. If you create a new index with the same name, `listUsers()` on it still returns the old users. They can't read the new index, because their keys don't unwrap its data key; delete them with `deleteUser()`. *** ## deleteUser Revokes a user. Their access keys for this index are erased, so their `cdbk_` key stops working on the next request. ```typescript theme={null} async deleteUser({ userId: string }): Promise ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `userId` | `string` | `userId` from `createUser()` or `listUsers()`. | ### Example ```typescript theme={null} const { userId } = await index.createUser({ permissions: ['read'] }); await index.deleteUser({ userId }); console.log(await index.listUsers()); // Output: [] ``` *** ## Exceptions These apply to all three methods: > [accordion] CyborgDBAuthenticationError > > The client isn't using the root key (HTTP `403`), or its `apiKey` is invalid (HTTP `401`). > [accordion] CyborgDBValidationError > > `permissions` is empty or contains a value other than `'read'` or `'write'`, or `userId` isn't hex (HTTP `400`). > [accordion] CyborgDBNotFoundError > > The index doesn't exist (HTTP `404`). > [accordion] CyborgDBServiceError > > The service returns `5xx`. See [Errors](../errors) for the full hierarchy. # Errors Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/errors Failed requests to the service throw a subclass of `CyborgDBError`. The subclass is chosen from the HTTP status code, so callers can catch one class per failure mode. ```typescript theme={null} import { Client, CyborgDBAuthenticationError } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'wrong-key' }); try { await client.listIndexes(); } catch (error) { if (error instanceof CyborgDBAuthenticationError) { console.log(error.statusCode, error.detail); } } // Output: 401 Invalid API Key ``` ## Error classes | Class | Thrown for | `retryable` | | - | - | - | | `CyborgDBValidationError` | HTTP `400` or `422`: the service rejected the request's arguments. Also thrown by the `Client` constructor for an invalid `baseUrl`. | `false` | | `CyborgDBAuthenticationError` | HTTP `401` or `403`: a missing or invalid `apiKey`, a non-root key used for a root-only operation, or an `indexKey` that doesn't match an index that has vectors and is already in the service's cache. | `false` | | `CyborgDBNotFoundError` | HTTP `404`: the index or resource does not exist. | `false` | | `CyborgDBConflictError` | HTTP `409`: the request conflicts with the current state on the server. | `false` | | `CyborgDBRateLimitError` | HTTP `429`. The service does not rate-limit requests yet. | `true` | | `CyborgDBServiceError` | Any HTTP `5xx` response. | `true` | | `CyborgDBTransportError` | No response arrived: DNS failure, refused connection, TLS failure, or timeout. The message names the cause, e.g. `connect ECONNREFUSED`. | `true` | All seven classes extend `CyborgDBError`, which extends `Error`, so existing `catch` blocks that handle `Error` still catch them. Each sets `name` to its class name. ## Properties | Property | Type | Description | | - | - | - | | `statusCode` | `number \| null` | HTTP status code. `null` when no response was received or the error was raised before sending. | | `detail` | `string \| null` | The service's error message, from the response body's `detail` field. | | `requestId` | `string \| null` | Value of the `X-Request-Id` response header, when the service sends one. Include it when reporting a problem. | | `retryAfter` | `number \| null` | Seconds from a numeric `Retry-After` header. | | `indexName` | `string \| null` | The index the call targeted. Set by `loadIndex()` and by `upsert()` with `items` or `number[][]` vectors; `null` for other calls, including `Float32Array` upserts. | | `retryable` | `boolean` | Fixed per class; see the table above. | | `cause` | `unknown` | The underlying error. | ```typescript theme={null} import { CyborgDBValidationError } from 'cyborgdb'; try { await index.queryMetadata({ filters: { category: { $regex: '^re' } } }); } catch (error) { if (error instanceof CyborgDBValidationError) { console.log(error.statusCode); console.log(error.detail); } } // Output: // 400 // Failed to query metadata: Invalid input: $regex on 'category' requires a regex-indexed (pattern) field ``` ## Retries The SDK does not retry requests or set a request timeout. `retryable` marks the errors that are safe to retry; the retry loop is up to the caller: ```typescript theme={null} import { CyborgDBError } from 'cyborgdb'; for (let attempt = 0; attempt < 3; attempt++) { try { await index.query({ queryVectors: [0.1, 0.2, 0.3, 0.4], topK: 5 }); break; } catch (error) { if (!(error instanceof CyborgDBError) || !error.retryable || attempt === 2) { throw error; } const seconds = error.retryAfter ?? 2 ** attempt; await new Promise((resolve) => setTimeout(resolve, seconds * 1000)); } } ``` ## Errors thrown before a request is sent Argument checks that run in the SDK, before anything is sent to the service, throw `CyborgDBValidationError` with `statusCode` `null`. This covers: * an `indexKey` that isn't 32 bytes, or neither `indexKey` nor `kmsName` passed to `createIndex()` * `query()` with neither `queryVectors` nor `queryContents`, or a `Float32Array` without `dimension` * malformed `upsert()` input, such as mismatched array lengths * a `queryMetadata()` `orderBy` object with more than one key ## Other statuses HTTP statuses outside the mapping above (for example `405` or `413`) throw the base `CyborgDBError`, with `statusCode` set. Set the environment variable `CYBORGDB_DEBUG=1` (or `true`) to print the full error details to stderr. # Getters Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/getters `EncryptedIndex` exposes index settings and training status as async methods. Every getter except `getIndexName()` calls the service's describe or training-status endpoint. ## getIndexName ```typescript theme={null} async getIndexName(): Promise ``` The index's name. Read locally, with no network call. ```typescript theme={null} console.log(await index.getIndexName()); // Output: my-vectors ``` *** ## getDimension ```typescript theme={null} async getDimension(): Promise ``` Vector dimensionality. Returns `0` if the index was created without a `dimension` and nothing has been upserted yet. Once non-zero, the value is cached and later calls don't reach the service. ```typescript theme={null} console.log(await index.getDimension()); // Output: 384 ``` *** ## getMetric ```typescript theme={null} async getMetric(): Promise ``` Distance metric: `'euclidean'`, `'squared_euclidean'`, or `'cosine'`. Cached after the first call. ```typescript theme={null} console.log(await index.getMetric()); // Output: euclidean ``` *** ## getNLists ```typescript theme={null} async getNLists(): Promise ``` Number of IVF lists. `1` for an untrained index; the trained list count after [`train()`](./encrypted-index/train). Fetched from the service on every call. ```typescript theme={null} console.log(await index.getNLists()); // Output: 1 ``` *** ## metadataSchema ```typescript theme={null} async metadataSchema(): Promise<{ [field: string]: Required }> ``` The per-field indexing policy set with `metadataSchema` or `textFields` in [`createIndex()`](./client/create-index#metadata-schema). Each entry has all three settings filled in: `filterable`, `pattern`, and `fullText`. `{}` when the index uses the default policy. Fetched on every call. ```typescript theme={null} console.log(await index.metadataSchema()); // Output: { body: { filterable: false, pattern: false, fullText: true } } ``` *** ## bm25 ```typescript theme={null} async bm25(): Promise ``` The index's BM25 settings, or `null` when it has no full-text fields. | Field | Type | Description | | - | - | - | | `k1` | `number` | Term-frequency saturation. | | `b` | `number` | Length normalization. | | `analyzerVersion` | `string \| null` | Text analyzer the index was built with. | ```typescript theme={null} console.log(await index.bm25()); // Output: // { // k1: 1.2, // b: 0.75, // analyzerVersion: 'en/1;sw=2de831ef7be676b6;snowball-english-utf8-3.0.1' // } ``` *** ## isTrained ```typescript theme={null} async isTrained(): Promise ``` `true` if the index has been trained. Fetched on every call. ```typescript theme={null} if (!(await index.isTrained())) { await index.train(); } ``` *** ## isTraining ```typescript theme={null} async isTraining(): Promise ``` `true` while the service is training this index or has it queued for training. Requires the root key: with a per-user key the service returns HTTP `403` and the SDK throws `CyborgDBAuthenticationError`. ```typescript theme={null} while (await index.isTraining()) { await new Promise((resolve) => setTimeout(resolve, 5000)); } console.log(await index.isTrained()); ``` # CyborgDB - JavaScript/TypeScript SDK Reference Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/introduction `v0.18.x` The **CyborgDB** JavaScript/TypeScript SDK is a client for the CyborgDB service. It creates encrypted indexes, upserts and retrieves vectors, runs vector, hybrid (BM25 + vector), and metadata-only queries, and manages per-index users. It ships TypeScript types and runs on Node.js 18+, Bun, Deno, modern browsers, Vercel Edge Runtime, and Cloudflare Workers. The package is available on [npm](https://www.npmjs.com/package/cyborgdb) and the source code is on [GitHub](https://github.com/cyborginc/cyborgdb-js). ## Installation ```bash theme={null} npm install cyborgdb ``` The package has no runtime dependencies. ## LangChain The LangChain vector store, `CyborgVectorStore`, is a separate entry point, so the main package doesn't require LangChain: ```bash theme={null} npm install cyborgdb @langchain/core ``` ```typescript theme={null} import { CyborgVectorStore } from 'cyborgdb/integrations/langchain'; ``` `@langchain/core` `^1.0.0` is an optional peer dependency. Since v0.18, `CyborgVectorStore` is no longer exported from `'cyborgdb'` itself. ## Prerequisites The SDK needs a running CyborgDB service: ```bash theme={null} # Install and start the service pip install cyborgdb-service cyborgdb-service # Or run the Docker image docker run -p 8000:8000 cyborginc/cyborgdb-service ``` See the quickstart guides for [Docker](../guides/intro/quickstart-docker) and [Python](../guides/intro/quickstart-python). ## Supported runtimes The SDK ships as a single dependency-free bundle and imports on any JavaScript runtime with `fetch` and Web Crypto: | Runtime | Supported | Notes | | - | - | - | | Node.js | >= 18 | Full functionality, including the on-disk sample-dataset cache. | | Bun / Deno | Yes | Node-compatible; same functionality as Node. | | Browsers | Yes (modern) | `verifySsl: false` has no effect. | | Vercel Edge Runtime | Yes | — | | Cloudflare Workers | Yes | — | The main `cyborgdb` entry point does not import `@langchain/core` — install it (as an optional peer) and import from the `cyborgdb/integrations/langchain` subpath only if you use the LangChain integration. # Load Sample Dataset Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/load-sample-dataset Loads a hosted sample dataset, ready to upsert and query, for quickstarts, demos, and tests without generating your own vectors. The dataset is downloaded from a public S3 bucket. On Node.js it's cached on disk after the first call; other runtimes download it on every call. ```typescript theme={null} async function loadSampleDataset( name?: string, // default: 'quickstart-75k' options?: LoadSampleDatasetOptions, ): Promise ``` `loadSampleDataset` is a top-level export: ```typescript theme={null} import { loadSampleDataset } from 'cyborgdb'; const dataset = await loadSampleDataset(); ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `name` | `string` | `'quickstart-75k'` | *(Optional)* Dataset to load. `'quickstart-75k'` is currently the only one. | | `options.cacheDir` | `string` | `$XDG_CACHE_HOME/cyborgdb` or `~/.cache/cyborgdb` | *(Optional)* Directory for the cached dataset. Node.js only. | | `options.forceDownload` | `boolean` | `false` | *(Optional)* Download again even if a cached copy exists. | The download has a 120-second timeout, and the decompressed dataset is capped at 512 MB. Each dataset's SHA-256 digest is pinned in the SDK and checked after download and on every cache read, so a tampered file is rejected and downloaded again. Decompression needs the runtime's `DecompressionStream`. ### Returns `Promise`: | Field | Type | Description | | - | - | - | | `name` | `string` | Dataset identifier, e.g. `'quickstart-75k'`. | | `version` | `number` | Dataset schema version. | | `description` | `string` | Human-readable description. | | `dimension` | `number` | Vector dimensionality. | | `metric` | `string` | Distance metric the vectors were generated for. | | `count` | `number` | Number of items. | | `items` | `VectorItem[]` | Items with `id`, `vector`, and `metadata`, ready for [`upsert()`](./encrypted-index/upsert). | | `sampleQueries` | `number[][]` | The first 10 query vectors. | | `exampleFilters` | `SampleFilter[]` | Metadata filters guaranteed to match, each with `name`, `filter`, and `demonstrates`. | | `ids` / `vectors` / `metadata` | parallel arrays | Raw arrays, aligned by position. | | `queries`, `metadata_queries`, `metadata_query_names`, `untrained_neighbors`, `trained_neighbors`, `untrained_metadata_matches`, `trained_metadata_matches`, `untrained_metadata_neighbors`, `trained_metadata_neighbors`, `untrained_recall`, `trained_recall`, `num_untrained_vectors`, `num_trained_vectors` | ground truth | Fixture data for checking recall. These keep their snake_case names. | The package also exports the `SampleDataset`, `SampleFilter`, and `LoadSampleDatasetOptions` types and the `DEFAULT_SAMPLE_DATASET` and `SAMPLE_DATASETS_BASE_URL` constants. ### Exceptions > [accordion] Error > > The dataset name is unknown, the download fails or times out, the file fails its SHA-256 check, it exceeds 512 MB, or the runtime has no `DecompressionStream`. ### Example Usage ```typescript theme={null} import { Client, loadSampleDataset, type FilterExpression, type QueryResultItem } from 'cyborgdb'; const client = new Client({ baseUrl: 'http://localhost:8000', apiKey: 'your-api-key' }); const indexKey = Client.generateKey(); // Downloads on first use; cached afterwards on Node.js const dataset = await loadSampleDataset(); console.log(dataset.name, dataset.count, dataset.dimension, dataset.metric); // Output: quickstart-75k 75000 128 euclidean const index = await client.createIndex({ indexName: 'demo', indexKey, dimension: dataset.dimension, metric: dataset.metric as 'euclidean', }); await index.upsert({ items: dataset.items }); // Similarity search with a bundled query vector const response = await index.query({ queryVectors: dataset.sampleQueries[0], topK: 5 }); console.log((response.results as QueryResultItem[]).length); // Output: 5 // A curated metadata filter const example = dataset.exampleFilters[0]; console.log(example.name, example.filter); // Output: Equality filter (string field) { string: 'string_0' } const filtered = await index.query({ queryVectors: dataset.sampleQueries[0], filters: example.filter as FilterExpression, }); ``` # Types Source: https://docs.cyborg.co/versions/latest/service/js-ts-sdk/types ## Index configuration These fields of [`client.createIndex()`](./client/create-index) configure the index. There is no `indexConfig` argument and no `IndexIVFFlat` / `IndexIVFPQ` / `IndexIVFSQ` types. | Parameter | Type | Default | Description | | - | - | - | - | | `dimension` | `number` | auto-detect | Vector dimensionality. Taken from the first upsert, or from `embeddingModel`, when omitted. | | `metric` | `string` | `'euclidean'` | `'euclidean'`, `'squared_euclidean'`, or `'cosine'`. | | `embeddingModel` | `string` | `undefined` | Name of one of the service's built-in embedding models (listed by `GET /v1/embedding-models`), used for automatic embedding generation. | | `storagePrecision` | `string` | `'float32'` | `'float32'`, `'float16'`, or TurboQuant `'tq12'`, `'tq8'`, `'tq6'`, `'tq4'`. See [Storage precision](./client/create-index#storage-precision). | | `metadataSchema` | `{ [field: string]: MetadataFieldPolicy }` | `undefined` | Per-field indexing policy. See [Metadata schema](./client/create-index#metadata-schema). | | `textFields` | `string[]` | `undefined` | Fields to index for BM25 full-text search. | | `bm25K1` | `number` | `1.2` | BM25 term-frequency saturation. | | `bm25B` | `number` | `0.75` | BM25 length normalization. | ### MetadataFieldPolicy ```typescript theme={null} interface MetadataFieldPolicy { filterable?: boolean; // default true pattern?: boolean; // default false fullText?: boolean; // default false } ``` ## Key management | Parameter | Type | Notes | | - | - | - | | `indexKey` | `Uint8Array` | 32-byte key for the SDK-supplied-key path. Pass it again on every `loadIndex()`. The SDK sends it to the service as hex. | | `kmsName` | `string` | Name of a `kms.registry` entry in the service YAML. The service generates and wraps the key; later calls omit `indexKey`. | Pass exactly one of the two to `createIndex()`; passing both throws `CyborgDBValidationError`. ## VectorItem The object shape [`upsert()`](./encrypted-index/upsert) accepts: ```typescript theme={null} import type { VectorItem } from 'cyborgdb'; const item: VectorItem = { id: 'unique_identifier', // Required vector: [0.1, 0.2, 0.3, 0.4], // Optional if the index has an embedding model contents: 'text content', // Optional: string or bytes metadata: { // Optional category: 'research', author: 'Dr. Smith', tags: ['ai', 'ml'], publishedMs: 1768435200000, // a date, as epoch milliseconds }, }; ``` ## Query result [`query()`](./encrypted-index/query) resolves to a `QueryResponse` whose `results` is a flat array for one query vector, and an array of arrays for a batch: ```typescript theme={null} // One query vector: QueryResultItem[] [ { id: 'doc1', distance: 0.125, metadata: { category: 'research' } }, { id: 'doc2', distance: 0.234, metadata: { category: 'news' } }, ] // Batch: QueryResultItem[][], one inner array per query vector [ [{ id: 'doc1', distance: 0.125 }, { id: 'doc2', distance: 0.234 }], [{ id: 'doc3', distance: 0.156 }, { id: 'doc4', distance: 0.278 }], ] ``` `QueryResultItem` has `id`, and optionally `distance` (vector queries; lower is closer), `score` (hybrid queries, instead of `distance`; higher is more relevant), and `metadata`. `QueryResponse.results` is typed `QueryResultItem[] | QueryResultItem[][]`; narrow it with a cast to the shape your call returns. ## MetadataResult The item type [`queryMetadata()`](./encrypted-index/query-metadata) resolves to: ```typescript theme={null} interface MetadataResult { id: string; score?: number; // Only when text is set } ``` ## BM25Config Returned by the [`bm25()`](./getters#bm25) getter: ```typescript theme={null} interface BM25Config { k1: number; b: number; analyzerVersion?: string | null; } ``` ## Field selection `include` picks the fields returned besides `id`: | Field | `get()` | `query()` | | - | - | - | | `vector` | Yes (default) | Not returned | | `contents` | Yes (default) | Not returned | | `metadata` | Yes (default) | Yes | | `distance` | - | Yes | `get()` defaults to `['vector', 'contents', 'metadata']`; `query()` defaults to `[]`, which returns only `id`. ## Metadata filtering `filters` on [`query()`](./encrypted-index/query) and [`queryMetadata()`](./encrypted-index/query-metadata) uses MongoDB-style operators. Nested fields use dot-paths such as `'loc.city'`. ### Operators | Operator | Meaning | Example | | - | - | - | | `$eq` | Equal (also the meaning of a bare value) | `{ category: 'research' }` | | `$ne` | Not equal | `{ status: { $ne: 'draft' } }` | | `$gt`, `$gte` | Greater than, or equal | `{ year: { $gte: 2020 } }` | | `$lt`, `$lte` | Less than, or equal | `{ price: { $lt: 100 } }` | | `$in` | Value is in the list | `{ tag: { $in: ['ai', 'ml'] } }` | | `$nin` | Value is not in the list | `{ category: { $nin: ['spam', 'deleted'] } }` | | `$exists` | Field is present (`true`) or absent (`false`) | `{ reviewer: { $exists: true } }` | | `$regex` | String matches a regular expression | `{ title: { $regex: '^intro' } }` | | `$contains` | String contains a substring | `{ title: { $contains: 'guide' } }` | | `$and` | All sub-filters match | `{ $and: [{ a: 1 }, { b: 2 }] }` | | `$or` | Any sub-filter matches | `{ $or: [{ x: 1 }, { y: 2 }] }` | | `$nor` | No sub-filter matches | `{ $nor: [{ status: 'draft' }, { status: 'deleted' }] }` | | `$not` | The sub-filter doesn't match. Takes one filter object, at the top level. | `{ $not: { price: { $gt: 100 } } }` | `$gt`, `$gte`, `$lt`, and `$lte` require a number; any other value throws `CyborgDBValidationError`. `$not` can't be nested inside a field (`{ price: { $not: ... } }` is rejected); wrap the whole condition instead. `$regex` and `$contains` resolve from the index only on fields created with `pattern: true`: `query()` falls back to a slower post-filter otherwise, and `queryMetadata()` rejects the filter. ### Examples ```typescript theme={null} import type { FilterExpression } from 'cyborgdb'; // Equality const simpleFilter: FilterExpression = { category: 'research' }; // Range const rangeFilter: FilterExpression = { published_year: { $gte: 2020, $lte: 2024 } }; // Compound const complexFilter: FilterExpression = { $and: [ { category: 'research' }, { confidence: { $gte: 0.9 } }, { $or: [{ language: 'en' }, { translated: true }] }, ], }; ``` ### Dates CyborgDB has no date type. Store dates in metadata as integer milliseconds since the Unix epoch (UTC), so range operators work on them. Don't store `Date` objects: the SDK sends them as ISO strings, which only support equality filters. ```typescript theme={null} const publishedMs = Date.UTC(2026, 0, 15); // 15 January 2026, 00:00 UTC await index.upsert({ items: [{ id: 'doc1', vector: [0.1, 0.2, 0.3, 0.4], metadata: { publishedMs } }], }); // Everything published on or after 2026-01-01 const results = await index.queryMetadata({ filters: { publishedMs: { $gte: Date.UTC(2026, 0, 1) } }, }); console.log(results); // Output: [ { id: 'doc1' } ] ``` Values come back as numbers. Convert one back to a `Date` with: ```typescript theme={null} const [item] = await index.get({ ids: ['doc1'], include: ['metadata'] }); const published = new Date(Number(item.metadata?.publishedMs)); console.log(published.toISOString()); // Output: 2026-01-15T00:00:00.000Z ``` ## Distance metrics | Metric | Description | | - | - | | `cosine` | Cosine distance. Suited to normalized embeddings. | | `euclidean` | Euclidean (L2) distance. | | `squared_euclidean` | Squared Euclidean distance. Same ranking as `euclidean`, without the square root. | ## Response types | Type | Fields | Returned by | | - | - | - | | `UpsertResponse` | `status: string`, `message?: string` | [`upsert()`](./encrypted-index/upsert) | | `DeleteResponse` | `status: string`, `message?: string` | [`delete()`](./encrypted-index/delete) | | `TrainResponse` | `status: string`, `message?: string` | [`train()`](./encrypted-index/train) | | `HealthResponse` | `status: string`, plus other string fields such as `api_version` and `version` | [`getHealth()`](./client/get-health) | | `GetResultItem` | `id: string`, `vector?: number[]`, `contents?: string`, `metadata?: VectorMetadata` | [`get()`](./encrypted-index/get) | | `QueryResponse` | `results: QueryResultItem[] \| QueryResultItem[][]` | [`query()`](./encrypted-index/query) | Since v0.18, `UpsertResponse` and `DeleteResponse` no longer declare `upsertedCount` / `deletedCount`; those fields were never set. `message` reports how many IDs were sent, not how many existed: deleting an ID that doesn't exist still counts it. ## TypeScript types ### JSON types ```typescript theme={null} type JsonPrimitive = string | number | boolean | null; type JsonValue = JsonPrimitive | JsonObject | JsonArray; interface JsonObject { [key: string]: JsonValue } type JsonArray = JsonValue[]; type VectorMetadata = JsonObject; ``` ### Filter types ```typescript theme={null} type FilterExpression = { [key: string]: FilterValue | FilterOperator }; type FilterValue = JsonPrimitive | JsonArray; interface FilterOperator { $eq?: FilterValue; $ne?: FilterValue; $gt?: number; $gte?: number; $lt?: number; $lte?: number; $in?: JsonArray; $nin?: JsonArray; $and?: FilterExpression[]; $or?: FilterExpression[]; $nor?: FilterExpression[]; $not?: FilterExpression; $exists?: boolean; $regex?: string; $contains?: string; } ``` `FilterOperator` places `$not` inside a field, which the service rejects. A top-level `{ $not: { ... } }` filter works on the service but doesn't match these types; cast it with `as FilterExpression`. ### Request models The package also exports the generated request and response models `CreateIndexRequest`, `UpsertRequest`, `BatchQueryRequest`, `TrainRequest`, `GetRequest`, `DeleteRequest`, `IndexOperationRequest`, `GetResponseModel`, `ErrorResponseModel`, and `HTTPValidationError`. The SDK methods build these for you; you only need them to call the REST API directly. ## Utility functions | Function | Description | | - | - | | `isJsonValue(value: unknown): value is JsonValue` | Checks for JSON primitives, arrays, and objects. It doesn't reject non-plain objects such as `Date` or `Map`, or `NaN`, and it treats any object that appears twice as circular, even when it isn't. | | `isError(error: unknown): error is Error` | `true` if `error` is an `Error` instance. | | `getErrorMessage(error: unknown): string` | `error.message` for an `Error`, otherwise `String(error)`. | ```typescript theme={null} import { isJsonValue } from 'cyborgdb'; const circular: Record = {}; circular.self = circular; console.log(isJsonValue({ tags: ['ai', 'ml'], score: 0.9 }), isJsonValue(circular)); // Output: true false ``` `VERSION` is the SDK version string, e.g. `'0.18.0'`. # Client Source: https://docs.cyborg.co/versions/latest/service/python-sdk/client/client `Client` is the entry point of the CyborgDB Python SDK. It connects to a running CyborgDB service and creates, loads, and lists encrypted indexes. ## Constructor ```python theme={null} Client(base_url, api_key=None, verify_ssl=None) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `base_url` | `str` | - | Base URL of the CyborgDB service, e.g. `"http://localhost:8000"`. | | `api_key` | `str` | `None` | *(Optional)* Service authentication credential, sent as the `X-API-Key` header. Required only when the service has authentication enabled. | | `verify_ssl` | `bool` | `None` | *(Optional)* TLS certificate verification. `None` auto-detects; see [TLS verification](#tls-verification). | > [!NOTE] > > `api_key` is the service **authentication** credential: the root key or a per-user `cdbk_` token. It is required only when the service runs with `CYBORGDB_SERVICE_ROOT_KEY` set; against an unauthenticated service (the default), omit it. This is distinct from the service's `CYBORGDB_API_KEY` license key. See [Managing Keys](../../guides/advanced/managing-keys). ### Example Usage ```python theme={null} from cyborgdb import Client client = Client(base_url='http://localhost:8000', api_key='your-api-key') ``` ## TLS verification `verify_ssl` decides whether the SDK checks the service's TLS certificate: | `base_url` | `verify_ssl=None` (default) | `verify_ssl=True` | `verify_ssl=False` | | - | - | - | - | | `http://…` | No TLS | No TLS (logs that the setting is ignored) | No TLS | | `https://` with host `localhost`, `127.0.0.1`, or `::1` | Verification **off** (logs a warning) | Verification on | Verification off (logs a warning) | | Any other `https://` URL | Verification on | Verification on | Verification off (logs a warning) | ## Errors Failed requests raise a subclass of `cyborgdb.CyborgDBError` chosen by HTTP status, such as `NotFoundError` for `404` or `AuthenticationError` for `401`. Arguments rejected inside the SDK, before a request is sent, raise `cyborgdb.ValidationError`. See [Errors](../errors) for the full list. ```python theme={null} import cyborgdb try: Client(base_url='http://localhost:8000', api_key='wrong-key').list_indexes() except cyborgdb.AuthenticationError as e: print(e.status_code) # Output: 401 ``` # Create Index Source: https://docs.cyborg.co/versions/latest/service/python-sdk/client/create-index Creates a new encrypted index on the service and returns an `EncryptedIndex` bound to it. ```python theme={null} client.create_index( index_name, index_key = None, kms_name = None, dimension = None, embedding_model = None, metric = None, storage_precision = None, metadata_schema = None, text_fields = None, bm25_k1 = None, bm25_b = None, ) ``` > [!NOTE] > > There is one index type, configured with flat keyword arguments. The earlier `IndexIVFFlat`, `IndexIVFPQ`, and `IndexIVFSQ` types and the `index_config` argument no longer exist. ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `index_name` | `str` | - | Unique name for the index. | | `index_key` | `bytes` | `None` | *(Optional)* 32-byte encryption key (SDK-supplied KEK). Pass either `index_key` or `kms_name`, never both. | | `kms_name` | `str` | `None` | *(Optional)* Name of a `kms.registry` entry in the service YAML. The service generates the KEK and wraps it with that provider; the SDK never sees the plaintext key. | | `dimension` | `int` | `None` | *(Optional)* Vector dimensionality. When omitted, the service detects it from the first upsert. | | `embedding_model` | `str` | `None` | *(Optional)* Name of one of the service's built-in embedding models (listed by `GET /v1/embedding-models`), used for automatic embedding generation. When set, `dimension` is taken from the model. | | `metric` | `str` | `None` (service default: `"euclidean"`) | *(Optional)* `"euclidean"`, `"squared_euclidean"`, or `"cosine"`. | | `storage_precision` | `str` | `None` (service default: `"float32"`) | *(Optional)* Storage format for the index's stored vector embeddings. See [Storage precision](#storage-precision). | | `metadata_schema` | `Dict[str, Dict[str, bool]]` | `None` | *(Optional)* Per-field metadata indexing policy. Fixed at creation and cannot be changed later. See [Metadata schema](#metadata-schema). | | `text_fields` | `List[str]` | `None` | *(Optional)* Metadata fields to index for BM25 full-text search. Shorthand for `{"full_text": True}` in `metadata_schema`. Enables `text=` on [`query()`](../encrypted-index/query) and [`query_metadata()`](../encrypted-index/query-metadata). | | `bm25_k1` | `float` | `None` (service default: `1.2`) | *(Optional)* BM25 term-frequency saturation, `>= 0`. Requires at least one full-text field. | | `bm25_b` | `float` | `None` (service default: `0.75`) | *(Optional)* BM25 length-normalization strength, in `[0, 1]`. Requires at least one full-text field. | ### Key management Pass exactly one of `index_key` or `kms_name`. The service rejects both together with `ValidationError` (HTTP `400`), whatever the KMS provider. * **SDK-supplied KEK:** pass `index_key`. Supply the same key again on every [`load_index()`](./load-index). * **KMS-backed:** pass `kms_name`. The service generates the key, wraps it with the named provider, and stores the wrapped key. Later calls omit `index_key`. ### Storage precision `storage_precision` sets the format used to store the index's vector embeddings. Every value works with every metric. | Value | Bits per dimension | | - | - | | `"float32"` | 32 | | `"float16"` | 16 | | `"tq12"` | 12 | | `"tq8"` | 8 | | `"tq6"` | 6 | | `"tq4"` | 4 | The `tq*` values are TurboQuant tiers; lower tiers use less storage in exchange for a small recall and latency cost. ### Metadata schema `metadata_schema` sets how each metadata field is indexed. Metadata itself stays schemaless: this controls indexing, not what may be stored. Fields left out get the default policy (indexed and filterable). Nested fields use dot-paths such as `"loc.city"`. ```python theme={null} metadata_schema = { "title": {"filterable": True, "pattern": True}, # regex-searchable "internal_blob": {"filterable": False}, # stored, not indexed "body": {"full_text": True}, # BM25 full-text search } ``` Each field takes three settings: | Setting | Default | Effect | | - | - | - | | `filterable` | `True` | Indexes the field, so filters on it resolve from the index. `False` still stores the field but doesn't index it; see [Filters the index cannot answer](#filters-the-index-cannot-answer). | | `pattern` | `False` | Also builds a regex dictionary, so `$regex` and `$contains` resolve from the index. Requires `filterable=True`. | | `full_text` | `False` | Sends the field's text through the BM25 analyzer instead of exact-match indexing. Implies `filterable=False`; an explicit `filterable=True` with it is rejected with `ValidationError` (HTTP `422`). Can't be combined with `pattern=True`. | #### Filters the index cannot answer The index can answer a filter when the field is filterable and, for `$regex` or `$contains`, the field also has `pattern` set. Any other filter is handled differently depending on the call: | Call | Filter the index can't answer | | - | - | | [`query()`](../encrypted-index/query) without `text` | Still works, but slower: the filter is applied to the decrypted metadata after the search. | | [`query()`](../encrypted-index/query) with `text` | Rejected with `ValidationError`. | | [`query_metadata()`](../encrypted-index/query-metadata) | Rejected with `ValidationError`. | With the schema above: ```python theme={null} {"title": {"$regex": "^Intro"}} # answerable: title is filterable and has pattern {"internal_blob": "abc"} # not answerable: internal_blob isn't filterable {"author": {"$regex": "^Ann"}} # not answerable: author is filterable by default, but has no pattern ``` The stored policy is returned by the [`metadata_schema`](../getters#metadata_schema) getter. ### Returns An `EncryptedIndex` bound to the new index. For KMS-backed indexes it holds no plaintext key. ### Exceptions > [accordion] cyborgdb.ValidationError > > Before any request is sent: neither `index_key` nor `kms_name` is passed, `index_key` is not 32 bytes, or `storage_precision` is not one of the six values above. From the service: the index name already exists, both `index_key` and `kms_name` were passed, or the `kms_name` slot is unknown (HTTP `400`); or `metadata_schema` combines settings that aren't allowed (HTTP `422`). > [accordion] cyborgdb.AuthenticationError > > The client's `api_key` is missing or invalid (HTTP `401`), or is a per-user key: creating an index requires the root key (HTTP `403`). > [accordion] cyborgdb.ServiceError > > The service returns `5xx`, including KMS wrap failures (`502`). > [accordion] cyborgdb.TransportError > > The service can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage #### SDK-supplied key ```python theme={null} from cyborgdb import Client client = Client(base_url='http://localhost:8000', api_key='your-api-key') index_key = client.generate_key() # The dimension is detected from the first upsert index = client.create_index('documents', index_key=index_key) ``` > [!NOTE] > > Store `index_key` securely: it is needed to load the index again. See [Generate Key](./generate-key). #### Explicit dimension and metric ```python theme={null} index = client.create_index( 'documents_384', index_key=index_key, dimension=384, metric='cosine', ) ``` #### KMS-backed index ```python theme={null} # The service generates the key and wraps it with the 'prod-aws' registry slot. index = client.create_index( 'kms_documents', kms_name='prod-aws', dimension=384, ) # Later calls, including load_index(), omit index_key. ``` #### Automatic embeddings ```python theme={null} # The dimension is taken from the embedding model index = client.create_index( 'semantic_docs', index_key=index_key, embedding_model='all-MiniLM-L6-v2', ) ``` See [Auto-Generate Embeddings](../../guides/data-operations/add-items#automatic-embedding-generation). #### Reduced storage with TurboQuant ```python theme={null} index = client.create_index( 'compact_docs', index_key=index_key, dimension=768, storage_precision='tq8', ) ``` #### Per-field metadata policy ```python theme={null} index = client.create_index( 'docs_index', index_key=index_key, dimension=4, metadata_schema={ 'title': {'filterable': True, 'pattern': True}, 'internal_blob': {'filterable': False}, }, ) index.upsert([ {'id': 'doc1', 'vector': [0.1, 0.2, 0.3, 0.4], 'metadata': {'title': 'intro to encryption'}}, {'id': 'doc2', 'vector': [0.5, 0.6, 0.7, 0.8], 'metadata': {'title': 'advanced setup'}}, ]) # $regex resolves from the index because 'title' has pattern=True print(index.query_metadata(filters={'title': {'$regex': '^intro'}})) # Output: [{'id': 'doc1'}] ``` #### Full-text search fields ```python theme={null} index = client.create_index( 'articles', index_key=index_key, dimension=4, text_fields=['body'], ) print(index.bm25) # Output: {'k1': 1.2, 'b': 0.75, 'analyzer_version': 'en/1;sw=2de831ef7be676b6;snowball-english-utf8-3.0.1'} ``` # Generate Key Source: https://docs.cyborg.co/versions/latest/service/python-sdk/client/generate-key Generates a random 32-byte (256-bit) key for creating an encrypted index with an SDK-supplied key. ```python theme={null} @staticmethod Client.generate_key(save: bool = False) -> bytes ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `save` | `bool` | `False` | *(Optional)* Store the key at `~/.cyborgdb/index_key`, or reuse the key already stored there. | ### Returns `bytes`: 32 bytes from Python's `secrets.token_bytes(32)`, which reads the operating system's cryptographic random source. ### Saving the key With `save=True`: * If `~/.cyborgdb/index_key` exists and holds exactly 32 bytes, that key is returned and no new key is generated. * Otherwise a new key is generated, written to that file, and returned. The file is not encrypted, and the SDK logs a warning each time it's used. Use `save=True` for local development only; in production, store keys in a secrets manager or use a KMS-backed index. See [Managing Encryption Keys](../../guides/advanced/managing-keys). > [!WARNING] > > An index created with an SDK-supplied key can only be opened with that exact key. If the key is lost, the index's data can't be decrypted. ### Example Usage ```python theme={null} from cyborgdb import Client client = Client(base_url='http://localhost:8000', api_key='your-api-key') index_key = Client.generate_key() print(len(index_key)) # Output: 32 index = client.create_index('my-secure-index', index_key) # Keep the key somewhere safe, e.g. as hex in a secrets manager key_hex = index_key.hex() ``` # Get Health Source: https://docs.cyborg.co/versions/latest/service/python-sdk/client/get-health Returns the health status of the CyborgDB service, to check that it is reachable and running. ```python theme={null} client.get_health() ``` ### Returns `Dict[str, str]` with these keys: | Key | Description | | - | - | | `status` | Service health, `"healthy"` when the service is up. | | `api_version` | REST API version, e.g. `"v1"`. | | `version` | CyborgDB service version. | ### Exceptions > [accordion] cyborgdb.TransportError > > The service can't be reached. > [accordion] cyborgdb.ServiceError > > The service returns `5xx`. See [Errors](../errors) for the full hierarchy. ### Example Usage ```python theme={null} from cyborgdb import Client client = Client(base_url='http://localhost:8000', api_key='your-api-key') health = client.get_health() print(health) # Output: {'status': 'healthy', 'api_version': 'v1', 'version': '0.18.0'} ``` # List Indexes Source: https://docs.cyborg.co/versions/latest/service/python-sdk/client/list-indexes Returns the names of all indexes on the CyborgDB service. ```python theme={null} client.list_indexes() ``` ### Returns `List[str]`: index names. Empty when the service has no indexes. ### Exceptions > [accordion] cyborgdb.AuthenticationError > > The client's `api_key` is missing or invalid (HTTP `401`), or is a per-user key: listing indexes requires the root key (HTTP `403`). > [accordion] cyborgdb.ServiceError > > The service returns `5xx`. > [accordion] cyborgdb.TransportError > > The service can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage ```python theme={null} from cyborgdb import Client client = Client(base_url='http://localhost:8000', api_key='your-api-key') indexes = client.list_indexes() print(indexes) # Output: ['documents', 'embeddings', 'semantic-search'] ``` # Load Index Source: https://docs.cyborg.co/versions/latest/service/python-sdk/client/load-index Loads an existing encrypted index and returns an `EncryptedIndex` bound to it. ```python theme={null} client.load_index( index_name, index_key = None, ) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `index_name` | `str` | - | Name of an existing index. | | `index_key` | `bytes` | `None` | *(Optional)* The 32-byte key the index was created with. Required for SDK-supplied-key indexes; omit it for KMS-backed indexes (created with `kms_name`). | > [!WARNING] > > For SDK-supplied-key indexes, `index_key` must be the exact key passed to `create_index()`. A KMS-backed index fails to load if its `kms_name` slot is missing from the service YAML or its provider is unreachable, with `cyborgdb.AuthenticationError` (HTTP `401`). ### Returns An `EncryptedIndex` bound to the loaded index. ### Exceptions > [accordion] cyborgdb.ValidationError > > `index_key` is passed but is not 32 bytes. Raised before any request is sent. > [accordion] cyborgdb.NotFoundError > > No index named `index_name` exists, or `index_key` doesn't match (HTTP `404`, in most cases). > [accordion] cyborgdb.AuthenticationError > > `index_key` doesn't match an index that has vectors and is already in the service's cache, or the client's `api_key` is missing or invalid; or, for a KMS-backed index, its KMS slot is missing or the provider call fails (HTTP `401`). > [accordion] cyborgdb.ServiceError > > The service returns `5xx`. > [accordion] cyborgdb.TransportError > > The service can't be reached. See [Errors](../errors) for the full hierarchy. > [!NOTE] > > A wrong key returns `cyborgdb.AuthenticationError` (HTTP `401`) when the index has vectors and the service already has it cached, and `cyborgdb.NotFoundError` (HTTP `404`) otherwise, for example on an empty index or right after the service restarts. Catch both when checking for a bad key. ### Example Usage #### SDK-supplied-key index ```python theme={null} from cyborgdb import Client client = Client(base_url='http://localhost:8000', api_key='your-api-key') # The same 32 bytes that were passed to create_index(), e.g. stored as hex index_key = bytes.fromhex('your-64-character-hex-key') index = client.load_index('my_index', index_key) print(index.index_name) # Output: my_index ``` #### KMS-backed index ```python theme={null} # No key needed: the service unwraps it with the index's KMS provider. index = client.load_index('kms_index') ``` # Delete Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/delete Permanently removes items from the index by ID, along with their contents and metadata. ```python theme={null} index.delete(ids) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `ids` | `List[str]` | - | IDs of the items to delete. An empty list is a no-op. | ### Returns `None` ### Exceptions > [accordion] cyborgdb.ValidationError > > The service rejects the request (HTTP `422`), for example when `ids` isn't a list of strings. > [accordion] cyborgdb.AuthenticationError > > The `index_key` or `api_key` is invalid (HTTP `401`). > [accordion] cyborgdb.ServiceError / cyborgdb.TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage ```python theme={null} index.delete(["doc1", "doc2"]) print(index.list_ids()) # Output: ['doc3'] ``` # Delete Index Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/delete-index > [!WARNING] > > Deleting an index is irreversible. Deletes the index and all of its data from the CyborgDB service. ```python theme={null} index.delete_index() ``` ### Returns `None` ### Exceptions > [accordion] cyborgdb.NotFoundError > > The index doesn't exist, for example because it was already deleted (HTTP `404`). > [accordion] cyborgdb.AuthenticationError > > The `index_key` or `api_key` is invalid (HTTP `401`), or the client is using a per-user key: deleting an index requires the root key (HTTP `403`). > [accordion] cyborgdb.ServiceError / cyborgdb.TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage ```python theme={null} index.delete_index() print(index.index_name in client.list_indexes()) # Output: False ``` # Get Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/get Retrieves items from the index by ID, with the fields you choose. ```python theme={null} index.get(ids, include=["vector", "contents", "metadata"]) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `ids` | `List[str]` | - | IDs of the items to retrieve. | | `include` | `List[str]` | `["vector", "contents", "metadata"]` | *(Optional)* Fields to return besides `id`. | ### Returns `List[Dict]`, one dict per ID found. IDs that don't exist are left out of the result without an error, and an empty `ids` list returns `[]`. When `include` doesn't contain `"vector"`, an existing item that has none of the requested fields is also left out. ```python theme={null} { "id": str, # Always returned "vector": List[float], # When "vector" is in include "contents": str, # When "contents" is in include; "" if the item has no contents "metadata": Dict, # When "metadata" is in include } ``` `contents` is always a `str`. Contents upserted as `bytes` come back as their base64 text; decode them with `base64.b64decode()`. ### Exceptions > [accordion] cyborgdb.AuthenticationError > > The `index_key` or `api_key` is invalid (HTTP `401`). > [accordion] cyborgdb.ServiceError / cyborgdb.TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage ```python theme={null} results = index.get(["doc1", "doc2", "missing-id"], include=["contents", "metadata"]) for item in results: print(item["id"], repr(item["contents"]), item["metadata"]) # Output: # doc1 'First document' {} # doc2 '' {'category': 'news'} ``` #### Decode bytes contents ```python theme={null} import base64 index.upsert([{"id": "img1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": b"\x89PNG..."}]) item = index.get(["img1"], include=["contents"])[0] raw = base64.b64decode(item["contents"]) print(raw[:4]) # Output: b'\x89PNG' ``` # List IDs Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/list-ids Returns every item ID in the index. ```python theme={null} index.list_ids() ``` ### Returns `List[str]`: all IDs in the index. ### Exceptions > [accordion] cyborgdb.AuthenticationError > > The `index_key` or `api_key` is invalid (HTTP `401`). > [accordion] cyborgdb.ServiceError / cyborgdb.TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage ```python theme={null} all_ids = index.list_ids() print(len(all_ids)) # Output: 3 print("doc1" in all_ids) # Output: True # Fetch items in batches of 100 for i in range(0, len(all_ids), 100): items = index.get(all_ids[i:i + 100]) ``` # Query Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/query Finds the nearest neighbors of one or more query vectors. With `query_contents`, the service embeds the text first (the index needs an `embedding_model`). With `text`, the query becomes **hybrid**: BM25 full-text ranking is fused with the vector ranking. ```python theme={null} # Single vector index.query(query_vectors=vector, top_k=10) # Batch of vectors index.query(query_vectors=vectors, top_k=10) # Text, embedded by the service index.query(query_contents=text, top_k=10) # Hybrid (BM25 + vector); needs an index with a full-text field index.query(query_vectors=vector, text="encrypted search", top_k=10) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `query_vectors` | `List[float]`, `List[List[float]]`, or `np.ndarray` | `None` | *(Optional)* One query vector, or a batch. A NumPy array is sent through the binary path, [`query_binary()`](./query-binary). | | `query_contents` | `str` | `None` | *(Optional)* Text for the service to embed and search with. Requires an index created with `embedding_model`. Ignored when `query_vectors` is a NumPy array. | | `top_k` | `int` | `None` (service default: `100`) | *(Optional)* Results to return per query. Must be at least `1`. | | `n_probes` | `int` | `None` (service default: auto) | *(Optional)* Clusters to probe. Higher values improve recall and add latency. | | `filters` | `Dict` | `None` | *(Optional)* Metadata filter. See [Metadata filtering](../types#metadata-filtering). | | `include` | `List[str]` | `None` (service default: `[]`) | *(Optional)* Extra fields per result: `"distance"` and `"metadata"`. `id` is always returned. See [Result fields](#result-fields). | | `greedy` | `bool` | `None` (service default: `False`) | *(Optional)* Use greedy search. | | `rerank_mult` | `int` | `None` (service default: `50`) | *(Optional)* Stage 1 returns `top_k * rerank_mult` candidates before reranking narrows them to `top_k`. Higher values trade latency for recall. | | `text` | `str` | `None` | *(Optional)* Query text for a BM25 leg, which makes the query hybrid. Requires an index with at least one full-text field. `query_vectors` is still required. | | `text_fields` | `List[str]` | `None` (all full-text fields) | *(Optional)* Full-text fields the BM25 leg searches. Naming a field that isn't full-text returns `ValidationError`. | | `text_field_weights` | `List[float]` | `None` (`1.0` each) | *(Optional)* Weight per searched field, in the same order as `text_fields`. | | `require_all_terms` | `bool` | `None` (service default: `False`) | *(Optional)* Match only items containing every query term (AND) instead of any term (OR). | | `alpha` | `float` | `None` (service default: `0.5`) | *(Optional)* Blend of the two legs, in `[0, 1]`: `0` is pure BM25, `1` is pure vector. At exactly `0` or `1` the other leg isn't run. | | `rrf_k` | `float` | `None` (service default: `60`) | *(Optional)* Reciprocal rank fusion smoothing constant. Must be `> 0`. | | `window_mult` | `int` | `None` (service default: `3`) | *(Optional)* Candidates retrieved per leg, as a multiple of `top_k`. Must be `>= 1`. | ### Returns * **Single query vector:** `List[Dict]`, one dict per neighbor. * **Batch of two or more vectors:** `List[List[Dict]]`, one inner list per query vector. A query with exactly one vector always returns single results, even when it's sent as a batch or through the binary path. #### Result fields ```python theme={null} { "id": str, # Always returned "distance": float, # Vector queries, when "distance" is in include. Lower is closer. "score": float, # Hybrid queries only, instead of distance. Higher is more relevant. "metadata": Dict, # When "metadata" is in include } ``` `query()` never returns `vector` or `contents`, even when they're listed in `include`. To read them, pass the result IDs to [`get()`](./get). ### Exceptions > [accordion] pydantic.ValidationError > > Neither `query_vectors` nor `query_contents` is passed. Raised before any request is sent. > [accordion] cyborgdb.ValidationError > > * A NumPy `query_vectors` array is not 1-D or 2-D. Raised before any request is sent. > * The service rejects the query (HTTP `400`/`422`): wrong vector dimension, `text` on an index without full-text fields, or an out-of-range `alpha`, `rrf_k`, or `window_mult`. Other numeric parameters aren't range-checked. > [accordion] cyborgdb.AuthenticationError > > The `index_key` or `api_key` is invalid (HTTP `401`). > [accordion] cyborgdb.ServiceError / cyborgdb.TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage #### Single vector ```python theme={null} results = index.query( query_vectors=[0.1, 0.2, 0.3, 0.4], top_k=2, include=["distance", "metadata"], ) for result in results: print(result["id"], round(result["distance"], 4), result["metadata"]) # Output: # doc1 0.0 {'category': 'news'} # doc2 0.8 {'category': 'research'} ``` #### Batch of vectors ```python theme={null} batch_results = index.query( query_vectors=[ [0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], ], top_k=1, include=["distance"], ) for i, results in enumerate(batch_results): print(i, [r["id"] for r in results]) # Output: # 0 ['doc1'] # 1 ['doc2'] ``` #### Text, embedded by the service ```python theme={null} # The index must have been created with embedding_model=... results = index.query( query_contents="machine learning in healthcare", top_k=3, ) print([r["id"] for r in results]) ``` #### Hybrid (BM25 + vector) The index needs at least one full-text field, set with `text_fields` or `{"full_text": True}` in [`create_index()`](../client/create-index#metadata-schema). ```python theme={null} results = index.query( query_vectors=[0.1, 0.2, 0.3, 0.4], text="encrypted search", top_k=2, alpha=0.5, include=["metadata"], ) for result in results: print(result["id"], round(result["score"], 4)) # Output: # doc1 0.0164 # doc2 0.0161 ``` #### Filters and search options ```python theme={null} results = index.query( query_vectors=[0.1, 0.2, 0.3, 0.4], top_k=20, n_probes=5, rerank_mult=20, greedy=True, filters={"category": "news"}, include=["distance", "metadata"], ) for result in results: print(result["id"], result["metadata"]["category"]) # Output: doc1 news ``` # Query (Binary) Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/query-binary `query_binary()` sends query vectors as base64-encoded little-endian `float32` instead of JSON arrays, which is faster for large batches. It accepts the same search and hybrid parameters as [`query()`](./query), except `query_contents`. ```python theme={null} index.query_binary( query_vectors, top_k=None, n_probes=None, filters=None, include=None, greedy=None, rerank_mult=None, text=None, text_fields=None, text_field_weights=None, require_all_terms=None, alpha=None, rrf_k=None, window_mult=None, ) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `query_vectors` | `np.ndarray` | - | Shape `(dim,)` for one query or `(n_queries, dim)` for a batch. Cast to little-endian `float32` if needed. | | `top_k` | `int` | `None` (service default: `100`) | *(Optional)* Results to return per query. Must be at least `1`. | | `n_probes` | `int` | `None` (service default: auto) | *(Optional)* Clusters to probe. | | `filters` | `Dict` | `None` | *(Optional)* Metadata filter. See [Metadata filtering](../types#metadata-filtering). | | `include` | `List[str]` | `None` (service default: `[]`) | *(Optional)* Extra fields per result: `"distance"` and `"metadata"`. | | `greedy` | `bool` | `None` (service default: `False`) | *(Optional)* Use greedy search. | | `rerank_mult` | `int` | `None` (service default: `50`) | *(Optional)* Stage 1 candidate multiplier before reranking. | | `text`, `text_fields`, `text_field_weights`, `require_all_terms`, `alpha`, `rrf_k`, `window_mult` | | `None` | *(Optional)* Hybrid search parameters. Same meaning and service defaults as on [`query()`](./query#parameters). | ### Returns * **1-D `query_vectors`:** `List[Dict]`, one dict per neighbor. * **2-D `query_vectors` with two or more rows:** `List[List[Dict]]`, one inner list per query vector. A 2-D array with one row returns a flat `List[Dict]`. Each dict has `id`, plus `distance` (vector query) or `score` (hybrid query), and `metadata` when requested. As with [`query()`](./query#result-fields), `vector` and `contents` are not returned. ### Exceptions > [accordion] cyborgdb.ValidationError > > * Also a `TypeError`. `query_vectors` is not a NumPy array. > * `query_vectors` is not 1-D or 2-D. > * The service rejects the query (HTTP `400`/`422`), for example a wrong vector dimension. > [accordion] cyborgdb.AuthenticationError > > The `index_key` or `api_key` is invalid (HTTP `401`). > [accordion] cyborgdb.ServiceError / cyborgdb.TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage #### Single query ```python theme={null} import numpy as np q = np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float32) results = index.query_binary(q, top_k=2, include=["distance"]) for r in results: print(r["id"], round(r["distance"], 4)) # Output: # doc1 0.0 # doc2 0.8 ``` #### Batch query ```python theme={null} queries = np.random.rand(32, 4).astype(np.float32) batch_results = index.query_binary(queries, top_k=10) print(len(batch_results)) # Output: 32 ``` > [!TIP] > > [`query()`](./query) already uses this binary path when `query_vectors` is a NumPy array. Call `query_binary()` directly to make the choice explicit. # Query Metadata Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/query-metadata Finds items by metadata alone, with no query vector. `query_metadata()` resolves the filter against the encrypted metadata index and returns the matching IDs. With `text`, it also ranks matches by BM25 relevance. It works on untrained indexes. ```python theme={null} index.query_metadata( filters=None, top_k=None, order_by=None, ascending=True, text=None, text_fields=None, text_field_weights=None, require_all_terms=None, ) -> List[MetadataResult] ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `filters` | `Dict[str, Any]` | `None` | *(Optional)* Metadata filter; `None` or `{}` matches everything. See [Filter constraints](#filter-constraints). | | `top_k` | `int` | `None` | *(Optional)* Maximum results; `None` returns every match. Applied after `order_by`. | | `order_by` | `str` or `Dict[str, int]` | `None` | *(Optional)* Sort by a metadata field: a field name (direction set by `ascending`), or a single-field dict such as `{"views": -1}` for descending. Can't be combined with `text`. | | `ascending` | `bool` | `True` | *(Optional)* Sort direction when `order_by` is a field name. Ignored when `order_by` is a dict. | | `text` | `str` | `None` | *(Optional)* Query text for BM25 full-text ranking. Requires an index with at least one full-text field. Results then carry a `score`, sorted by relevance, and `filters` act as a pre-filter. | | `text_fields` | `List[str]` | `None` (all full-text fields) | *(Optional)* Full-text fields to search. | | `text_field_weights` | `List[float]` | `None` (`1.0` each) | *(Optional)* Weight per searched field, in the same order as `text_fields`. | | `require_all_terms` | `bool` | `None` (service default: `False`) | *(Optional)* Match only items containing every query term. | > [!NOTE] > > * Without `order_by` or `text`, results come back in no particular order. > * Items missing the `order_by` field, or holding a non-scalar value in it, sort last. ### Filter constraints [`query()`](./query) falls back to a post-filter over decrypted metadata when the index can't answer a filter, for pure vector queries. `query_metadata()` has no fallback, so every filter must be answerable from the index. The index's [`metadata_schema`](../client/create-index#metadata-schema) is therefore enforced here: * `$regex` and `$contains` need a field created with `pattern: True`. * A field created with `filterable: False` can't be filtered on. * `$type` isn't supported. Any of these returns `cyborgdb.ValidationError` (HTTP `400`) with the reason. Nested dot-paths such as `"loc.city"` are supported. ### Returns `List[MetadataResult]`: one dict per match. ```python theme={null} { "id": str, # Always returned "score": float, # Only when text is set. BM25 relevance; higher is more relevant. } ``` ### Exceptions > [accordion] cyborgdb.ValidationError > > `order_by` is a dict with more than one key, or is neither a `str` nor a dict (raised before any request is sent), or the service rejects the query (HTTP `400`): see [Filter constraints](#filter-constraints). > [accordion] cyborgdb.AuthenticationError > > The `index_key` or `api_key` is invalid (HTTP `401`). > [accordion] cyborgdb.ServiceError / cyborgdb.TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage #### Filter only ```python theme={null} results = index.query_metadata(filters={"label": "dog"}) print(sorted(r["id"] for r in results)) # unordered without order_by # Output: ['101', '102'] ``` #### Operators and a result cap ```python theme={null} results = index.query_metadata( filters={"$and": [{"label": "cat"}, {"confidence": {"$gte": 0.9}}]}, top_k=10, ) print(results) # Output: [{'id': '201'}] ``` #### Sorted by a field ```python theme={null} # Ascending by "views" results = index.query_metadata(filters={"label": "dog"}, order_by="views") # Descending by "views"; top_k applies after the sort results = index.query_metadata( filters={"label": "dog"}, order_by={"views": -1}, top_k=5, ) print([r["id"] for r in results]) # Output: ['102', '101'] ``` #### Regex match ```python theme={null} # "title" must have been created with pattern=True results = index.query_metadata(filters={"title": {"$regex": "^intro"}}) ``` #### Full-text search ```python theme={null} # The index needs a full-text field, e.g. create_index(..., text_fields=["body"]) results = index.query_metadata(text="encrypted search", top_k=5) for r in results: print(r["id"], round(r["score"], 4)) ``` For filter syntax and operators, see [Metadata filtering](../types#metadata-filtering). # Train Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/train Clusters the index's vectors into IVF lists so queries only scan the closest lists. `train()` waits until training finishes before returning. ```python theme={null} index.train( n_lists=None, batch_size=None, max_iters=None, tolerance=None, max_memory=None, ) ``` > [!TIP] > > The service also trains indexes automatically. An untrained index is trained once it holds more than `AUTO_TRAIN_MIN_VECTORS` vectors (default `65536`), and a trained index is retrained when its size calls for more lists than it has. Set `AUTO_TRAIN_DISABLED=true` on the service to turn this off. Call `train()` yourself to train a smaller index, or to make sure training is finished before running queries or benchmarks. ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `n_lists` | `int` | `None` (auto) | *(Optional)* Number of IVF lists. `None` picks the square root of the vector count, rounded to a power of two. | | `batch_size` | `int` | `None` (ignored) | *(Optional)* Vectors processed per training batch. | | `max_iters` | `int` | `None` (ignored) | *(Optional)* Maximum clustering iterations. | | `tolerance` | `float` | `None` (ignored) | *(Optional)* Convergence tolerance. | | `max_memory` | `int` | `None` (ignored) | *(Optional)* Memory cap for training, in MB. | > [!WARNING] > > Only `n_lists` affects training today. The service accepts `batch_size`, `max_iters`, `tolerance`, and `max_memory` but doesn't pass them to training, so they have no effect. Parameter values aren't range-checked: an out-of-range value such as a negative list count is accepted, and training is skipped as described in [Requirements](#requirements). ### Requirements Training only runs when all three hold: * The index has at least **10,000 vectors**. * It has at least twice as many vectors as `n_lists`. * The vector dimension is a **multiple of 32**, such as 384, 768, or 1536. > [!WARNING] > > `train()` doesn't report a skipped or failed training run. If a requirement isn't met, or training fails on the service, `train()` still returns normally and the index stays untrained. Check [`is_trained()`](../getters#is_trained) after `train()` returns: an untrained index has `n_lists` of `1`. Queries on an untrained index still work. ### Returns `None`. If the index is already training, `train()` waits for that run to finish, then trains again. ### Exceptions > [accordion] cyborgdb.AuthenticationError > > The client isn't using the root key, or the `index_key` is invalid (HTTP `401`/`403`). Training requires the root key. > [accordion] cyborgdb.NotFoundError > > The index doesn't exist (HTTP `404`). > [accordion] cyborgdb.ServiceError / cyborgdb.TransportError > > The service returns `5xx` or can't be reached. A failed training run doesn't raise; see [Requirements](#requirements). See [Errors](../errors) for the full hierarchy. ### Example Usage #### Default settings ```python theme={null} index.train() # train() doesn't raise if training is skipped, so check the result print(index.is_trained(), index.n_lists) # Output: True 128 ``` #### Custom settings ```python theme={null} index.train( n_lists=128, batch_size=4096, max_iters=200, tolerance=1e-7, ) ``` # Upsert Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/upsert Adds vectors to the index, or replaces existing vectors with the same ID. `upsert()` takes one of two shapes: ```python theme={null} # Shape 1: a list of item dicts index.upsert(items) # Shape 2: parallel arrays of IDs and a NumPy array of vectors index.upsert(ids, vectors) ``` ### Parameters #### Shape 1: list of item dicts | Parameter | Type | Default | Description | | - | - | - | - | | `items` | `List[Dict]` | - | One dict per vector. | Each dict can contain: ```python theme={null} { "id": str, # Required. Unique identifier. "vector": List[float], # Optional if the index has an embedding model and "contents" is set. "contents": str | bytes, # Optional. Encrypted before storage. "metadata": Dict, # Optional. Key-value pairs for filtering. } ``` `contents` accepts a `str` or `bytes`. Strings are stored as-is; bytes are base64-encoded first. [`get()`](./get) always returns `contents` as a `str`, so bytes come back as their base64 text: decode them with `base64.b64decode()`. > [!NOTE] > > `datetime` and `date` objects in `metadata` are converted to integer epoch milliseconds before being sent (naive datetimes are treated as UTC; sub-millisecond precision is truncated). Values read back with `get()` come back as the same integer, not a `datetime`. The same conversion runs on filter dicts passed to `query()` / `query_binary()` / `query_metadata()`, so a `{"created": {"$gte": datetime(...)}}` predicate works directly. See [Dates](../types#dates). #### Shape 2: parallel arrays | Parameter | Type | Default | Description | | - | - | - | - | | `ids` | `List[str]` | - | Unique identifier for each vector. | | `vectors` | `np.ndarray` (shape `(n, dim)`) | - | Vector data. Sent as binary through [`upsert_binary()`](./upsert-binary). | Shape 2 can't attach metadata or contents. To send them with parallel arrays, call [`upsert_binary()`](./upsert-binary) directly. > [!WARNING] > > Don't upsert vectors containing `NaN` or infinite values. The service stores them, and later `get` or `query` calls on that index that return vectors or distances fail with a `5xx` error. The SDK doesn't check for them. ### Returns `None` ### Exceptions > [accordion] cyborgdb.ValidationError > > * The arguments don't match either shape (also a `TypeError`), an item has no `id`, or the IDs and vectors differ in length. Raised before any request is sent. > * The service rejects the items (HTTP `400`), for example a vector with the wrong dimension. > [accordion] cyborgdb.AuthenticationError > > The `index_key` or `api_key` is invalid (HTTP `401`). > [accordion] cyborgdb.ServiceError > > The service returns `5xx`. > [accordion] cyborgdb.TransportError > > The service can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage #### Item dicts ```python theme={null} items = [ {"id": "doc1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "First document"}, {"id": "doc2", "vector": [0.5, 0.6, 0.7, 0.8], "metadata": {"category": "news"}}, ] index.upsert(items) ``` #### Parallel arrays ```python theme={null} import numpy as np ids = ["vec1", "vec2", "vec3"] vectors = np.random.rand(3, 4).astype(np.float32) index.upsert(ids, vectors) ``` #### Parallel arrays with metadata and contents ```python theme={null} import numpy as np ids = ["vec4", "vec5", "vec6"] vectors = np.random.rand(3, 4).astype(np.float32) metadata = [{"category": "news"}, {"category": "research"}, None] contents = ["Fourth body", "Fifth body", None] index.upsert_binary(ids, vectors, metadata=metadata, contents=contents) ``` #### Replace an existing item ```python theme={null} index.upsert([{"id": "doc1", "vector": [0.1, 0.2, 0.3, 0.4], "metadata": {"version": 1}}]) # Same ID: replaces the vector, contents, and metadata index.upsert([{"id": "doc1", "vector": [0.2, 0.3, 0.4, 0.5], "metadata": {"version": 2}}]) item = index.get(["doc1"], include=["metadata"])[0] print(item["metadata"]) # Output: {'version': 2} ``` # Upsert (Binary) Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/upsert-binary `upsert_binary()` sends vectors as base64-encoded little-endian `float32` instead of JSON arrays, which is faster for large batches. Unlike the two-argument form of [`upsert()`](./upsert), it also takes parallel `metadata` and `contents`. ```python theme={null} index.upsert_binary( ids, vectors, metadata=None, contents=None, ) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `ids` | `List[str]` | - | Unique identifier for each vector. Length must equal `vectors.shape[0]`. | | `vectors` | `np.ndarray` (shape `(n, dim)`) | - | Vector data. Cast to little-endian `float32` if needed. | | `metadata` | `List[Optional[Dict]]` | `None` | *(Optional)* Metadata per vector, same length as `ids`. Use `None` for entries without metadata. | | `contents` | `List[Optional[str \| bytes]]` | `None` | *(Optional)* Contents per vector, same length as `ids`. Strings are stored as-is; bytes are base64-encoded first. Use `None` for entries without contents. | > [!WARNING] > > Don't upsert vectors containing `NaN` or infinite values. The service stores them, and later `get` or `query` calls on that index that return vectors or distances fail with a `5xx` error. The SDK doesn't check for them. ### Returns `None` ### Exceptions > [accordion] cyborgdb.ValidationError > > * Also a `TypeError`. `vectors` is not a NumPy array. > * `vectors` is not 2-D, or `ids`, `metadata`, or `contents` differ in length from `vectors`. Raised before any request is sent. > * The service rejects the batch (HTTP `400`), for example a vector with the wrong dimension. > [accordion] cyborgdb.ServiceError / cyborgdb.TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors) for the full hierarchy. ### Example Usage ```python theme={null} import numpy as np ids = ["vec1", "vec2", "vec3"] vectors = np.random.rand(3, 4).astype(np.float32) metadata = [ {"category": "news", "lang": "en"}, {"category": "research"}, None, ] contents = ["First doc body", "Second doc body", None] index.upsert_binary(ids, vectors, metadata=metadata, contents=contents) print(index.get(["vec1"], include=["contents"])) # Output: [{'id': 'vec1', 'contents': 'First doc body'}] ``` > [!TIP] > > For small batches, the item-dict form of [`upsert()`](./upsert) is easier to read. Use `upsert_binary()` when the vectors are already a NumPy array and JSON encoding time matters. # User Management (RBAC) Source: https://docs.cyborg.co/versions/latest/service/python-sdk/encrypted-index/users When the service runs with `CYBORGDB_SERVICE_ROOT_KEY` set, `EncryptedIndex` can create, list, and revoke per-index users. These methods require a client created with the root key. > [!NOTE] > > See [Multi-Tenancy & RBAC](../../guides/advanced/multi-tenancy) for the operator-side playbook (modes, key kinds, SDK-supplied indexes). ## create_user Creates a user scoped to this index and returns their API key. ```python theme={null} index.create_user(permissions: List[str]) -> Dict[str, str] ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `permissions` | `List[str]` | Non-empty subset of `["read", "write"]`. | ### Returns `Dict[str, str]`: | Key | Type | Description | | - | - | - | | `user_id` | `str` | Hex identifier for the new user. | | `api_key` | `str` | The user's API key, starting with `cdbk_`. | > [!WARNING] > > The service returns `api_key` only in this response and never stores it. Give it to the user over a secure channel and don't log it. If it's lost, delete the user and create a new one. ### Example ```python theme={null} from cyborgdb import Client ROOT_KEY = 'your-service-root-key' index_key = bytes.fromhex('your-64-character-hex-key') admin = Client(base_url='http://localhost:8000', api_key=ROOT_KEY) index = admin.load_index('documents', index_key) user = index.create_user(permissions=['read', 'write']) print(sorted(user.keys())) # Output: ['api_key', 'user_id'] # The user connects with their own key user_client = Client(base_url='http://localhost:8000', api_key=user['api_key']) ``` *** ## list_users Lists the users created for this index. ```python theme={null} index.list_users() -> List[Dict[str, Any]] ``` ### Returns A list of dicts: | Key | Type | Description | | - | - | - | | `user_id` | `str` | Hex identifier. | | `permissions` | `List[str]` | Subset of `["read", "write"]`. | ### Example ```python theme={null} for u in index.list_users(): print(u['user_id'], u['permissions']) # Output: 99a4a548e6824c45c84ca7c64535fcc9 ['read', 'write'] ``` > [!NOTE] > > Deleting an index doesn't delete its user records. If you create a new index with the same name, `list_users()` on it still returns the old users. They can't read the new index, because their keys don't unwrap its data key; delete them with `delete_user()`. *** ## delete_user Revokes a user. Their access keys for this index are erased, so their `cdbk_` key stops working on the next request. ```python theme={null} index.delete_user(user_id: str) -> None ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `user_id` | `str` | `user_id` from `create_user()` or `list_users()`. Deleting an ID that doesn't exist succeeds without an error. | ### Example ```python theme={null} index.delete_user(user['user_id']) print(index.list_users()) # Output: [] ``` *** ## Exceptions These apply to all three methods: > [accordion] cyborgdb.AuthenticationError > > The client isn't using the root key (HTTP `403`), or its `api_key` is invalid (HTTP `401`). > [accordion] cyborgdb.ValidationError > > `permissions` is empty or contains a value other than `"read"` or `"write"`, or `user_id` isn't hex (HTTP `400`). > [accordion] cyborgdb.NotFoundError > > The index doesn't exist (HTTP `404`). > [accordion] cyborgdb.ServiceError / cyborgdb.TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors) for the full hierarchy. # Errors Source: https://docs.cyborg.co/versions/latest/service/python-sdk/errors Every failed request to the service raises a subclass of `cyborgdb.CyborgDBError`. The subclass is chosen from the HTTP status code, so callers can catch one class per failure mode. ```python theme={null} import cyborgdb try: index = client.load_index("missing-index", index_key) except cyborgdb.NotFoundError as e: print(e.status_code, e.detail) # Output: 404 No KMS envelope for index 'missing-index' ``` ## Exception classes | Class | Raised for | `retryable` | | - | - | - | | `ValidationError` | HTTP `400` or `422`: the service rejected the request's arguments. | `False` | | `AuthenticationError` | HTTP `401` or `403`: a missing or invalid `api_key`, a non-root key used for a root-only operation, or an `index_key` that doesn't match an index that has vectors and is already in the service's cache. | `False` | | `NotFoundError` | HTTP `404`: the index or resource does not exist. | `False` | | `ConflictError` | HTTP `409`: the request conflicts with the current state on the server. | `False` | | `RateLimitError` | HTTP `429`. The service does not rate-limit requests yet. | `True` | | `ServiceError` | Any HTTP `5xx` response. | `True` | | `TransportError` | No response arrived: DNS failure, refused connection, TLS failure, or timeout. | `True` | All seven classes inherit from `CyborgDBError`, which inherits from `ValueError`. Code written against earlier SDK versions that catches `ValueError` still catches them. > [!NOTE] > > `cyborgdb.ValidationError` shares its name with `pydantic.ValidationError`. Import it as `cyborgdb.ValidationError` to avoid confusion. ## Attributes | Attribute | Type | Description | | - | - | - | | `status_code` | `int` or `None` | HTTP status code. `None` for a `TransportError`. | | `detail` | `str` or `None` | The service's error message, taken from the response body's `detail` field. For a `422` it's the JSON-encoded list of validation errors; for a `TransportError` it's the connection error text. | | `request_id` | `str` or `None` | Value of the `X-Request-Id` response header, when the service sends one. Include it when reporting a problem. | | `retry_after` | `float` or `None` | Seconds from a numeric `Retry-After` header. | | `retryable` | `bool` | Class-level flag from the table above. | The original exception is kept as `__cause__`. ```python theme={null} try: index.query_metadata(filters={"category": {"$regex": "^re"}}) except cyborgdb.ValidationError as e: print(e.status_code) print(e.detail) # Output: # 400 # Failed to query metadata: Invalid input: $regex on 'category' requires a regex-indexed (pattern) field ``` ## Logging The SDK also logs every failed request at `ERROR` level through Python's `logging` module, including the response headers and body, even when the caller catches the exception. All SDK loggers sit under the `cyborgdb` logger, so they can be quieted together: ```python theme={null} import logging logging.getLogger("cyborgdb").setLevel(logging.CRITICAL) ``` ## Retries The SDK sets no request timeout and retries a request only once, when its connection fails or drops (see [Client](./client/client#errors)). `retryable` marks the errors that are safe to retry; any further retry loop is up to the caller: ```python theme={null} import time for attempt in range(3): try: results = index.query(query_vectors=[0.1, 0.2, 0.3, 0.4], top_k=5) break except cyborgdb.CyborgDBError as e: if not e.retryable or attempt == 2: raise time.sleep(e.retry_after or 2 ** attempt) ``` ## Errors raised before a request is sent Argument checks that run in the SDK, before anything is sent to the service, raise `cyborgdb.ValidationError` with `status_code` `None`. They cover: * an `index_key` that isn't 32 bytes, or neither `index_key` nor `kms_name` passed to `create_index()` * an invalid `storage_precision` * a NumPy array with the wrong number of dimensions * mismatched `ids`, `vectors`, `metadata`, or `contents` lengths in `upsert_binary()` * an upsert item without an `id` * an `order_by` dict with more than one key An argument of the wrong type, such as a list where `upsert_binary()` or `query_binary()` expects a NumPy array, raises a `ValidationError` that is also a `TypeError`, so existing `except TypeError` blocks keep working. > [!NOTE] > > A few wrong-type arguments are caught by the generated request models instead, and raise `pydantic.ValidationError`: for example `get(5)`, `delete([1, 2])`, `query(top_k="abc")`, `query_metadata(order_by=5)`, or `query()` with neither `query_vectors` nor `query_contents`. It is still a `ValueError`. ## Other statuses HTTP statuses outside the mapping above (for example `405` or `413`) raise the base `CyborgDBError`, with `status_code` set. # Getters Source: https://docs.cyborg.co/versions/latest/service/python-sdk/getters `EncryptedIndex` exposes index settings as properties, plus two training-status methods. Every getter except `index_name` calls the service's describe or training-status endpoint. On HTTP errors, getters raise the same [`CyborgDBError`](./errors) subclasses as the other methods, for example `NotFoundError` if the index was deleted. ## index_name ```python theme={null} @property index_name: str ``` The index's name. Read locally, with no network call. ```python theme={null} print(index.index_name) # Output: my-vectors ``` *** ## dimension ```python theme={null} @property dimension: int ``` Vector dimensionality. Returns `0` if the index was created without a `dimension` and nothing has been upserted yet. Once non-zero, the value is cached and later reads don't call the service. ```python theme={null} print(index.dimension) # Output: 384 ``` *** ## metric ```python theme={null} @property metric: str ``` Distance metric: `"euclidean"`, `"squared_euclidean"`, or `"cosine"`. Cached after the first read. ```python theme={null} print(index.metric) # Output: euclidean ``` *** ## n_lists ```python theme={null} @property n_lists: int ``` Number of IVF lists. `1` for an untrained index; the trained list count after [`train()`](./encrypted-index/train). Fetched from the service on every read. ```python theme={null} print(index.n_lists) # Output: 1 ``` *** ## metadata_schema ```python theme={null} @property metadata_schema: Dict[str, Dict[str, bool]] ``` The per-field indexing policy set with `metadata_schema` or `text_fields` in [`create_index()`](./client/create-index#metadata-schema). Each entry has `filterable`, `pattern`, and `full_text`. `{}` when the index uses the default policy. Fetched on every read. ```python theme={null} print(index.metadata_schema) # Output: {'body': {'filterable': False, 'pattern': False, 'full_text': True}} ``` *** ## bm25 ```python theme={null} @property bm25: Optional[Dict[str, Any]] ``` The index's BM25 settings, or `None` when it has no full-text fields. | Key | Type | Description | | - | - | - | | `k1` | `float` | Term-frequency saturation. | | `b` | `float` | Length normalization. | | `analyzer_version` | `str` or `None` | Text analyzer the index was built with. | ```python theme={null} print(index.bm25) # Output: {'k1': 1.2, 'b': 0.75, 'analyzer_version': 'en/1;sw=2de831ef7be676b6;snowball-english-utf8-3.0.1'} ``` *** ## is_trained ```python theme={null} index.is_trained() -> bool ``` `True` if the index has been trained. Raises a [`CyborgDBError`](./errors) subclass if the describe request fails, for example `NotFoundError` if the index was deleted. ```python theme={null} if not index.is_trained(): index.train() ``` *** ## is_training ```python theme={null} index.is_training() -> bool ``` `True` while the service is training this index or has it queued for training. Requires the root key: with a per-user key the service returns HTTP `403` and the SDK raises `cyborgdb.AuthenticationError`. ```python theme={null} import time while index.is_training(): time.sleep(5) print(index.is_trained()) ``` # CyborgDB - Python SDK Reference Source: https://docs.cyborg.co/versions/latest/service/python-sdk/introduction `v0.18.x` The **CyborgDB** Python SDK is a client for the CyborgDB service. It creates encrypted indexes, upserts and retrieves vectors, runs vector, hybrid (BM25 + vector), and metadata-only queries, and manages per-index users. It includes a LangChain vector store, `cyborgdb.CyborgVectorStore`. The package is available on [PyPI](https://pypi.org/project/cyborgdb/) and the source code is available on [GitHub](https://github.com/cyborginc/cyborgdb-py). ## Installation ```bash theme={null} pip install cyborgdb ``` ## Prerequisites Before using the CyborgDB Python SDK, you need to have the CyborgDB service running: ```bash theme={null} # Install the CyborgDB service pip install cyborgdb-service # Or pull the Docker image docker pull cyborginc/cyborgdb-service # Start the service cyborgdb-service # Or run the Docker container docker run -p 8000:8000 cyborginc/cyborgdb-service ``` For detailed service setup instructions, see our quickstart guides for [Docker](../guides/intro/quickstart-docker) and [Python](../guides/intro/quickstart-python). # Load Sample Dataset Source: https://docs.cyborg.co/versions/latest/service/python-sdk/load-sample-dataset Loads a hosted sample dataset, ready to upsert and query — useful for quickstarts, demos, and tests without generating your own vectors. The dataset is fetched from a public S3 bucket on first use and cached locally for subsequent calls. ```python theme={null} def load_sample_dataset(name: str = "quickstart-75k", cache_dir: str = None, force_download: bool = False) -> SampleDataset ``` `load_sample_dataset` is a module-level function: ```python theme={null} import cyborgdb dataset = cyborgdb.load_sample_dataset() ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `name` | `str` | `"quickstart-75k"` | *(Optional)* Name of the dataset to load. `"quickstart-75k"` is currently the only available dataset. | | `cache_dir` | `str` | `None` | *(Optional)* Directory to cache the decompressed dataset in. Defaults to `$XDG_CACHE_HOME/cyborgdb` or `~/.cache/cyborgdb`. | | `force_download` | `bool` | `False` | *(Optional)* Re-download even if a cached copy exists. | > [!NOTE] > > Each dataset's SHA-256 digest is pinned in the SDK and verified both after download and on every cache read, so a tampered download or cache file is rejected and re-fetched rather than trusted. ### Returns `SampleDataset`: A dataclass combining dataset metadata, upsert-ready convenience fields, the raw parallel arrays, and ground-truth fixture data: | Field | Type | Description | | - | - | - | | `name` | `str` | Dataset identifier, e.g. `"quickstart-75k"` | | `version` | `int` | Dataset schema version | | `description` | `str` | Human-readable description | | `dimension` | `int` | Vector dimensionality | | `metric` | `str` | Distance metric the vectors were generated for | | `count` | `int` | Number of items in the dataset | | `items` | `List[Dict]` | Items with `id`, `vector`, and `metadata` keys — pass directly to [`upsert()`](./encrypted-index/upsert) | | `sample_queries` | `List[List[float]]` | The first 10 query vectors, for quick similarity-search demos | | `example_filters` | `List[Dict]` | Curated, guaranteed-to-match metadata filters, each with `name`, `filter`, and `demonstrates` keys | | `ids` / `vectors` / `metadata` | parallel lists | Raw arrays, aligned by index | | `queries`, `metadata_queries`, `metadata_query_names`, `untrained_neighbors`, `trained_neighbors`, `untrained_metadata_matches`, `trained_metadata_matches`, `untrained_metadata_neighbors`, `trained_metadata_neighbors`, `untrained_recall`, `trained_recall`, `num_untrained_vectors`, `num_trained_vectors` | ground truth | Fixture data for validating recall / accuracy | ### Exceptions > [accordion] ValueError > > * Throws if the dataset name is unknown. > [accordion] RuntimeError > > * Throws if the download fails. > * Throws if the downloaded dataset fails its integrity (SHA-256) check. ### Example Usage ```python theme={null} import cyborgdb client = cyborgdb.Client('http://localhost:8000', 'your-api-key') index_key = client.generate_key() # Load the sample dataset (downloads on first use, cached afterwards) dataset = cyborgdb.load_sample_dataset() print(dataset.name, dataset.count, dataset.dimension, dataset.metric) # Output: quickstart-75k 75000 128 euclidean index = client.create_index( index_name="demo", index_key=index_key, dimension=dataset.dimension, metric=dataset.metric, ) # Populate the index index.upsert(dataset.items) # Run a similarity search with a bundled query vector results = index.query(query_vectors=dataset.sample_queries[0], top_k=5) # Try a curated metadata filter example = dataset.example_filters[0] print(example["name"], example["filter"]) # Output: Equality filter (string field) {'string': 'string_0'} results = index.query( query_vectors=dataset.sample_queries[0], filters=example["filter"], ) ``` # Types Source: https://docs.cyborg.co/versions/latest/service/python-sdk/types ## Index configuration These keyword arguments to [`client.create_index()`](./client/create-index) configure the index. There is no `index_config` argument and no `IndexIVFFlat` / `IndexIVFPQ` / `IndexIVFSQ` types. | Parameter | Type | Default | Description | | - | - | - | - | | `dimension` | `int` | `None` (auto-detect) | Vector dimensionality. Taken from the first upsert, or from `embedding_model`, when omitted. | | `metric` | `str` | `"euclidean"` | `"euclidean"`, `"squared_euclidean"`, or `"cosine"`. | | `embedding_model` | `str` | `None` | Name of one of the service's built-in embedding models (listed by `GET /v1/embedding-models`), used for automatic embedding generation. | | `storage_precision` | `str` | `"float32"` | `"float32"`, `"float16"`, or TurboQuant `"tq12"`, `"tq8"`, `"tq6"`, `"tq4"`. See [Storage precision](./client/create-index#storage-precision). | | `metadata_schema` | `Dict[str, Dict[str, bool]]` | `None` | Per-field indexing policy. See [Metadata schema](./client/create-index#metadata-schema). | | `text_fields` | `List[str]` | `None` | Fields to index for BM25 full-text search. | | `bm25_k1` | `float` | `1.2` | BM25 term-frequency saturation. | | `bm25_b` | `float` | `0.75` | BM25 length normalization. | ## Key management | Parameter | Type | Notes | | - | - | - | | `index_key` | `bytes` | 32-byte key for the SDK-supplied-key path. Pass it again on every `load_index()`. | | `kms_name` | `str` | Name of a `kms.registry` entry in the service YAML. The service generates and wraps the key; later calls omit `index_key`. | Pass exactly one of the two to `create_index()`; passing both returns `ValidationError`. ## Vector item The dict shape [`upsert()`](./encrypted-index/upsert) accepts: ```python theme={null} vector_item = { "id": "unique_identifier", # Required: str "vector": [0.1, 0.2, 0.3, 0.4], # Optional: List[float] "contents": "text content", # Optional: str or bytes "metadata": { # Optional: Dict[str, Any] "category": "research", "author": "Dr. Smith", "tags": ["ai", "ml"], "published_ms": 1767225600000, # a date, as epoch milliseconds }, } ``` ## Query result [`query()`](./encrypted-index/query) returns a flat list for one query vector, and a list of lists for a batch: ```python theme={null} # One query vector [ {"id": "doc1", "distance": 0.125, "metadata": {"category": "research"}}, {"id": "doc2", "distance": 0.234, "metadata": {"category": "news"}}, ] # Batch: one inner list per query vector [ [{"id": "doc1", "distance": 0.125}, {"id": "doc2", "distance": 0.234}], [{"id": "doc3", "distance": 0.156}, {"id": "doc4", "distance": 0.278}], ] ``` Vector queries return `distance` (lower is closer). Hybrid queries (`text=`) return `score` instead (higher is more relevant). ## MetadataResult The item type [`query_metadata()`](./encrypted-index/query-metadata) returns, importable as `cyborgdb.MetadataResult`: ```python theme={null} { "id": str, # Always present "score": float, # Only when text is set } ``` ## Field selection `include` picks the fields returned besides `id`: | Field | `get()` | `query()` / `query_binary()` | | - | - | - | | `vector` | Yes (default) | Not returned | | `contents` | Yes (default) | Not returned | | `metadata` | Yes (default) | Yes | | `distance` | - | Yes | `get()` defaults to `["vector", "contents", "metadata"]`; `query()` defaults to `[]`, which returns only `id`. ## Metadata filtering `filters` on [`query()`](./encrypted-index/query), [`query_binary()`](./encrypted-index/query-binary), and [`query_metadata()`](./encrypted-index/query-metadata) uses MongoDB-style operators. Nested fields use dot-paths such as `"loc.city"`. ### Operators | Operator | Meaning | Example | | - | - | - | | `$eq` | Equal (also the meaning of a bare value) | `{"category": "research"}` | | `$ne` | Not equal | `{"status": {"$ne": "draft"}}` | | `$gt`, `$gte` | Greater than, or equal | `{"year": {"$gte": 2020}}` | | `$lt`, `$lte` | Less than, or equal | `{"price": {"$lt": 100}}` | | `$in` | Value is in the list | `{"tag": {"$in": ["ai", "ml"]}}` | | `$nin` | Value is not in the list | `{"category": {"$nin": ["spam", "deleted"]}}` | | `$exists` | Field is present (`true`) or absent (`false`) | `{"reviewer": {"$exists": True}}` | | `$regex` | String matches a regular expression | `{"title": {"$regex": "^intro"}}` | | `$contains` | String contains a substring | `{"title": {"$contains": "guide"}}` | | `$and` | All sub-filters match | `{"$and": [{"a": 1}, {"b": 2}]}` | | `$or` | Any sub-filter matches | `{"$or": [{"x": 1}, {"y": 2}]}` | | `$nor` | No sub-filter matches | `{"$nor": [{"status": "draft"}, {"status": "deleted"}]}` | | `$not` | The sub-filter doesn't match. Takes one filter object, at the top level. | `{"$not": {"price": {"$gt": 100}}}` | `$gt`, `$gte`, `$lt`, and `$lte` require a number; any other value returns `ValidationError`. `$not` can't be nested inside a field (`{"price": {"$not": ...}}` returns `ValidationError`); wrap the whole condition instead. `$regex` and `$contains` resolve from the index only on fields created with `pattern: True`: `query()` falls back to a slower post-filter otherwise, and `query_metadata()` rejects the filter. ### Examples ```python theme={null} # Equality simple_filter = {"category": "research"} # Range range_filter = {"published_year": {"$gte": 2020, "$lte": 2024}} # Compound complex_filter = { "$and": [ {"category": "research"}, {"confidence": {"$gte": 0.9}}, {"$or": [{"language": "en"}, {"translated": True}]}, ] } ``` ### Dates CyborgDB has no date type. Store dates in metadata as integer milliseconds since the Unix epoch (UTC), so range operators work on them: ```python theme={null} from datetime import datetime, timezone published = datetime(2026, 1, 15, tzinfo=timezone.utc) published_ms = int(published.timestamp() * 1000) index.upsert([ {"id": "doc1", "vector": [0.1, 0.2, 0.3, 0.4], "metadata": {"published_ms": published_ms}}, ]) # Everything published on or after 2026-01-01 start_ms = int(datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp() * 1000) results = index.query_metadata(filters={"published_ms": {"$gte": start_ms}}) print(results) # Output: [{'id': 'doc1'}] ``` Values come back as integers. Convert one back to a `datetime` with: ```python theme={null} item = index.get(["doc1"], include=["metadata"])[0] published = datetime.fromtimestamp(item["metadata"]["published_ms"] / 1000, tz=timezone.utc) print(published) # Output: 2026-01-15 00:00:00+00:00 ``` A date stored as a string, such as `"2026-01-15"`, only works with equality filters. Range operators need a number, so `{"$gte": "2026-01-01"}` returns `ValidationError`. ## Distance metrics | Metric | Description | | - | - | | `cosine` | Cosine distance. Suited to normalized embeddings. | | `euclidean` | Euclidean (L2) distance. | | `squared_euclidean` | Squared Euclidean distance. Same ranking as `euclidean`, without the square root. | # Create Index Source: https://docs.cyborg.co/versions/latest/service/rest-api/client/create-index POST /v1/indexes/create Create a new encrypted index. > [!NOTE] > > There is a single index type. Configuration parameters (`dimension`, `metric`, `embedding_model`, `storage_precision`) are top-level fields; the `index_config` object and the IVFFlat/IVFPQ/IVFSQ distinction from earlier versions no longer apply. ## Authentication Required - **admin (root) API key** via `X-API-Key` header. Per-user (`cdbk_`) keys are rejected with `403` — a per-user credential operates on data, not index lifecycle: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes", "dimension": 384, "metric": "euclidean", "embedding_model": "all-MiniLM-L6-v2", "storage_precision": "float32", "metadata_schema": { "title": {"filterable": true, "pattern": true}, "internal_blob": {"filterable": false} } } ``` **parameters** **index_name** `string` *required* Unique name for the index. **index_key** `string` 32-byte encryption key as a hex string. Required when `kms_name` is omitted (SDK-supplied KEK path). Must be omitted when `kms_name` is set — supplying both is always rejected with 400. **kms_name** `string` Name of a `kms.registry` entry in the service YAML configuration. When supplied, the service generates a fresh KEK, wraps it under the named provider (e.g. `aws-kms`), and persists the envelope. The SDK never sees the plaintext key. Mutually exclusive with `index_key`. **dimension** `integer` Vector dimensionality. If omitted, the server auto-detects from the first upsert. **metric** `string` Distance metric. Options: `euclidean`, `squared_euclidean`, `cosine`. Defaults to the server's default (`euclidean`). **embedding_model** `string` Optional embedding model name for automatic embedding generation on upsert/query. Must be one of the built-in models returned by [List Embedding Models](./list-embedding-models). When set, `dimension` is inferred from the model and may be omitted. **storage_precision** `string` On-disk rerank-vector dtype. Accepts `"float32"` (default), `"float16"`, or the TurboQuant tiers `"tq12"`, `"tq8"`, `"tq6"`, `"tq4"`. Lower precisions reduce storage at the cost of small recall — `"float16"` halves it; the `tq*` tiers compress further (12, 8, 6, or 4 bits per component). **metadata_schema** `object` Per-field metadata indexing policy, keyed by field name (dot-paths for nested fields). Fixed at create time and immutable. Fields omitted here inherit the default (indexed and filterable). See [Metadata Schema](#metadata-schema) below. **MetadataFieldPolicy** **filterable** `boolean` (default: true) Index the field so filters on it resolve from the index. When `false`, the field is still stored and still filterable via post-filter on `/v1/vectors/query`, but cannot be filtered on `/v1/vectors/query_metadata`. **pattern** `boolean` (default: false) Additionally build the field's regex dictionary, needed for index-resolved `$regex` / `$contains`. Requires `filterable=true`. **full_text** `boolean` (default: false) Route the field's string value through the BM25 analyzer instead of exact-match indexing, making it searchable via `text` on `/v1/vectors/query` and `/v1/vectors/query_metadata`. A field is either analyzed or exact-match indexed, so `full_text: true` implies `filterable: false` and is incompatible with `pattern: true`. **text_fields** `array[string]` Fields to index for BM25 full-text search — shorthand for marking them `full_text: true` in `metadata_schema`. Enables `text` queries on `/v1/vectors/query` and `/v1/vectors/query_metadata`. **bm25_k1** `number` BM25 term-frequency saturation (`>= 0`, default `1.2`). Requires at least one `full_text` field. **bm25\_b** `number` BM25 length-normalization strength (in `[0, 1]`, default `0.75`). Requires at least one `full_text` field. ## Key Management Modes Exactly one of `index_key` / `kms_name` must be supplied: * **SDK-supplied KEK** (set `index_key`, omit `kms_name`) — the service records the index with `provider: none`. The same key must be re-supplied on every subsequent request (load, query, upsert, etc.). * **KMS-backed** (set `kms_name`, omit `index_key`) — the service generates the KEK, wraps it under the named registry slot, and persists the envelope. Subsequent requests omit `index_key` entirely; the service resolves it from the index's stored key envelope. Supplying both is rejected with 400, regardless of the registry slot's provider type. (The `none` provider is not addressable by name — omit `kms_name` to use the SDK-supplied path.) ## Metadata Schema `metadata_schema` sets the per-field indexing policy. Metadata itself stays schemaless — this controls how each field is indexed, not what may be stored. Three knobs per field: * `filterable` (default `true`) — index the field so filters on it resolve from the index (pre-filter, and the only path `/v1/vectors/query_metadata` uses). `false` still stores the field but forces the dense post-filter path when `/v1/vectors/query` filters reference it — cheaper writes, slower filtered queries. * `pattern` (default `false`) — additionally build the field's regex dictionary, needed for index-resolved `$regex` / `$contains`. Requires `filterable: true`. * `full_text` (default `false`) — route the field through the BM25 analyzer for full-text search instead of exact-match indexing. Implies `filterable: false` and is incompatible with `pattern: true`. On `/v1/vectors/query` the schema is a performance hint: filters that miss the index fall back to a post-filter over the decrypted metadata, same rows either way. On `/v1/vectors/query_metadata` it is enforced — `$regex` / `$contains` on a non-`pattern` field, or any filter on a `filterable: false` field, is rejected with 400. The recorded policy is echoed back on `POST /v1/indexes/describe` under `metadata_schema` (empty object when the index uses the default posture). ## Response ```json theme={null} { "status": "success", "message": "Index 'my_index' created successfully" } ``` ## Exceptions > [accordion] 400 Bad Request > > Index name already exists. Also raised for missing/conflicting key parameters (both `index_key` and `kms_name` supplied, or neither), and for BM25 parameter violations: `bm25_k1` / `bm25_b` supplied for an index with no `full_text` field, `bm25_k1 < 0`, `bm25_b` outside `[0, 1]`, or a `text_fields` entry naming a field the schema sets `full_text=false` > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) > [accordion] 403 Forbidden > > Authenticated with a per-user (`cdbk_`) key — this operation requires the admin (root) API key > [accordion] 422 Unprocessable Entity > > Invalid request parameters — including `metadata_schema` with `pattern=true` but `filterable=false`, `full_text=true` combined with `pattern=true` or an explicit `filterable=true`, an empty field name, or an empty `text_fields` entry > [accordion] 500 Internal Server Error > > Internal server error > [accordion] 502 Bad Gateway > > KMS error (e.g. wrap operation failed) ## Example Usage **Basic (SDK-supplied key):** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "dimension": 384 }' ``` **KMS-backed:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "kms_index", "kms_name": "prod-aws", "dimension": 384 }' ``` **With auto-embedding:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "semantic_index", "index_key": "your_64_character_hex_key_here", "embedding_model": "all-MiniLM-L6-v2" }' ``` **Float16 storage for reduced footprint:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "compact_index", "index_key": "your_64_character_hex_key_here", "dimension": 768, "storage_precision": "float16" }' ``` **With per-field metadata policy:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/create" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "docs_index", "index_key": "your_64_character_hex_key_here", "dimension": 384, "metadata_schema": { "title": {"filterable": true, "pattern": true}, "internal_blob": {"filterable": false} } }' ``` > [!NOTE] > > When `embedding_model` is specified, `dimension` is optional — the server infers it from the model. The index will automatically generate embeddings for text content during upsert operations. # Health Check Source: https://docs.cyborg.co/versions/latest/service/rest-api/client/get-health GET /v1/health Check if the API service is running and accessible. ## Parameters None ## Authentication Not required ## Response ```json theme={null} { "status": "healthy", "api_version": "v1", "version": "0.17.0" } ``` ### Response Fields | Field | Type | Description | | - | - | - | | `status` | `string` | Health status of the service (always `"healthy"` if responding) | | `api_version` | `string` | Current API version | | `version` | `string` | Application version number | ## Example Usage ```bash theme={null} curl http://localhost:8000/v1/health # Or with HTTPS curl https://your-domain.com:8000/v1/health ``` ## Use Cases * **Health monitoring**: Check if the service is operational * **Load balancer checks**: Verify service availability * **Deployment validation**: Confirm successful service startup * **Network connectivity**: Test basic API accessibility # List Embedding Models Source: https://docs.cyborg.co/versions/latest/service/rest-api/client/list-embedding-models GET /v1/embedding-models List the text embedding models accepted by `embedding_model` on index create. This reads the service's model table — nothing is downloaded. ## Parameters None ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Response ```json theme={null} { "models": [ { "name": "sentence-transformers/all-MiniLM-L6-v2", "dimension": 384, "max_seq_length": 256 } ] } ``` | Field | Type | Description | | - | - | - | | `models` | `array[object]` | Supported embedding models | | `models[].name` | `string` | Canonical model name. The bare name (without the organization prefix) is also accepted, in any case | | `models[].dimension` | `integer` | Length of each embedding; indexes created with this model use it as their dimension | | `models[].max_seq_length` | `integer` | Longest input, in tokens, before truncation | ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage ```bash theme={null} curl -X GET "http://localhost:8000/v1/embedding-models" \ -H "X-API-Key: cyborg_your_api_key_here" # Or with HTTPS curl -X GET "https://your-domain.com:8000/v1/embedding-models" \ -H "X-API-Key: cyborg_your_api_key_here" ``` ## Use Cases * **Index creation**: Pick a valid `embedding_model` (and its dimension) before calling create index * **Validation**: Verify a model name is supported before deploying * **Client UIs**: Populate model-selection dropdowns from the live service # List Indexes Source: https://docs.cyborg.co/versions/latest/service/rest-api/client/list-indexes GET /v1/indexes/list Retrieve a list of all available encrypted indexes. ## Parameters None ## Authentication Required - **admin (root) API key** via `X-API-Key` header. Per-user (`cdbk_`) keys are rejected with `403`: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Response ```json theme={null} { "indexes": ["my_index", "another_index", "demo_index"] } ``` | Field | Type | Description | | - | - | - | | `indexes` | `array[string]` | List of available index names | ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) > [accordion] 403 Forbidden > > Authenticated with a per-user (`cdbk_`) key — listing indexes requires the admin (root) API key > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage ```bash theme={null} curl -X GET "http://localhost:8000/v1/indexes/list" \ -H "X-API-Key: cyborg_your_api_key_here" # Or with HTTPS curl -X GET "https://your-domain.com:8000/v1/indexes/list" \ -H "X-API-Key: cyborg_your_api_key_here" ``` ## Use Cases * **Index discovery**: Find all available indexes in your deployment * **Administrative tasks**: List indexes for management operations * **Application initialization**: Verify required indexes exist * **Monitoring**: Track index inventory across environments # Training Status Source: https://docs.cyborg.co/versions/latest/service/rest-api/client/training-status GET /v1/indexes/training-status Get the current training status including indexes being trained and the first-train vector-count floor. ## Authentication Required - **admin (root) API key** via `X-API-Key` header. Per-user (`cdbk_`) keys are rejected with `403`: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request This is a GET request with no request body. Authentication is required via the admin API key header. ## Response ```json theme={null} { "training_indexes": ["my_index", "semantic_index"], "retrain_threshold": 65536, "currently_training": "my_index", "queued_indexes": ["semantic_index"], "worker_running": true, "worker_pid": 0, "global_training": {} } ``` **response fields** **training_indexes** `array[string]` List of index names currently being trained or queued for training **retrain_threshold** `integer` Vector-count floor before the first automatic training: an untrained index is auto-trained once `num_vectors > retrain_threshold`. Reflects the service's `AUTO_TRAIN_MIN_VECTORS` setting (default 65536). **currently_training** `string | null` Name of the index currently being trained, or null if none **queued_indexes** `array[string]` List of indexes queued for training (waiting their turn) **worker_running** `boolean` Whether the training worker thread is active **worker_pid** `integer` *(Deprecated)* Always 0. Kept for SDK backward compatibility **global_training** `object` *(Deprecated)* Always empty object. Kept for SDK backward compatibility ## Training States Training state is inferred from the `currently_training` and `queued_indexes` fields: * If `currently_training` is non-null, that index is actively being trained * Indexes in `queued_indexes` are waiting their turn * An index not in either field has completed or has not been trained ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) > [accordion] 403 Forbidden > > Authenticated with a per-user (`cdbk_`) key — training status requires the admin (root) API key > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage **Get Training Status:** ```bash theme={null} curl -X GET "http://localhost:8000/v1/indexes/training-status" \ -H "X-API-Key: cyborg_your_api_key_here" ``` **Monitor Training Progress:** ```bash theme={null} # Check if any indexes are being trained training_count=$(curl -s -X GET "http://localhost:8000/v1/indexes/training-status" \ -H "X-API-Key: cyborg_your_api_key_here" | \ jq '.training_indexes | length') if [ "$training_count" -gt 0 ]; then echo "$training_count indexes are currently being trained" fi ``` **Wait for Training Completion:** ```bash theme={null} # Poll until specific index training is complete index_name="my_index" while true; do is_training=$(curl -s -X GET "http://localhost:8000/v1/indexes/training-status" \ -H "X-API-Key: cyborg_your_api_key_here" | \ jq --arg idx "$index_name" '.training_indexes | contains([$idx])') if [ "$is_training" = "false" ]; then echo "Training complete for $index_name" break fi echo "Still training $index_name..." sleep 5 done ``` **Check First-Train Floor:** ```bash theme={null} # Get the current first-train vector-count floor threshold=$(curl -s -X GET "http://localhost:8000/v1/indexes/training-status" \ -H "X-API-Key: cyborg_your_api_key_here" | \ jq '.retrain_threshold') echo "Untrained indexes will auto-train once they exceed ${threshold} vectors" ``` > [!NOTE] > > Training is automatically triggered when: > > 1. An untrained index's vector count exceeds the first-train floor (`num_vectors > retrain_threshold`) > 2. A trained index grows enough that its optimal number of inverted lists exceeds the current `n_lists` > 3. Manual training is requested via the `/v1/indexes/train` endpoint > > Set `AUTO_TRAIN_DISABLED=true` on the service to turn off automatic training. See [Train an Encrypted Index](../../guides/advanced/train-index) for details. > [!TIP] > > Use this endpoint to avoid querying an index while it's being trained, as training can temporarily affect query performance. # Delete Vectors Source: https://docs.cyborg.co/versions/latest/service/rest-api/encrypted-index/delete POST /v1/vectors/delete Delete specific items from the index by their IDs. ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes", "ids": ["item_1", "item_2", "item_3"] } ``` **parameters** **index_name** `string` *required* Name of the target index **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). **ids** `array[string]` *required* List of item IDs to delete ## Response ```json theme={null} { "status": "success", "message": "Deleted 3 vectors" } ``` **response fields** **status** `string` Status of the operation (always "success" on successful deletion) **message** `string` Confirmation message with count of deleted vectors (format: "Deleted N vectors") ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Invalid request parameters > [accordion] 500 Internal Server Error > > Internal server error > [!NOTE] > > If some IDs don't exist in the index, they will be silently ignored and the operation will continue with the existing IDs. ## Example Usage **Delete Single Item:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/delete" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "ids": ["item_1"] }' ``` **Delete Multiple Items:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/delete" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "ids": ["item_1", "item_2", "item_3", "item_4", "item_5"] }' ``` **Batch Delete:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/delete" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "cleanup_index", "index_key": "your_64_character_hex_key_here", "ids": [ "old_1", "old_2", "old_3", "old_4", "old_5", "temp_1", "temp_2", "temp_3", "temp_4", "temp_5", "test_1", "test_2", "test_3", "test_4", "test_5" ] }' ``` ## Safe Delete Pattern ```bash theme={null} # First, verify items exist curl -X POST "http://localhost:8000/v1/vectors/get" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "ids": ["item_to_delete"], "include": ["metadata"] }' # Then delete if confirmed curl -X POST "http://localhost:8000/v1/vectors/delete" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "ids": ["item_to_delete"] }' ``` ## Data Removal When vectors are deleted, the following data is permanently removed: * **Vector embeddings**: The stored vector representation * **Item contents**: Any associated text or binary content * **Metadata**: All key-value metadata pairs for the item * **Index references**: Internal index pointers to the deleted items ## Performance Considerations * **Batch operations**: Delete multiple items in single requests for better performance * **Index impact**: Large deletions may affect index efficiency; consider retraining after significant deletions * **Memory**: Deleted items may not immediately free memory until index optimization occurs ## Use Cases * **Data cleanup**: Remove outdated or invalid items * **Content moderation**: Delete inappropriate or flagged content * **User management**: Remove user-associated data upon account deletion * **Testing cleanup**: Clean up test data after development * **Data governance**: Remove data that exceeds retention policies # Delete Index Source: https://docs.cyborg.co/versions/latest/service/rest-api/encrypted-index/delete-index POST /v1/indexes/delete > [!WARNING] > > This action is irreversible. All items, vectors and metadata will be permanently lost. Permanently delete an index and all its data. ## Authentication Required - **admin (root) API key** via `X-API-Key` header. Per-user (`cdbk_`) keys are rejected with `403` — a per-user credential operates on data, not index lifecycle: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes" } ``` **parameters** **index_name** `string` *required* Name of the index to delete **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). ## Response ```json theme={null} { "status": "success", "message": "Index 'my_index' deleted successfully" } ``` ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 403 Forbidden > > Authenticated with a per-user (`cdbk_`) key — this operation requires the admin (root) API key > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Invalid request parameters > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/delete" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' ``` ## Confirmation Example ```bash theme={null} # First, list indexes to confirm the target index exists curl -X GET "http://localhost:8000/v1/indexes/list" \ -H "X-API-Key: cyborg_your_api_key_here" # Then delete the specific index curl -X POST "http://localhost:8000/v1/indexes/delete" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "old_index", "index_key": "your_64_character_hex_key_here" }' # Verify deletion by listing indexes again curl -X GET "http://localhost:8000/v1/indexes/list" \ -H "X-API-Key: cyborg_your_api_key_here" ``` ## Data Removal When an index is deleted, the following data is permanently removed: * **Index structure**: All index files and metadata * **Vector embeddings**: All stored vector data * **Item contents**: All associated content data * **Metadata**: All key-value metadata pairs * **Training data**: Any cached training information ## Use Cases * **Cleanup**: Remove outdated or test indexes * **Resource management**: Free up storage and memory * **Development lifecycle**: Clean up development environments * **Data governance**: Remove indexes containing deprecated data # Get Vectors Source: https://docs.cyborg.co/versions/latest/service/rest-api/encrypted-index/get POST /v1/vectors/get Retrieve specific vectors from the index by their IDs. ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes", "ids": ["item_1", "item_2", "item_3"], "include": ["vector", "contents", "metadata"] } ``` **parameters** **index_name** `string` *required* Name of the target index **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). **ids** `array[string]` *required* List of item IDs to retrieve **include** `array[string]` Fields to include in response: **include options** **vector** `string` Include the stored rerank vector. Returned at the index's configured `storage_precision` (`float32` by default; `float16` or a TurboQuant tier `tq12`/`tq8`/`tq6`/`tq4` if set at create time). **contents** `string` Include text content associated with the vector **metadata** `string` Include item metadata key-value pairs ## Response ```json theme={null} { "results": [ { "id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Hello world!", "metadata": {"category": "greeting", "language": "en"} }, { "id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "contents": "Bonjour monde!", "metadata": {"category": "greeting", "language": "fr"} } ] } ``` If an item ID doesn't exist, it will be omitted from the results. ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Invalid request parameters > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage **Get All Fields:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/get" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "ids": ["item_1", "item_2", "item_3"] }' ``` **Get Only Contents:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/get" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "ids": ["doc_1", "doc_2", "doc_3"], "include": ["contents"] }' ``` **Get Metadata Only:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/get" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "ids": ["user_1", "user_2"], "include": ["metadata"] }' ``` **Batch Retrieval:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/get" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "ids": [ "batch_1", "batch_2", "batch_3", "batch_4", "batch_5", "batch_6", "batch_7", "batch_8", "batch_9", "batch_10" ], "include": ["contents", "metadata"] }' ``` **Example Response (Contents Only):** ```json theme={null} { "results": [ { "id": "doc_1", "contents": "First document content here..." }, { "id": "doc_2", "contents": "Second document content here..." }, { "id": "doc_3", "contents": "Third document content here..." } ] } ``` **Example Response (Metadata Only):** ```json theme={null} { "results": [ { "id": "user_1", "metadata": { "name": "Alice Smith", "role": "admin", "department": "engineering", "created": "2024-01-01" } }, { "id": "user_2", "metadata": { "name": "Bob Johnson", "role": "user", "department": "marketing", "created": "2024-01-02" } } ] } ``` ## Use Cases * **Content retrieval**: Get original text content by ID * **Metadata lookup**: Retrieve item metadata for display * **Data validation**: Verify stored data integrity * **Bulk operations**: Retrieve multiple items efficiently * **Content management**: Extract specific items for editing or processing # List IDs Source: https://docs.cyborg.co/versions/latest/service/rest-api/encrypted-index/list-ids POST /v1/vectors/list_ids List all item IDs currently stored in the encrypted index. ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes" } ``` **parameters** **index_name** `string` *required* Name of the index to list IDs from **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). ## Response ```json theme={null} { "ids": [ "item_1", "item_2", "item_3", "item_4", "item_5" ], "count": 5 } ``` **response fields** **ids** `array[string]` List of all item IDs in the index **count** `integer` Total number of IDs in the index ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Invalid request parameters > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage **Basic List IDs:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/list_ids" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' ``` **With jq processing:** ```bash theme={null} # Get total count count=$(curl -s -X POST "http://localhost:8000/v1/vectors/list_ids" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' | jq '.count') echo "Index contains $count items" # List all IDs curl -s -X POST "http://localhost:8000/v1/vectors/list_ids" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' | jq -r '.ids[]' ``` **Check if specific ID exists:** ```bash theme={null} # Check if item exists id_to_check="item_123" exists=$(curl -s -X POST "http://localhost:8000/v1/vectors/list_ids" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' | jq --arg id "$id_to_check" '.ids | contains([$id])') if [ "$exists" = "true" ]; then echo "Item $id_to_check exists in the index" else echo "Item $id_to_check not found" fi ``` > [!NOTE] > > This endpoint is useful for auditing index contents, verifying data integrity, and implementing custom batch processing workflows. > [!TIP] > > For large indexes with many items, consider implementing pagination on the client side by processing the returned IDs in batches. # Query Vectors Source: https://docs.cyborg.co/versions/latest/service/rest-api/encrypted-index/query POST /v1/vectors/query Retrieve the nearest neighbors for a given query vector. Passing `text` alongside `query_vectors` turns this into a **hybrid** query that fuses BM25 full-text ranking with the vector ranking (see [Full-Text and Hybrid Search](../../guides/data-operations/bm25-search)). Adding `filters` on top composes with either form — including a **three-way** query (vector + BM25 + metadata); see [Combining search legs](#combining-search-legs). ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ### Single Query Request ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes", "query_vectors": [0.1, 0.2, 0.3, 0.4], "top_k": 10, "n_probes": 1, "greedy": false, "filters": {"category": "greeting"}, "include": ["distance", "metadata"] } ``` ### Batch Query Request ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes", "query_vectors": [ [0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8] ], "top_k": 10, "n_probes": 1, "greedy": false, "filters": {"category": "greeting"}, "include": ["distance", "metadata"] } ``` ### Semantic Search Request (with embedding model) ```json theme={null} { "index_name": "semantic_index", "index_key": "64_character_hex_string_representing_32_bytes", "query_contents": "Find documents about machine learning", "top_k": 10, "filters": {"type": "research"}, "include": ["distance", "metadata"] } ``` **parameters** **index_name** `string` *required* Name of the target index **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). **query_vectors** `array[number] | array[array[number]]` Query vector(s) for similarity search: * Single query: `[0.1, 0.2, 0.3, ...]` (1D array) * Batch query: `[[0.1, 0.2, ...], [0.4, 0.5, ...]]` (2D array) Required unless `query_contents` is provided **query_contents** `string` Text content for semantic search (requires index with `embedding_model`). Alternative to `query_vectors` for automatic embedding generation **top\_k** `integer` (default: 100) Number of nearest neighbors to return **n\_probes** `integer` (default: auto) Number of index lists to probe. When set to 0 or omitted, automatically determines optimal value based on index size and query requirements **greedy** `boolean` (default: false) Use greedy search for higher recall **rerank_mult** `integer` (default: 50) Multiplier for stage 1 retrieval in reranking indexes. Stage 1 returns `top_k * rerank_mult` candidates before the rerank pass narrows the result down to `top_k`. Higher values trade query latency for recall. Ignored by indexes that do not rerank. `top_k * rerank_mult` must not exceed 10,000; hybrid (vector + `text`) queries multiply by an additional fusion window, so their budget is tighter. **filters** `object` MongoDB-style metadata filters **include** `array[string]` Fields to include in response. `id` is always returned. `contents` and `vector` are **not** valid values for query — to retrieve stored vectors or contents, call `POST /v1/vectors/get` (or the SDK's `get`) with the matching IDs afterwards. **include options** **distance** `string` Include distance/similarity score to query vector (pure vector query only) **metadata** `string` Include item metadata key-value pairs **text** `string` Query text for a BM25 full-text leg. Setting it makes the query **hybrid**: the BM25 ranking is fused with the vector ranking by weighted RRF and each result carries `score` instead of `distance`. Requires an index with at least one `full_text` field. A `query_vectors` value is still required even with `text` set — it fixes the batch shape. **text_fields** `array[string]` Which `full_text` fields the text leg searches. Omitted means all designated fields. Naming a non-`full_text` field returns 400. **text_field_weights** `array[number]` Per-field weights on the summed per-field BM25 scores, parallel to the searched fields. Omitted means 1.0 each. **require_all_terms** `boolean` (default: false) Require every query term to match (AND) instead of any (OR, the default). **alpha** `number` (default: 0.5) Leg blend in `[0, 1]`: `0` = pure BM25, `1` = pure vector. An exact endpoint skips the dead leg's retrieval. **rrf\_k** `number` (default: 60) RRF rank-smoothing constant (must be `> 0`). Higher rewards agreement further down each leg's list. **window_mult** `integer` (default: 3) Per-leg candidate depth as a **multiple of `top_k`** (must be `>= 1`), so each leg looks deeper than the final cut. > [!NOTE] > > Hybrid queries accept fewer filters than pure vector queries. Filtering on a `full_text` or `filterable: false` field, or using `$regex`/`$contains` on a non-`pattern` field, works in a pure query but is rejected with 400 when `text` is set. To keep such a filter, run the query without `text`. ## Response ### Single Query Response When `query_vectors` is a 1D array or `query_contents` is used: ```json theme={null} { "results": [ { "id": "item_1", "distance": 0.123, "metadata": {"category": "greeting", "language": "en"} }, { "id": "item_3", "distance": 0.245, "metadata": {"category": "greeting", "language": "es"} } ] } ``` ### Batch Query Response When `query_vectors` is a 2D array (array of arrays): ```json theme={null} { "results": [ [ {"id": "item_1", "distance": 0.123, "metadata": {"category": "greeting"}}, {"id": "item_2", "distance": 0.245, "metadata": {"category": "farewell"}} ], [ {"id": "item_3", "distance": 0.156, "metadata": {"category": "question"}}, {"id": "item_4", "distance": 0.298, "metadata": {"category": "answer"}} ] ] } ``` > [!NOTE] > > The response format automatically matches the request format: > > * Single query → flat array of results > * Batch query → nested array with results for each query ### Hybrid Query Response When `text` is set alongside `query_vectors`, each result carries a `score` (fused BM25 + vector relevance, higher = more relevant) instead of `distance` — a text-only match has no vector distance to report: ```json theme={null} { "results": [ {"id": "a1", "score": 0.0161, "metadata": {"title": "Encrypted vector search"}}, {"id": "a7", "score": 0.0134, "metadata": {"title": "Query fusion"}} ] } ``` ## Metadata Filtering Use MongoDB-style query operators: ```json theme={null} { "filters": { "$and": [ {"category": "greeting"}, {"confidence": {"$gte": 0.9}} ] } } ``` **Supported operators:** `$eq`, `$ne`, `$in`, `$nin`, `$exists`, `$gt`, `$gte`, `$lt`, `$lte`, `$regex`, `$contains`, combined with `$and`, `$or`, `$nor`, `$not` Filtering works on any metadata field; the index's `metadata_schema` only decides *how* a filter is resolved — fields marked `filterable` (the default) are answered from the inverted index, and `$regex` / `$contains` are answered from the regex dictionary on `pattern` fields. Anything else falls back to a post-filter over the decrypted metadata, which is correct but slower. Dates have no native type: store and filter them as epoch milliseconds. ## Combining Search Legs Vector similarity, BM25 full-text, and metadata filtering are independent legs that compose in one request: | Legs | Request shape | Endpoint | | - | - | - | | Vector + metadata | `query_vectors` + `filters` | this endpoint | | Vector + BM25 (hybrid) | `query_vectors` + `text` | this endpoint | | Vector + BM25 + metadata (three-way) | `query_vectors` + `text` + `filters` | this endpoint | | BM25 + metadata (no vector) | `text` + `filters` | [`/v1/vectors/query_metadata`](./query-metadata) | | Metadata only | `filters` | [`/v1/vectors/query_metadata`](./query-metadata) | On a three-way query the filter is resolved **once**, before retrieval, and the surviving IDs constrain both the vector and BM25 legs — so both rankings are computed over the same filtered candidate set, then fused by RRF. A filter that matches nothing short-circuits to an empty result without running either leg. `alpha` still applies: `0` reduces the query to BM25 + metadata, `1` to vector + metadata, and either exact endpoint skips the dead leg's retrieval entirely. > [!NOTE] > > Any query with `text` set accepts only filters the metadata index can resolve exactly (see the Note above) — this includes the three-way form. ## Exceptions > [accordion] 400 Bad Request > > Invalid values (e.g. vector dimension mismatch with the index), or a hybrid-parameter violation — a filter disallowed on a hybrid (`text`) query (see the Note above), `text` on an index with no `full_text` field, a `text_fields` entry that is not a `full_text` field, a text knob (`text_fields` / `text_field_weights` / `require_all_terms`) without `text`, `alpha` outside `[0, 1]`, `rrf_k <= 0`, or `window_mult < 1` > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Request body failed validation (missing/mistyped fields) > [accordion] 500 Internal Server Error > > Internal server error > [accordion] 503 Service Unavailable > > Embedding model unavailable (semantic search via `query_contents`) ## Example Usage **Basic Query:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.1, 0.2, 0.3, 0.4], "top_k": 5 }' ``` **With Filters:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.1, 0.2, 0.3, 0.4], "top_k": 10, "filters": { "$and": [ {"category": "document"}, {"priority": {"$gte": 3}} ] }, "include": ["distance", "metadata"] }' ``` **Semantic Search:** ```bash theme={null} # For indexes with embedding_model curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "semantic_index", "index_key": "your_64_character_hex_key_here", "query_contents": "Find documents about machine learning", "top_k": 10, "filters": {"type": "research"} }' ``` **Hybrid Query (BM25 + Vector):** ```bash theme={null} # Requires an index created with at least one full_text field. # Each result carries `score` instead of `distance`. curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "articles", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.1, 0.2, 0.3, 0.4], "text": "encrypted search", "top_k": 10, "alpha": 0.5, "include": ["metadata"] }' ``` **Three-Way Query (Vector + BM25 + Metadata):** ```bash theme={null} # Filters are resolved once and constrain both legs before retrieval. # Every filtered field must be resolvable from the metadata index # (filterable, or pattern for $regex) — see the hybrid filter Note. curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "articles", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.1, 0.2, 0.3, 0.4], "text": "encrypted search", "filters": { "$and": [ {"category": "tech"}, {"published": {"$gte": 1735689600000}} ] }, "top_k": 10, "alpha": 0.5, "include": ["metadata"] }' ``` **Batch Query:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [ [0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.9, 0.1, 0.2, 0.3] ], "top_k": 5, "include": ["distance"] }' ``` **High Recall Query:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "query_vectors": [0.1, 0.2, 0.3, 0.4], "top_k": 20, "n_probes": 10, "rerank_mult": 20, "greedy": true }' ``` > [!NOTE] > > If `embedding_model` is configured for the index, you can use either `query_vectors` for direct vector search or `query_contents` for text-based semantic search. > [!TIP] > > Higher `n_probes`, `rerank_mult`, and `greedy=true` all increase recall but reduce query performance. Start with defaults and adjust based on your recall requirements. # Query Vectors (Binary) Source: https://docs.cyborg.co/versions/latest/service/rest-api/encrypted-index/query-binary POST /v1/vectors/query_binary Search for nearest neighbors in the encrypted index using binary-encoded query vectors for more efficient transfer of large batch queries. ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes", "batch": { "vectors_b64": "BASE64_ENCODED_FLOAT32_ARRAY", "dimension": 384 }, "top_k": 10, "n_probes": 5, "greedy": false, "rerank_mult": 50, "filters": {"category": "research"}, "include": ["distance", "metadata"] } ``` **parameters** **index_name** `string` *required* Name of the target index **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). **batch** `object` *required* Batch of query vectors in binary format: **batch parameters** **vectors_b64** `string` *required* Base64-encoded float32 array. The decoded bytes represent a flat array of `n_queries x dimension` little-endian float32 values **dimension** `integer` *required* Dimensionality of each query vector **top\_k** `integer` Number of nearest neighbors to return per query. Defaults to 100 **n\_probes** `integer` Number of clusters to probe during search. Auto-determined when not specified **greedy** `boolean` Whether to use greedy search algorithm. Defaults to false **rerank_mult** `integer` (default: 50) Multiplier for stage 1 retrieval in reranking indexes. Stage 1 returns `top_k * rerank_mult` candidates before the rerank pass narrows the result down to `top_k`. Higher values trade query latency for recall. Ignored by indexes that do not rerank. `top_k * rerank_mult` must not exceed 10,000. **filters** `object` Metadata filters to apply to the search **include** `array[string]` Fields to include in response: `"distance"`, `"metadata"`. Defaults to `[]` (only `id` is returned). `"contents"` and `"vector"` are **not** valid values — fetch stored vectors or contents via `POST /v1/vectors/get` with the matching IDs afterwards. **text** `string` Query text for a BM25 full-text leg. Setting it makes the query **hybrid**: the BM25 ranking is fused with the vector ranking by weighted RRF and each result carries `score` instead of `distance`. Requires an index with at least one `full_text` field. **text_fields** `array[string]` Which `full_text` fields the text leg searches. Omitted means all designated fields. Naming a non-`full_text` field returns 400. **text_field_weights** `array[number]` Per-field weights on the summed per-field BM25 scores, parallel to the searched fields. Omitted means 1.0 each. **require_all_terms** `boolean` (default: false) Require every query term to match (AND) instead of any (OR, the default). **alpha** `number` (default: 0.5) Leg blend in `[0, 1]`: `0` = pure BM25, `1` = pure vector. An exact endpoint skips the dead leg's retrieval. **rrf\_k** `number` (default: 60) RRF rank-smoothing constant (must be `> 0`). Higher rewards agreement further down each leg's list. **window_mult** `integer` (default: 3) Per-leg candidate depth as a **multiple of `top_k`** (must be `>= 1`), so each leg looks deeper than the final cut. > [!NOTE] > > Hybrid queries accept fewer filters than pure vector queries. Filtering on a `full_text` or `filterable: false` field, or using `$regex`/`$contains` on a non-`pattern` field, works in a pure query but is rejected with 400 when `text` is set. See the [query endpoint](./query) for details. All leg combinations from the standard query endpoint work here too, including the three-way form (`query_vectors` + `text` + `filters`) — see [Combining search legs](./query#combining-search-legs). ## Response The response format is the same as the standard [query endpoint](./query). When `text` is set, each result carries a `score` (fused BM25 + vector relevance, higher = more relevant) instead of `distance`: ```json theme={null} { "results": [ [ {"id": "doc1", "distance": 0.125, "metadata": {"category": "research"}}, {"id": "doc2", "distance": 0.234, "metadata": {"category": "research"}} ], [ {"id": "doc3", "distance": 0.156, "metadata": {"category": "research"}}, {"id": "doc4", "distance": 0.278, "metadata": {"category": "research"}} ] ] } ``` ## Exceptions > [accordion] 400 Bad Request > > Invalid values (e.g. vector dimension mismatch with the index), or a filter disallowed on a hybrid (`text`) query > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Request body failed validation (missing/mistyped fields) > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage ```bash theme={null} # Encode query vectors as base64 float32 array (example using Python) # query_vectors = np.array([[0.1, 0.2, 0.3, 0.4]], dtype=np.float32) # vectors_b64 = base64.b64encode(query_vectors.tobytes()).decode() curl -X POST "http://localhost:8000/v1/vectors/query_binary" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "batch": { "vectors_b64": "zczMPc3MTD6amZk+zczMPg==", "dimension": 4 }, "top_k": 5 }' ``` > [!TIP] > > The binary format is more efficient than the standard JSON query for large batch queries, as it avoids the overhead of encoding each float as a JSON number. The SDK clients automatically use this format when query vectors are passed as typed arrays (e.g., `np.ndarray` in Python, `Float32Array` in JS/TS). # Query by Metadata Source: https://docs.cyborg.co/versions/latest/service/rest-api/encrypted-index/query-metadata POST /v1/vectors/query_metadata Find items by metadata alone — no query vector. With no `text`, the filter is resolved entirely against the encrypted metadata index and the matching items are returned unscored. With `text`, a BM25 full-text search runs over the index's `full_text` fields and the top matches are returned ranked by score; a filter given alongside restricts which items are scored. Works on untrained indexes. To add a vector leg on top of either form, use [`/v1/vectors/query`](./query) — see [Combining search legs](./query#combining-search-legs). ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes", "filters": {"label": "dog"}, "top_k": 10, "order_by": "views", "ascending": false } ``` **parameters** **index_name** `string` *required* Name of the target index **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). **filters** `object` Metadata filters as a JSON object; empty matches everything. Same operators as `/v1/vectors/query` except `$type`. See [Filter constraints](#filter-constraints) below. **top\_k** `integer` Cap on the number of IDs returned; omit for all matches. Applied **after** `order_by`, so it yields the first N of the sorted result. **order_by** `string | object` Metadata field to sort matches by, applied post-filter. Accepts a field name, or a single-field MongoDB-style dict such as `{"views": -1}` (`1` ascending, `-1` descending) which overrides `ascending`. Unordered when omitted. Items missing the field, or holding a non-scalar, sort last. Not supported together with `text`. **ascending** `boolean` (default: true) Sort direction when `order_by` is a field name. Ignored when `order_by` is omitted or is a dict (the dict's sign wins). **text** `string` Query text for a BM25 full-text search. Requires an index with at least one `full_text` field. When set, results are ranked by descending BM25 `score` and `order_by` is not supported. **text_fields** `array[string]` Which `full_text` fields the text search covers. Omitted means all designated fields. Naming a non-`full_text` field returns 400. **text_field_weights** `array[number]` Per-field weights on the summed per-field BM25 scores, parallel to the searched fields. Omitted means 1.0 each. **require_all_terms** `boolean` (default: false) Require every query term to match (AND) instead of any (OR, the default). ## Filter constraints Unlike `/v1/vectors/query`, which falls back to a post-filter over the decrypted metadata when a filter cannot be answered from the index, `/v1/vectors/query_metadata` has no fallback stage — every filter leaf must be resolvable from the encrypted metadata index. That makes the index's [`metadata_schema`](../client/create-index#metadata-schema) enforcement instead of a performance hint: * `$regex` / `$contains` require the field to have been declared `pattern: true` at index create time. * A field declared `filterable: false` cannot be filtered on here at all. * `$type` is not supported on this endpoint. Any of these come back as 400 with the reason; use `/v1/vectors/query` with a vector for filters that need the post-filter path. Nested dot-paths (`loc.city`) are supported. **Supported operators:** `$and`, `$or`, `$nor`, `$not`, `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`, `$exists`, `$regex` (pattern fields only), `$contains` (pattern fields only). ## Response **Filter-only query** — each result row is `{"id"}` (there is nothing to score): ```json theme={null} { "results": [ {"id": "item_1"}, {"id": "item_3"}, {"id": "item_7"} ], "ids": ["item_1", "item_3", "item_7"], "count": 3 } ``` **Text query** — each result row is `{"id", "score"}` in descending BM25 score order: ```json theme={null} { "results": [ {"id": "item_3", "score": 4.21}, {"id": "item_1", "score": 2.87} ], "ids": ["item_3", "item_1"], "count": 2 } ``` **response fields** **results** `array[object]` Matching items. On a `text` query each row is `{id, score}` in descending score order; on a filter-only query each row is `{id}` (no `score` key), following `order_by` when set, otherwise an unordered subset. **ids** `array[string]` Matching item IDs, parallel to `results`. Retained for backward compatibility with callers that only read IDs. **count** `integer` Number of items returned. ## Exceptions > [accordion] 400 Bad Request > > Filter references a field the metadata index cannot resolve — a `$regex`/`$contains` on a non-`pattern` field, a `filterable: false` field, or an unsupported operator. Also raised for text-parameter violations: `text` on an index with no `full_text` field, a `text_fields` entry that is not a `full_text` field, a text knob (`text_fields` / `text_field_weights` / `require_all_terms`) without `text`, or `order_by` combined with `text` > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Invalid request parameters > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage **Filter only (all matches, unordered):** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/query_metadata" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "filters": {"label": "dog"} }' ``` **Combined operators with a result cap:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/query_metadata" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "filters": { "$and": [ {"label": "cat"}, {"confidence": {"$gte": 0.9}} ] }, "top_k": 10 }' ``` **Sorted descending by a metadata field (top_k applies after the sort):** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/query_metadata" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "filters": {"label": "dog"}, "order_by": "views", "ascending": false, "top_k": 5 }' ``` **Full-text search (index must have at least one `full_text` field; results ranked by BM25 score):** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/query_metadata" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "docs_index", "index_key": "your_64_character_hex_key_here", "text": "encrypted search", "filters": {"label": "article"}, "top_k": 10 }' ``` **Regex match (field must have been created with `pattern: true`):** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/query_metadata" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "docs_index", "index_key": "your_64_character_hex_key_here", "filters": {"title": {"$regex": "^intro"}} }' ``` # Train Index Source: https://docs.cyborg.co/versions/latest/service/rest-api/encrypted-index/train POST /v1/indexes/train Train an index for efficient querying. Required before optimal performance. ## Authentication Required - **admin (root) API key** via `X-API-Key` header. Per-user (`cdbk_`) keys are rejected with `403` — a per-user credential operates on data, not index lifecycle: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes", "n_lists": null, "batch_size": 2048, "max_iters": 100, "tolerance": 0.000001, "max_memory": 0 } ``` **parameters** **index_name** `string` *required* Name of the index to train **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). **n\_lists** `integer` (default: null (auto)) Number of inverted lists to create. When `null` or omitted, automatically determines optimal value based on dataset size **batch_size** `integer` (default: 2048) Size of each training batch. **Currently ignored** — see warning below **max_iters** `integer` (default: 100) Maximum training iterations. **Currently ignored** — see warning below **tolerance** `number` (default: 0.000001) Convergence tolerance. **Currently ignored** — see warning below **max_memory** `integer` (default: 0) Maximum memory usage in MB (0 = no limit). **Currently ignored** — see warning below > [!WARNING] > > Only `index_name`, `index_key`, and `n_lists` affect training. The remaining parameters — `batch_size`, `max_iters`, `tolerance`, and `max_memory` — are accepted and validated but **not applied**: the training job silently drops them and runs with built-in defaults. Sending them does not cause an error, but it has no effect. This will be fixed in an upcoming update. ## Response **Training Completed:** ```json theme={null} { "status": "success", "message": "Index 'my_index' trained successfully" } ``` **Training Failed:** ```json theme={null} { "status": "error", "message": "Training failed for 'my_index': internal error during training" } ``` > [!NOTE] > > This endpoint blocks until training completes. It will return `"success"` when training finishes normally, or `"error"` if the training job fails — both as HTTP `200`, never an HTTP error status. The `"error"` message is generic; the underlying cause is written to the service logs, not the response. HTTP error codes below only cover failures *before* the job runs (auth, unknown index, malformed request). > > **Too few vectors is not reported as an error.** When the index holds fewer vectors than the training minimums (see [Training Requirements](#training-requirements)), the job skips training silently and still returns `"status": "success"` — the only trace is a warning in the service logs. Check your vector count before training. ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 403 Forbidden > > Authenticated with a per-user (`cdbk_`) key — this operation requires the admin (root) API key > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Request body failed validation (missing/mistyped fields) > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage **Basic Training:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/train" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' ``` **Explicit `n_lists`:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/train" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "n_lists": 128 }' ``` > [!TIP] > > There must be at least 10,000 vector embeddings in the index prior to training — and at least `2 × n_lists` if you set `n_lists` explicitly. ## Training Requirements * **Minimum vectors**: At least 10,000 vectors must be present in the index, and at least `2 × n_lists` when `n_lists` is set explicitly (the auto-computed `n_lists` always satisfies this). Below either floor the job **skips training silently** and still returns `200` with `"status": "success"` — the skip is only visible as a warning in the service logs * **Memory**: Training may require significant memory depending on dataset size * **Time**: Training duration varies based on dataset size and convergence parameters ## Use Cases * **Performance optimization**: Enable fast approximate nearest neighbor search * **Production preparation**: Train indexes before deploying to production * **Batch processing**: Train indexes after bulk data ingestion * **Index maintenance**: Retrain indexes after significant data updates # Upsert Vectors Source: https://docs.cyborg.co/versions/latest/service/rest-api/encrypted-index/upsert POST /v1/vectors/upsert Add new vectors or update existing ones in the encrypted index. ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes", "items": [ { "id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Hello world!", "metadata": {"category": "greeting", "language": "en"} }, { "id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "contents": "Bonjour monde!", "metadata": {"category": "greeting", "language": "fr"} } ] } ``` **parameters** **index_name** `string` *required* Name of the target index **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). **items** `array[object]` *required* List of items to upsert, each containing: **items parameters** **id** `string` *required* Unique identifier for the item **vector** `array[number]` *required* Vector embedding (required if index does not use automatic embedding generation) **contents** `string` Text content associated with the vector **metadata** `object` Key-value pairs for additional metadata. String values in fields the index designates `full_text` are BM25-indexed on ingest — see [Full-text (BM25) ingestion](#full-text-bm25-ingestion). ## Full-Text (BM25) Ingestion There is no separate ingestion call or parameter for BM25: text is indexed at upsert, from the metadata fields the index designated `full_text` at [creation](../client/create-index). Put the searchable text in those fields and it is analyzed and added to the encrypted BM25 index automatically, making the item retrievable via `text` on [`/v1/vectors/query`](./query) and [`/v1/vectors/query_metadata`](./query-metadata). ```json theme={null} { "id": "article_1", "vector": [0.1, 0.2, 0.3, 0.4], "metadata": { "title": "Encrypted vector search", "body": "CyborgDB keeps embeddings encrypted during search...", "category": "tech" } } ``` Here `title` and `body` are BM25-searchable if the index marked them `full_text`; `category` (a regular `filterable` field) is exact-match indexed as usual. * A `full_text` field's value must be a JSON **string**. Items where the field is missing or non-string are skipped for that field — the upsert still succeeds, and the service logs one warning per field per batch. * `full_text` designations are fixed at index creation; text upserted into non-designated fields is stored as ordinary metadata and is not text-searchable. * `full_text` fields are analyzed instead of exact-match indexed (`filterable: false`), so they cannot be used in `filters` on [`/v1/vectors/query_metadata`](./query-metadata) or on hybrid queries. ## Response **Standard Success Response:** ```json theme={null} { "status": "success", "message": "Upserted 2 vectors" } ``` **With Auto-Training Triggered:** ```json theme={null} { "status": "success", "message": "Upserted 2 vectors", "training_triggered": true, "training_message": "Index training has been triggered (vectors: 5000)" } ``` **With Training Check Warning:** ```json theme={null} { "status": "success", "message": "Upserted 2 vectors", "warning": "Training check failed but upsert succeeded" } ``` > [!NOTE] > > When the number of vectors in an index exceeds the automatic training threshold, the upsert response will include `training_triggered` and `training_message` fields. Training happens asynchronously in the background. > > In rare cases where the training check encounters an error but the upsert operation itself succeeds, a `warning` field will be included instead. The vectors are still successfully upserted in this scenario. ## Exceptions > [accordion] 400 Bad Request > > Invalid values (e.g. vector dimension mismatch with the index) > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Request body failed validation (missing/mistyped fields) > [accordion] 500 Internal Server Error > > Internal server error > [accordion] 503 Service Unavailable > > Embedding model unavailable (auto-embedding upserts on indexes with an `embedding_model`) ## Example Usage **Basic Upsert:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/upsert" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "items": [ { "id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Hello world!" } ] }' ``` **With Metadata:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/upsert" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "items": [ { "id": "doc_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Important document content", "metadata": { "category": "documentation", "author": "admin", "created": "2024-01-15", "priority": "high" } } ] }' ``` **Auto-Generated Embeddings:** ```bash theme={null} # For indexes created with embedding_model curl -X POST "http://localhost:8000/v1/vectors/upsert" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "semantic_index", "index_key": "your_64_character_hex_key_here", "items": [ { "id": "text_1", "contents": "This text will be automatically embedded", "metadata": {"type": "auto_embedded"} } ] }' ``` **Batch Upsert:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/vectors/upsert" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "items": [ {"id": "batch_1", "vector": [0.1, 0.2, 0.3]}, {"id": "batch_2", "vector": [0.4, 0.5, 0.6]}, {"id": "batch_3", "vector": [0.7, 0.8, 0.9]}, {"id": "batch_4", "vector": [0.2, 0.3, 0.4]}, {"id": "batch_5", "vector": [0.5, 0.6, 0.7]} ] }' ``` > [!NOTE] > > When `embedding_model` is configured for the index, the `vector` parameter becomes optional. If provided, it will be used directly; if omitted, a vector will be auto-generated from the `contents` field. > [!TIP] > > For large datasets, use batch upserts with multiple items in a single request to improve performance and reduce network overhead. # Upsert Vectors (Binary) Source: https://docs.cyborg.co/versions/latest/service/rest-api/encrypted-index/upsert-binary POST /v1/vectors/upsert_binary Add new vectors or update existing ones in the encrypted index using a binary-encoded format for more efficient transfer of large batches. ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes", "batch": { "ids": ["item_1", "item_2"], "vectors_b64": "BASE64_ENCODED_FLOAT32_ARRAY", "dimension": 384, "metadata": [ {"category": "greeting", "language": "en"}, {"category": "greeting", "language": "fr"} ], "contents": ["Hello world!", "Bonjour monde!"] } } ``` **parameters** **index_name** `string` *required* Name of the target index **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). **batch** `object` *required* Batch of vectors in binary format: **batch parameters** **ids** `array[string]` *required* List of unique identifiers, one per vector **vectors_b64** `string` *required* Base64-encoded float32 array. The decoded bytes represent a flat array of `n_vectors x dimension` little-endian float32 values **dimension** `integer` *required* Dimensionality of each vector **metadata** `array[object]` Optional list of metadata objects, one per vector. String values in fields the index designates `full_text` are BM25-indexed on ingest, same as the standard endpoint — see [Full-text (BM25) ingestion](./upsert#full-text-bm25-ingestion) **contents** `array[string]` Optional list of text content strings, one per vector ## Response ```json theme={null} { "status": "success", "message": "Upserted 2 vectors" } ``` **With Auto-Training Triggered:** ```json theme={null} { "status": "success", "message": "Upserted 2 vectors", "training_triggered": true, "training_message": "Index training has been triggered (vectors: 5000)" } ``` **With Training Check Warning:** ```json theme={null} { "status": "success", "message": "Upserted 2 vectors", "warning": "Training check failed but upsert succeeded" } ``` > [!NOTE] > > In rare cases where the training check encounters an error but the upsert operation itself succeeds, a `warning` field will be included instead. The vectors are still successfully upserted in this scenario. ## Exceptions > [accordion] 400 Bad Request > > Invalid values (e.g. vector dimension mismatch with the index) > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Request body failed validation (missing/mistyped fields) > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage ```bash theme={null} # Encode vectors as base64 float32 array (example using Python) # vectors = np.array([[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]], dtype=np.float32) # vectors_b64 = base64.b64encode(vectors.tobytes()).decode() curl -X POST "http://localhost:8000/v1/vectors/upsert_binary" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here", "batch": { "ids": ["item_1", "item_2"], "vectors_b64": "zczMPc3MTD6amZk+zczMPgAAAD+amRk/MzMzP83MTD8=", "dimension": 4 } }' ``` > [!TIP] > > The binary format is more efficient than the standard JSON upsert for large batches, as it avoids the overhead of encoding each float as a JSON number. The SDK clients automatically use this format when vectors are passed as typed arrays (e.g., `np.ndarray` in Python, `Float32Array` in JS/TS). # Describe Index Source: https://docs.cyborg.co/versions/latest/service/rest-api/getters/describe-index POST /v1/indexes/describe Get detailed information about an existing index. ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes" } ``` **parameters** **index_name** `string` *required* Name of the index to describe. **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path (`provider: none`). Omit for KMS-backed indexes — the service resolves the key from the index's stored key envelope. ## Response ```json theme={null} { "index_name": "my_index", "is_trained": true, "dimension": 384, "metric": "euclidean", "n_lists": 1024, "metadata_schema": { "title": {"filterable": true, "pattern": true, "full_text": false} }, "bm25": null } ``` **response fields** **index_name** `string` Name of the index. **is_trained** `boolean` Whether the index has been trained for optimized queries. **dimension** `integer` Vector dimensionality. Returns `0` if the index was created without an explicit dimension and the first upsert has not yet happened (auto-detect pending). **metric** `string` Distance metric (`euclidean`, `squared_euclidean`, or `cosine`). **n\_lists** `integer` Number of inverted lists in the IVF index. Returns `1` for untrained indexes; populated with the trained cluster count after `train()`. **metadata_schema** `object` Per-field metadata indexing policy recorded at create time, keyed by field name (each entry has `filterable`, `pattern`, and `full_text` booleans). Empty object when the index uses the default index-everything posture. **bm25** `object | null` BM25 scoring config when the index has at least one `full_text` field; `null` otherwise. Contains `k1` and `b` (the tuning parameters supplied at create time, or their defaults) and `analyzer_version`, which identifies the tokenizer/stemmer pipeline the corpus was indexed with. > [!NOTE] > > The response has no `index_type` or nested `index_config` field. There is a single index type, and its parameters are returned as top-level fields. ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Invalid request parameters > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/describe" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' ``` **KMS-backed index (no key required):** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/describe" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "kms_index" }' ``` # Get Vector Count Source: https://docs.cyborg.co/versions/latest/service/rest-api/getters/get-vector-count POST /v1/vectors/num_vectors Get the number of vectors stored in an encrypted index. ## Authentication Required - API key via `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_api_key_here ``` Any valid credential is accepted — the root key or a per-user `cdbk_` token. When RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), no header is required. ## Request Body ```json theme={null} { "index_name": "my_index", "index_key": "64_character_hex_string_representing_32_bytes" } ``` **parameters** **index_name** `string` *required* Name of the index to count vectors for **index_key** `string` 32-byte encryption key as a hex string. Required for indexes created with the SDK-supplied KEK path; omit for KMS-backed indexes (the service resolves the key from the index's stored key envelope). ## Response ```json theme={null} { "result": 1500 } ``` **response fields** **result** `integer` Total number of vectors stored in the index ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid API key) **or** wrong `index_key` on SDK-supplied indexes — see [error model](../introduction#error-model-api-keys-index-keys-and-kms) > [accordion] 404 Not Found > > Index not found > [accordion] 422 Unprocessable Entity > > Invalid request parameters > [accordion] 500 Internal Server Error > > Internal server error ## Example Usage ```bash theme={null} # Get vector count count=$(curl -s -X POST "http://localhost:8000/v1/vectors/num_vectors" \ -H "X-API-Key: cyborg_your_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "index_name": "my_index", "index_key": "your_64_character_hex_key_here" }' | jq -r '.result') echo "Index contains $count vectors" ``` # CyborgDB REST API Reference Source: https://docs.cyborg.co/versions/latest/service/rest-api/introduction The CyborgDB REST API provides HTTP/HTTPS endpoints for all encrypted vector database operations using standard RESTful principles and JSON responses. ## Base URL **Development:** `http://localhost:8000/v1`\ **Production:** `https://your-domain.com:8000/v1` ## Authentication Authentication is controlled by the service's `CYBORGDB_SERVICE_ROOT_KEY`. When it is **unset** (the default), authentication is disabled — every endpoint is open and no header is required. When it is **set**, all endpoints except `/v1/health` require a credential in the `X-API-Key` header: ```http theme={null} X-API-Key: your-root-key-or-cdbk-token ``` The accepted credential is either the root key itself or a per-user `cdbk_` token minted under it (see [Managing Keys](../guides/advanced/managing-keys)). > [!NOTE] > > This `X-API-Key` credential is **not** the same as `CYBORGDB_API_KEY`. `CYBORGDB_API_KEY` is the core *license* key — it sets the usage tier (unset → free tier with a 1M-item-per-index cap; a paid key from the [CyborgDB Admin Dashboard](https://cyborgdb.co/new) → unlimited) and is never sent by clients. Service request authentication is gated only by `CYBORGDB_SERVICE_ROOT_KEY`. ## Response Format **Success:** ```json theme={null} { "status": "success", "message": "Operation completed successfully" } ``` **Error:** ```json theme={null} { "status_code": 400, "detail": "Error description" } ``` ## Error model: API keys, index keys, and KMS A small amount of nuance applies to error codes on index-scoped routes — the data-plane routes under `/v1/vectors/…` (`upsert`, `upsert_binary`, `query`, `query_binary`, `query_metadata`, `get`, `delete`, `list_ids`, `num_vectors`) and the index-lifecycle routes under `/v1/indexes/…` (`create`, `train`, `delete`, `training-status`, …): | Status | Meaning | | - | - | | `400 Bad Request` | The request is malformed for this index's key path. The most common case is supplying `index_key` (header or body) for a **KMS-backed** index — the service resolves the key itself using its KMS configuration, so the error `detail` says the index is KMS-backed and asks you to omit `index_key` from the request. | | `401 Unauthorized` | Either (a) the `X-API-Key` header is missing/invalid, **or** (b) for SDK-supplied indexes, the `index_key` was supplied but does not match the key the index was created with (*"Wrong encryption key for index '\'"*). Inspect the `detail` field to disambiguate. | | `403 Forbidden` | An admin-gated route (`/v1/indexes/list`, `create`, `delete`, `train`, `training-status`) called with a non-root (`cdbk_`) API key, or an RBAC route (user create/list/delete) called without the root API key or when RBAC is not enabled on the service. | | `404 Not Found` | The named index does not exist. | > [!NOTE] > > A wrong `index_key` returns **401**. KMS-backed indexes that receive an unexpected `index_key` return **400** rather than silently ignoring it — this surfaces SDK-versus-KMS confusion early. ## Interactive Documentation Explore the complete API at: [http://localhost:8000/v1/docs](http://localhost:8000/v1/docs) after starting the service. ReDoc is served at `/v1/redoc` and the OpenAPI spec at `/v1/openapi.json`. # Create User Source: https://docs.cyborg.co/versions/latest/service/rest-api/users/create-user POST /v1/indexes/{index_name}/users Mint a per-user API key scoped to a single index. Requires RBAC enabled on the service (`CYBORGDB_SERVICE_ROOT_KEY` set) and the request must be authenticated with the root key. > [!NOTE] > > See [Multi-Tenancy & RBAC](../../guides/advanced/multi-tenancy) for the full operator playbook. ## Authentication Required — root API key in the `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_root_api_key_here ``` The core license key (`CYBORGDB_API_KEY`) is **not** a service credential; sending it as `X-API-Key` returns 401 ("Invalid API Key"). A 403 is returned only for a valid non-root credential (a `cdbk_` user token). ## Path Parameters | Parameter | Type | Description | | - | - | - | | `index_name` | `string` | Name of the index the user will be scoped to. | ## Request Body ```json theme={null} { "permissions": ["read", "write"], "index_key": "64_character_hex_string_representing_32_bytes" } ``` > [!NOTE] > > For `POST`, the index key rides in the JSON body as `index_key` (alongside `permissions`). The sibling `GET /v1/indexes/{index_name}/users` and `DELETE /v1/indexes/{index_name}/users/{user_id}` endpoints have no request body, so they take the same key via the `X-Index-Key` header instead. **parameters** **permissions** `array[string]` *required* Non-empty subset of `["read", "write"]`. The grant is enforced cryptographically by the service — the wrapped data-encryption keys that exist for a user *are* their permission set. **index_key** `string` 32-byte index KEK as a hex string. Required for SDK-supplied indexes (`provider: none`) so the service can unwrap the root DEK and re-wrap it under the new user. Omit for KMS-backed indexes — the service resolves the key from the index's stored key envelope. Note: the index KEK is needed only at mint time. The minted user then authenticates with their `cdbk_` token alone — the service opens the index via the user's own wrapped DEK, on KMS-backed and SDK-supplied indexes alike. One caveat for SDK-supplied indexes: auto-training after a user's upsert is skipped (the service holds no index KEK to train with) — see [SDK-supplied indexes](../../guides/advanced/multi-tenancy#sdk-supplied-indexes). ## Response ```json theme={null} { "user_id": "a1b2c3d4e5f6...", "api_key": "cdbk_..." } ``` **response fields** **user_id** `string` Hex-encoded identifier for the new user. **api_key** `string` The user's API key. Begins with `cdbk_`. **Returned exactly once and never stored** — capture it now, it cannot be recovered. > [!WARNING] > > The returned `api_key` is shown only in this response and is never persisted by the service. If you lose it, revoke the user (`DELETE`) and mint a new one. ## Exceptions > [accordion] 400 Bad Request > > `permissions` is missing, empty, or contains values outside `{"read", "write"}`. > [accordion] 401 Unauthorized > > Authentication failed (invalid root API key). > [accordion] 403 Forbidden > > RBAC is not enabled (`CYBORGDB_SERVICE_ROOT_KEY` unset), or the caller is not using the root key. > [accordion] 404 Not Found > > Index not found. > [accordion] 500 Internal Server Error > > Internal server error. ## Example Usage ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/documents/users" \ -H "X-API-Key: cyborg_your_root_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "permissions": ["read", "write"] }' ``` **Read-only user:** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/documents/users" \ -H "X-API-Key: cyborg_your_root_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "permissions": ["read"] }' ``` **SDK-supplied index (KEK in body):** ```bash theme={null} curl -X POST "http://localhost:8000/v1/indexes/documents/users" \ -H "X-API-Key: cyborg_your_root_api_key_here" \ -H "Content-Type: application/json" \ -d '{ "permissions": ["read", "write"], "index_key": "your_64_character_hex_key_here" }' ``` # Delete User Source: https://docs.cyborg.co/versions/latest/service/rest-api/users/delete-user DELETE /v1/indexes/{index_name}/users/{user_id} Revoke a user. Erases their wrapped DEK(s) for this index — even a captured `cdbk_…` token becomes useless on the next request. Cryptographic revocation, no propagation lag. > [!NOTE] > > See [Multi-Tenancy & RBAC](../../guides/advanced/multi-tenancy) for the full operator playbook. ## Authentication Required — root API key in the `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_root_api_key_here ``` ## Path Parameters | Parameter | Type | Description | | - | - | - | | `index_name` | `string` | Name of the index the user is scoped to. | | `user_id` | `string` | Hex-encoded `user_id` returned by `POST /v1/indexes/{index_name}/users` (also surfaced by `GET …/users`). | ## Headers | Header | Type | Description | | - | - | - | | `X-Index-Key` | `string` | *(Optional)* 32-byte index KEK as a hex string. Required for SDK-supplied indexes (`provider: none`). Omit for KMS-backed indexes — the service resolves the key from the index's stored key envelope. | > [!NOTE] > > `GET`/`DELETE` on this resource have no request body, so the index key travels in the `X-Index-Key` header. The sibling `POST /v1/indexes/{index_name}/users` endpoint takes the same key as an `index_key` field in its JSON body. ## Response `204 No Content` on success — body is empty. Revocation is idempotent: an unknown or already-revoked `user_id` also returns `204`, not an error. ## Exceptions > [accordion] 400 Bad Request > > `user_id` is not valid hex. > [accordion] 401 Unauthorized > > Authentication failed (invalid root API key). > [accordion] 403 Forbidden > > RBAC is not enabled, or the caller is not using the root key. > [accordion] 404 Not Found > > Index not found. > [accordion] 500 Internal Server Error > > Internal server error. ## Example Usage ```bash theme={null} curl -X DELETE "http://localhost:8000/v1/indexes/documents/users/a1b2c3d4e5f6" \ -H "X-API-Key: cyborg_your_root_api_key_here" ``` **Verify revocation:** ```bash theme={null} # Any subsequent request using the revoked cdbk_... key will fail with 401 curl -X POST "http://localhost:8000/v1/vectors/query" \ -H "X-API-Key: cdbk_revoked_key" \ -H "Content-Type: application/json" \ -d '{ "index_name": "documents", "query_vectors": [0.1, 0.2, 0.3] }' ``` # List Users Source: https://docs.cyborg.co/versions/latest/service/rest-api/users/list-users GET /v1/indexes/{index_name}/users List the users provisioned for a specific index. Requires RBAC enabled and the root API key. > [!NOTE] > > See [Multi-Tenancy & RBAC](../../guides/advanced/multi-tenancy) for the full operator playbook. ## Authentication Required — root API key in the `X-API-Key` header: ```http theme={null} X-API-Key: cyborg_your_root_api_key_here ``` ## Path Parameters | Parameter | Type | Description | | - | - | - | | `index_name` | `string` | Name of the index to list users for. | ## Headers | Header | Type | Description | | - | - | - | | `X-Index-Key` | `string` | *(Optional)* 32-byte index KEK as a hex string. Required for SDK-supplied indexes (`provider: none`). Omit for KMS-backed indexes — the service resolves the key from the index's stored key envelope. | > [!NOTE] > > `GET`/`DELETE` on this resource have no request body, so the index key travels in the `X-Index-Key` header. The sibling `POST /v1/indexes/{index_name}/users` endpoint takes the same key as an `index_key` field in its JSON body. ## Response ```json theme={null} { "users": [ { "user_id": "a1b2c3d4...", "permissions": ["read", "write"] }, { "user_id": "e5f6a7b8...", "permissions": ["read"] } ] } ``` **response fields** **users** `array[object]` Array of users scoped to this index. **user fields** **user_id** `string` Hex-encoded identifier for the user. **permissions** `array[string]` Subset of `["read", "write"]`. Derived from which wrapped DEKs exist for the user (the cryptographic source of truth), not a stored field. ## Exceptions > [accordion] 401 Unauthorized > > Authentication failed (invalid root API key). > [accordion] 403 Forbidden > > RBAC is not enabled, or the caller is not using the root key. > [accordion] 404 Not Found > > Index not found. > [accordion] 500 Internal Server Error > > Internal server error. ## Example Usage ```bash theme={null} curl -X GET "http://localhost:8000/v1/indexes/documents/users" \ -H "X-API-Key: cyborg_your_root_api_key_here" ``` **SDK-supplied index (KEK via header):** ```bash theme={null} curl -X GET "http://localhost:8000/v1/indexes/documents/users" \ -H "X-API-Key: cyborg_your_root_api_key_here" \ -H "X-Index-Key: your_64_character_hex_key_here" ``` # CyborgDB Release Notes Source: https://docs.cyborg.co/changelog CyborgDB follows a bi-monthly release cadence, with new features, enhancements, and bug fixes released every even month (Feb, Apr, etc). This changelog provides a summary of the changes in each release. **v0.18.0** 2026-10-01 ## CyborgDB v0.18.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * **BM25 full-text and hybrid search** * Mark metadata fields as `full_text` in `metadata_schema` to make them keyword-searchable; tune scoring per index with `bm25_k1` / `bm25_b` * `query(text=...)` runs a keyword search, optionally limited to specific `text_fields`; combine it with a query vector for hybrid search, blended with `alpha`, `rrf_k`, and `window_mult` * Available in the embedded libraries, the REST API, and the Python, JavaScript/TypeScript, and Go SDKs * **Metadata schema.** `create_index` accepts a `metadata_schema` that sets, per field, whether it is `filterable`, indexed for fast `$regex` / `$contains` matching (`pattern`), or `full_text` * **`query_metadata`** returns the items matching a metadata filter without a query vector, in the embedded libraries, all client SDKs, and the REST API (`POST /v1/vectors/query_metadata`) * **TurboQuant storage precision.** `storage_precision` adds the `tq12`, `tq8`, `tq6`, and `tq4` tiers for much smaller stored vectors at a small recall cost (`tq4` is the most compact) * `GET /v1/embedding-models` lists the built-in embedding models the service supports * `load_sample_dataset` (`loadSampleDataset` / `LoadSampleDataset`) in the client SDKs loads a sample dataset for quick evaluation * `StorageConfig.disk(...)` adds a `cache_metadata_index` option ### Improvements * Built-in embedding models no longer require PyTorch; installing the `[embeddings]` extra is no longer needed * `$regex` filters are now evaluated with RE2, giving linear-time matching and protection against pathological patterns * `$contains` filter operator for substring matching * The client SDKs now raise standardized error types (for example `AuthenticationError`, `NotFoundError`, `ValidationError`) * Telemetry is not sent when no API key is set * Index dimension is now validated at `create_index` ### Breaking Changes * **Memory backend removed.** `StorageConfig.memory()` and `CYBORGDB_DB_TYPE=memory` are gone; use `disk` (or `s3`) instead * **One process per storage target.** A disk path or S3 bucket/prefix must be used by a single CyborgDB process at a time. Running multiple embedded processes or service replicas against the same storage target is not supported * `GET /v1/indexes/list` and `GET /v1/indexes/training-status` now require the root (admin) key ### Bug Fixes * JavaScript/TypeScript SDK: fixed decoding of `contents` returned by `get()`, and `verifySsl: false` is now honored **v0.17.0** 2026-06-25 ## CyborgDB v0.17.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * **Access control (RBAC)** on encrypted indexes, in both the embedded libraries and the service * The holder of the root index KEK can mint per-user keys scoped to `read` and/or `write` — the keys a user holds determine their permissions, enforced cryptographically on every request * Embedded: `create_user_keys` (Python) / `CreateUserKeys` (C++), plus `index_key=` / `user_id=` per-operation overrides for stateless deployments * Service: `POST`/`GET`/`DELETE` on `/v1/indexes/{name}/users`, surfaced as `users` in the Python, JavaScript/TypeScript, and Go SDKs * **Per-index KMS & BYOK.** Each index can be wrapped by its own operator-managed key, optionally living in a customer's own AWS account * Providers: `aws-kms` (AWS KMS `Encrypt`/`Decrypt`), `aws` (Secrets Manager), and `none` * Pass `kms_name` to `create_index` instead of `index_key`; the service resolves the key server-side from the index's stored key envelope, so the SDK never holds a long-term key * Cross-account BYOK via `role_arn` + `external_id`; KMS credentials are kept separate from `CYBORGDB_S3_*` storage credentials * **Free tier.** `CYBORGDB_API_KEY` is now optional — without it, CyborgDB runs free-tier with a 1,000,000-item-per-index cap. Demo keys are available via `get_demo_api_key()` / `getDemoApiKey()` / `GetDemoAPIKey()` * **YAML configuration.** The service can be configured entirely by `cyborgdb.yaml` (resolved from `CYBORGDB_CONFIG_FILE`, the working directory, or `/etc/cyborgdb/`), with `${VAR}` / `${VAR:-default}` env-var substitution. Environment variables override the file * `storage_precision` lets you store rerank vectors as `float16` instead of `float32`, halving the on-disk footprint at a small recall cost * `rerank_mult` on `query` tunes stage 1 retrieval depth (`top_k * rerank_mult` candidates before reranking), and `include=["vector"]` returns the stored rerank vector ### Improvements * `n_lists` is now selected automatically by the core engine ### Breaking Changes * **Single index type.** CyborgDB now ships a single IVF index type. The polymorphic `index_config` object is gone, along with the IVFFlat / IVFPQ / IVFSQ distinction * Configuration parameters (`dimension`, `metric`, `embedding_model`, `storage_precision`) are now top-level fields on `create_index` * `dimension` is optional — the server auto-detects it from the first upsert, or infers it from `embedding_model` * In the embedded SDKs, all parameters after `index_key` are keyword-only * **Storage refactor.** The backing store surface is now just `memory`, `disk`, or `s3` * The `standalone`, `postgres`, and `redis` backends have been removed * `CYBORGDB_CONNECTION_STRING` is replaced by `CYBORGDB_DISK_PATH` and the `CYBORGDB_S3_*` variables — switch `standalone` → `disk` when upgrading * In the embedded SDKs, a single `StorageConfig` (`StorageConfig.memory()` / `.disk(path)` / `.s3(bucket)`) replaces the `index_location` / `config_location` / `items_location` trio of `DBConfig` objects * **Authentication overhaul.** `CYBORGDB_API_KEY` is now a *license* key only and no longer gates access to the REST API * Request authentication is controlled by `CYBORGDB_SERVICE_ROOT_KEY`. Leave it unset and authentication is disabled; set it and routes accept only the root key or a per-user `cdbk_…` token in the `X-API-Key` header * The legacy `cyborgdb-api-key` header and the `REQUIRE_API_KEY` flag have been removed * A wrong `index_key` now returns `401` instead of `500` **v0.16.1** 2026-04-13 ## CyborgDB v0.16.1 ### Behavior Changes * `query()` now returns only `id` fields by default when `include` is not specified * Previously defaulted to `["distance", "metadata"]`; new default is `[]` * Pass `include=["distance", "metadata"]` explicitly to retain the prior behavior * Applies to both the embedded library and the REST service (`QueryRequest`, `BatchQueryRequest`, and `BinaryQueryRequest` all default `include` to `[]`) * **Breaking change for REST API clients**: requests without an explicit `include` field will no longer receive `distance` or `metadata` in the response ### Bug Fixes * Fixed an S3 backing store bug to properly support S3 versioned objects * Fixed a distance computation bug affecting query result ordering * Fixed an arm64 Linux issue where `cyborgdb-core` could fail to load runtime dependencies * query() now returns vector IDs by default ### Improvements * CUDA wheels now statically link CUDA runtime dependencies for improved portability **v0.16.0** 2026-04-02 ## CyborgDB v0.16.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * CyborgDB now supports **Amazon S3** as a backing store for encrypted indexes * Configure via `CYBORGDB_DB_TYPE=s3` with an S3 connection string * Compatible with AWS S3, MinIO, and any S3-compatible object storage * **CyborgDB Migrate**: New tool for migrating vector embeddings from other databases into CyborgDB * Supports Pinecone, Qdrant, Weaviate, ChromaDB, and Milvus as sources * Interactive TUI wizard or headless TOML-based config for CI/CD pipelines * Install via `pip install cyborgdb-migrate` * IVFSQ default scalar quantization bits increased from 8 to 16 for improved recall accuracy ### Improvements & Bug Fixes * Stability improvements and bug fixes across all components * Ingest errors now properly propagate to callers instead of being silently swallowed * Improved serialization support for all backing store types * New API contract test suite for guaranteed interface stability * Expanded E2E test coverage across all SDK languages and backing stores **v0.15.0** 2026-02-24 ## CyborgDB v0.15.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Significant performance optimizations for all index types * Added new `IVFSQ` index type and replace `IVFFlat` as the default * Deprecated IVF index type * Added standalone support for on-device encrypted indexes without external database dependencies * Added support for binary upsert and query vectors for faster data transfer and reduced memory usage * New `/training-status` endpoint in REST API for monitoring index training progress and status * Improved error handling and logging across all components **v0.14.0** 2025-11-25 ## CyborgDB v0.14.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Significant performance optimizations for `cyborgdb-core`: * Reduced single-query (unbatched) latency by 75% * Introduced `standalone` database mode for quick evaluation and testing: * Automatically enabled when no external database is configured * Useful for rapid prototyping and development without infrastructure overhead * Not recommended for production use - use PostgreSQL or Redis for production deployments * Improved type definitions for TypeScript SDK **v0.13.1** 2025-10-31 ## CyborgDB v0.13.1 ### Bug Fixes * Fixed an issue where `cyborgdb-core` would fail to find runtime dependencies on certain Linux arm64 systems * Exposed demo API key creation on Go and TypeScript SDKs **v0.13.0** 2025-10-27 ## CyborgDB v0.13.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Merged `cyborgdb-lite` functionality into `cyborgdb-core`: * `cyborgdb-lite` package has been deprecated and removed * All features previously available in `cyborgdb-lite` are now included in `cyborgdb-core` * Simplified package structure with a single unified library for embedded use * CyborgDB Service now supports CUDA with `pip install "cyborgdb-service[cuda]"`: * Enables existing `cyborgdb-core` CUDA optimizations in the REST API microservice * Deprecated support for Python 3.9 due to EOL for: * `cyborgdb-core` * `cyborgdb-service` * `cyborgdb-py` **v0.12.0** 2025-08-28 ## CyborgDB v0.12.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Go Client SDK now available: * [`go get github.com/cyborginc/cyborgdb-go`](https://pkg.go.dev/github.com/cyborginc/cyborgdb-go) * Automatic index management enabled by default in CyborgDB Service: * Simplifies setup and reduces manual configuration * `IndexConfig` classes now optional - CyborgDB can auto-configure indexes on the fly based on data & usage characteristics * Training & retraining now handled automatically, optimizing index performance without manual intervention * Queries can now automatically determine the optimal number of clusters to search * LangChain integration now available for Python Client SDK **v0.11.0** 2025-06-26 ## CyborgDB v0.11.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript & TypeScript) ### New Features * CyborgDB is now available as a **REST API** microservice * Available as a Python package ([`cyborgdb-service`](https://pypi.org/project/cyborgdb-service/)) * Available as a Docker image ([`cyborginc/cyborgdb-service`](https://hub.docker.com/r/cyborginc/cyborgdb-service)) * CyborgDB Client SDKs now available for REST API microservice * Python ([`cyborgdb`](https://pypi.org/project/cyborgdb/)) * JavaScript ([`cyborgdb`](https://www.npmjs.com/package/cyborgdb)) * TypeScript ([`cyborgdb`](https://www.npmjs.com/package/cyborgdb)) * Introduced API key management and a new Admin Dashboard for enhanced operational control * Optimized concurrency handling using opportunistic mutexes to improve performance under load * Improved Docker container reliability and stability across deployment environments **v0.10.0** 2025-04-30 ## CyborgDB v0.10.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker - *early access*) * Client SDK (Python, JavaScript & TypeScript - *early access*) ### New Features * CyborgDB REST API service in **early access** * CyborgDB Client SDKs in **early access** * Python * JavaScript * TypeScript * [LangChain integration for CyborgDB](/versions/latest/integrations/langchain/introduction) now available * Install via `pip install "cyborgdb-core[langchain]"` * Use via `from cyborgdb_core.integrations.langchain import CyborgVectorStore` * Supports both `cyborgdb-core` and `cyborgdb-lite` * Added configurable logging utility for embedded library in C++ and [Python](/versions/latest/embedded/python/client/logger) **v0.9.2** 2025-04-14 ## CyborgDB v0.9.2 ### New Features * `cyborgdb_lite` is now available for **evaluation** and **non-commercial use** on [PyPI](https://pypi.org/project/cyborgdb-lite/) **v0.9.1** 2025-03-28 ## CyborgDB v0.9.1 ### Bug Fixes * Fixed a bug where [automatic embedding generation](/versions/latest/embedded/guides/encrypted-indexes/create-index#automatic-embedding-generation) would not load the model correctly when using [`load_index()`](/versions/latest/embedded/guides/encrypted-indexes/load-index) * Fixed a bug which caused intermittent [`query()`](/versions/latest/embedded/guides/data-operations/query) recall issues on Linux * Fixed incorrect type returns for [`get()`](/versions/latest/embedded/guides/data-operations/get-items) in C++ and Python APIs ### Improvements * Enabled pre-filtering on [metadata queries](/versions/latest/embedded/guides/data-operations/metadata-filtering) to improve performance * Added annotations and IDE auto-completion for the Python API * Expanded support to Python 3.9 - 3.13 **v0.9.0** 2025-02-28 ## CyborgDB v0.9.0 > [!NOTE] > > This release renamed Cyborg Vector Search to **CyborgDB**. **Deployment Model**: Embedded Library (Python & C++) ### New Features * Added support for **metadata fields & query filtering** * Metadata fields can be added to items during [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items#adding-items-with-metadata) calls * [`query()`](/versions/latest/embedded/guides/data-operations/metadata-filtering) calls can filter results based on metadata fields * Added support for **item deletion** * [`delete()`](/versions/latest/embedded/guides/data-operations/delete-items) calls can remove items from the encrypted index * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items) conflicts are now resolved by overwriting existing items * Added support for **automatic embedding generation** * An embedding model can be specified during [index creation](/versions/latest/embedded/guides/encrypted-indexes/create-index#automatic-embedding-generation) * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items#automatic-embedding-generation) calls can generate embeddings directly from index contents * [`query()`](/versions/latest/embedded/guides/data-operations/query#automatic-embedding-generation) calls can use the model to generate embeddings for query vectors ### Breaking Changes * IDs are now `string`-type (instead of `int`) * This impacts `upsert()`, `get()` and `query()` function signatures * `get_item()` and `get_items()` have been replaced by [`get()`](/versions/latest/embedded/guides/data-operations/get-items) **v0.8.0** 2024-12-19 ## Cyborg Vector Search v0.8.0 **Deployment Model**: Embedded Library (Python & C++) ### New Features * Added support for **encrypted item storage & retrieval** * Encrypted indexes can now handle item content storage * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items) calls can take item content as bytes, encrypt and store them in the index * [`get_item()`](/versions/latest/embedded/guides/data-operations/get-items) calls can retrieve encrypted item content and decrypt them * Client-side caching now available for encrypted indexes (via [`max_cache_size`](/versions/latest/embedded/guides/encrypted-indexes/create-index) parameter) * Client can now handle more than one index via multiple `EncryptedIndex` objects * Optimizations: * Full-pipeline GPU acceleration for encrypted indexes * Optimized quantization and ranking logic * Backing store batch operations for improved performance ### Breaking Changes * Python & C++ APIs now split into two classes: * [`Client`](/versions/latest/embedded/guides/encrypted-indexes/create-client) class now handles DB backend connection, index creation and loading * [`EncryptedIndex`](/versions/latest/embedded/guides/encrypted-indexes/create-index) class now handles data operations (e.g., `upsert()`, `query()`, etc.) **v0.7.0** 2024-10-31 ## Cyborg Vector Search v0.7.0 **Deployment Model**: Embedded Library (Python & C++) ### New Features * First *public* release of Cyborg Vector Search * Python API available through PyBind11 * GPU acceleration with CUDA support # CyborgDB Docs Source: https://docs.cyborg.co/index ![CyborgDB](https://mintcdn.com/cyborg/o5z3-JbkwPXf99Si/images/cyborgdb-white.svg?fit=max\&auto=format\&n=o5z3-JbkwPXf99Si\&q=85\&s=7ad60fe8f70762276000d401bece8503) The vector database that keeps\ your data encrypted at rest, in transit, and in use.Similarity search directly on encrypted embeddings — self-hosted in your VPC or on-prem. AES-256-GCM with your KMS key, per-operation key derivation, keys zeroized after use. **CyborgDB** is an encrypted vector database — similarity search directly on encrypted embeddings, with per-operation key derivation via your KMS and keys zeroized after use. Only the final candidates are decrypted. It runs self-hosted and standalone — persisting to local disk (default) or S3 — exposes a familiar API that slots into existing AI pipelines, and can be [GPU-accelerated with NVIDIA cuVS](https://developer.nvidia.com/blog/bringing-confidentiality-to-vector-search-with-cyborg-and-nvidia-cuvs/). \<5msp95 encrypted query latency 100M+vectors per index Zerodata leaves your boundary ### Choose Your Path > [card] [Learn the Fundamentals](versions/latest/intro/about) > > Understand the architecture and principles behind encrypted vector search > [card] [Start Building](versions/latest/intro/quickstart) > > Get hands-on with CyborgDB in minutes using our quickstart guide > [card] [Explore Deployment Options](versions/latest/intro/deployment-models) > > Discover embedded libraries, managed service, and custom deployment options ### Documentation Structure > [card] [Introduction](versions/latest/intro/about) > > Core concepts, deployment models, and getting started guides > [card] [CyborgDB Service](versions/latest/service/guides/intro/about) > > CyborgDB self-hosted with REST API and client SDKs > [card] [CyborgDB Embedded](versions/latest/embedded/guides/intro/about) > > Self-hosted, embedded deployments with Python and C++ bindings > [card] [Integrations](versions/latest/integrations/about) > > LangChain and other framework integrations for seamless adoption > [card] [How to Use These Docs](versions/latest/intro/using-docs) > > Navigation tips and conventions used throughout these docs # Access Control (RBAC) Source: https://docs.cyborg.co/versions/latest/embedded/guides/advanced/access-control CyborgDB supports per-user access control (RBAC) on an encrypted index. Instead of sharing the single root index key with every caller, the holder of the **root** index KEK can mint per-user keys that grant scoped `read` and/or `write` access. Each user then loads the index with their own per-user key and is restricted to the permissions they were granted. > [!NOTE] > > **Key model.** Each index is encrypted under a 32-byte Key-Encryption-Key (KEK) — the `index_key`. The root KEK holder mints per-user wrapped keys; **the set of wraps that exist *is* the permission set** — there is no separate permission flag. A read-only user simply has no write wrap. Managing users (create / delete / list) is always gated on the root KEK. *** ## Minting User Keys The root holder calls `create_user_keys`, supplying the new user's 16-byte identifier, their 32-byte per-user KEK, the permissions to grant, and the **root** index KEK as the admin gate. ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb import secrets client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) # Root index KEK — the admin gate for user management index_key = secrets.token_bytes(32) index = client.create_index("shared_index", index_key) # Mint a read-only user and a read/write user reader_id = secrets.token_bytes(16) reader_kek = secrets.token_bytes(32) index.create_user_keys(reader_id, reader_kek, permissions=["read"], index_key=index_key) writer_id = secrets.token_bytes(16) writer_kek = secrets.token_bytes(32) index.create_user_keys(writer_id, writer_kek, permissions=["read", "write"], index_key=index_key) ``` You must securely deliver each user's `user_id` and `user_kek` to that user out-of-band — together they are that user's credentials for the index. *** ## Loading the Index as a User A user loads the index with their own KEK as the `index_key` and passes their `user_id`. From then on, every operation is gated to the permissions they hold — a read-only user's `upsert`/`delete` is rejected, raising `RuntimeError`. ```python Python icon="python" theme={null} # The read-only user loads the index with their own key user_index = client.load_index("shared_index", reader_kek, user_id=reader_id) # Reads are allowed (user's KEK + user_id gate every data op) results = user_index.query( query_vectors=[0.1, 0.2, 0.3, 0.4], top_k=5, index_key=reader_kek, user_id=reader_id, ) # Writes are rejected for a read-only user # user_index.upsert([...], index_key=reader_kek, user_id=reader_id) # raises RuntimeError — no write wrap ``` > [!NOTE] > > Every data operation requires the `index_key=` keyword argument; an RBAC user passes their KEK as `index_key=` together with `user_id=`. *** ## Listing and Revoking Users User management is always gated on the **root** KEK. `list_user_keys` returns each user's id and whether they have read/write; `delete_user_keys` revokes a user (idempotent). ```python Python icon="python" theme={null} # List all users (root-gated) for u in index.list_user_keys(index_key=index_key): print(u["user_id"], u["has_read"], u["has_write"]) # Revoke a user (idempotent, root-gated) index.delete_user_keys(reader_id, index_key=index_key) ``` *** ## API Reference For full signatures and exceptions, refer to the API Reference: > [card] [Python API Reference](../../python/encrypted-index/manage-users) > > API reference for `create_user_keys` / `list_user_keys` / `delete_user_keys` in Python # Configure an Encrypted Index Source: https://docs.cyborg.co/versions/latest/embedded/guides/advanced/configure-index > [!NOTE] > > Index configuration is automatically handled by default. This guide allows you to override these defaults to customize index behavior & performance characteristics. CyborgDB uses a single index type: a disk-backed inverted-file (IVF) index. Rather than choosing between several index variants, you tune one index with a small set of knobs. The index retrieves results in two stages: a fast first stage narrows down candidates using a compact Product-Quantized (PQ) representation, then a rerank stage recomputes exact distances against the stored vectors to deliver high recall. This gives you the speed of a quantized index with the accuracy of an exact rerank, all within a single index that scales to disk. You configure the index at **creation time** (dimension, storage precision, metric), at **training time** (clustering parameters), and at **query time** (`n_probes`, `rerank_mult`). *** ## Creating an Index The most common path is to let CyborgDB choose sensible defaults. You only need an index name and a 32-byte key; the `dimension` is auto-detected from your first upsert (or derived from `embedding_model` if you provide one). ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb import secrets client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) index_key = secrets.token_bytes(32) # 32-byte index KEK # Create an index with defaults (dimension auto-detected on first upsert) index = client.create_index("test_index", index_key) ``` ### Creation Parameters You can override the defaults at creation time: * `dimension`: vector dimensionality. Optional — auto-detected from the first upsert, or derived from `embedding_model` if provided. * `storage_precision`: the on-disk dtype used for the rerank vectors. `float32` (default) gives the highest recall; `float16` roughly **halves disk footprint** with a slight precision loss. Acceptable values are `numpy.float32` / `numpy.float16` (or the strings `"float32"` / `"float16"`) in Python. * `embedding_model`: an optional built-in model name that enables automatic text embedding (no `sentence-transformers`/`torch` install required) and overwrites the dimension. Call `cyborgdb.supported_embedding_models()` for accepted names. * `metric`: the distance metric — `"euclidean"` (default), `"cosine"`, or `"squared_euclidean"`. ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb import numpy as np import secrets index_key = secrets.token_bytes(32) # Create an index with explicit configuration index = client.create_index( "test_index", index_key, dimension=768, storage_precision=np.float16, # halve disk footprint vs. float32 metric="cosine" ) ``` > [!TIP] > > Use `float16` storage precision when disk footprint matters more than the last fraction of a percent of recall. For most workloads the recall difference is negligible. *** ## Training Parameters For datasets larger than \~50,000 vectors, you should train the index to build the IVF clustering. Training accepts several optional tuning parameters: * `n_lists`: the number of clusters (inverted lists). `0` (default) auto-selects a value based on the dataset size. More lists make each list smaller (faster, finer-grained search) but require more `n_probes` at query time to maintain recall. * `max_iters`: maximum k-means iterations (default `100`). * `tolerance`: convergence tolerance for k-means (default `1e-6`). * `max_memory`: a soft cap (in MB) on memory used during training; `0` (default) means no limit. * `batch_size`: training batch size; `0` (default) lets CyborgDB choose automatically. ```python Python icon="python" theme={null} # Train the index with custom clustering parameters index.train( n_lists=4096, max_iters=100, tolerance=1e-6, max_memory=0, # no limit index_key=index_key, ) ``` For more on the training lifecycle, see [Training an Encrypted Index](../encrypted-indexes/train-index). *** ## Query-Time Parameters The index exposes two knobs at query time that trade recall against latency: * `n_probes`: how many clusters to search per query. Higher values increase recall at some latency cost. `0` (default) auto-selects based on `n_lists`. * `rerank_mult`: the stage-1 retrieval multiplier. CyborgDB first retrieves `rerank_mult * top_k` candidates using the compact PQ representation, then reranks them against the stored vectors. Higher values improve recall at some latency cost (default `50`). ```python Python icon="python" theme={null} # Tune recall vs. latency at query time results = index.query( query_vectors=[0.5, 0.9, 0.2, 0.7], top_k=10, n_probes=32, rerank_mult=10, index_key=index_key, ) ``` *** ## Customizing Distance Metrics By default, CyborgDB uses `euclidean` distance. You can override this by providing a `metric` parameter at index creation: ```python Python icon="python" theme={null} # Existing setup ... index = client.create_index( "index_name", index_key, metric="cosine" ) ``` The currently supported distance metrics are: * `"cosine"`: Cosine similarity. * `"euclidean"`: Euclidean distance. * `"squared_euclidean"`: Squared Euclidean distance. *** ## API Reference For more information on configuring an encrypted index, refer to the API Reference: > [card] [Python API Reference](../../python/types) > > API reference for `StoragePrecision` and index types in Python # External Key Management (KMS) Source: https://docs.cyborg.co/versions/latest/embedded/guides/advanced/kms CyborgDB can persist a per-index **KMS envelope** — a small record describing how an index's 32-byte KEK is wrapped by an external Key Management Service. A service layer can then read the envelope at request time, unwrap the KEK with the external KMS, and hand the plaintext KEK to the SDK. The envelope itself is represented by the `KMSBlob` type and stored alongside the index. > [!NOTE] > > KMS key wrapping is **advanced and optional**, and primarily intended for the **service layer**. Embedded SDK users who supply their own KEK directly (see [Managing Encryption Keys](./managing-keys)) can ignore these functions entirely, or use `provider="none"`, in which case nothing key-derived is stored and the caller supplies the plaintext KEK per request. *** ## The KMS Envelope Each index is encrypted with AES-256-GCM under a 32-byte KEK. The KMS envelope records *how* that KEK is wrapped so it can be unwrapped later. Supported providers: * `"aws"` — the KEK is wrapped with AES-256-GCM under a value stored in AWS Secrets Manager. * `"aws-kms"` — the KEK is wrapped via `kms.Encrypt` using an AWS KMS key. * `"none"` — no external wrapping; the caller supplies the plaintext KEK per request and nothing is stored. The envelope is described by a `KMSBlob`, whose fields are: `kms_name`, `provider`, `key_id`, `region` (strings), `wrapped_kek` (bytes), `version` (int), and `created_at` (unix epoch seconds). *** ## Storing an Envelope Use `create_index_kms` for a strict insert (fails if an envelope already exists) or `push_index_kms` for an idempotent upsert. Both take a `config_location` ([`StorageConfig`](../../python/types)) identifying where the index keystore lives, the index name, and the `KMSBlob`. ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb # Where the index keystore lives config = cyborgdb.StorageConfig.disk("/tmp/cyborgdb") blob = cyborgdb.KMSBlob( kms_name="prod-kms", provider="aws-kms", key_id="arn:aws:kms:us-east-1:123456789012:key/abcd-...", region="us-east-1", wrapped_kek=b"...", # KEK wrapped by the external KMS version=1, ) # Strict insert (fails if an envelope already exists for this index) cyborgdb.create_index_kms(config, "my_index", blob) # Idempotent upsert (creates or overwrites) cyborgdb.push_index_kms(config, "my_index", blob) ``` *** ## Reading and Deleting an Envelope `get_index_kms` returns the stored `KMSBlob`; `delete_index_kms` removes it (idempotent). A service layer typically reads the envelope, unwraps the KEK with the external KMS, then uses the plaintext KEK when loading the index. ```python Python icon="python" theme={null} # Read the envelope back blob = cyborgdb.get_index_kms(config, "my_index") print(blob.provider, blob.key_id, blob.version) # ... unwrap blob.wrapped_kek with your KMS to recover the 32-byte KEK ... # index_key = kms_unwrap(blob.wrapped_kek) # index = client.load_index("my_index", index_key) # Delete the envelope (idempotent) cyborgdb.delete_index_kms(config, "my_index") ``` > [!TIP] > > For embedded deployments where you already hold the KEK, you don't need the KMS envelope at all — pass the KEK directly to `create_index` / `load_index`. See [Managing Encryption Keys](./managing-keys) and [Access Control (RBAC)](./access-control) for per-user keys. *** ## API Reference For full signatures and the `KMSBlob` type, refer to the API Reference: > [card] [Python API Reference](../../python/kms) > > API reference for the KMS module functions and `KMSBlob` in Python # Managing Encryption Keys Source: https://docs.cyborg.co/versions/latest/embedded/guides/advanced/managing-keys Encryption keys are one of the most critical elements that enable the security guarantees of CyborgDB. By default, one key is used for the entire index, and it secures all index data, including: * Vector embeddings * Item contents * Metadata This main key, referred to in the API as the `index_key`, is a 256-bit (32-byte) symmetric Key-Encryption-Key (KEK)—the same you would find when using AES-256 encryption. CyborgDB wraps a per-index data key (DEK) under this KEK internally and encrypts all index data with that DEK using **AES-256-GCM**; callers only ever handle the KEK. CyborgDB's cryptography is based entirely on well-established cryptographic standards, including AES-256-GCM, HMAC, and SHA-3 (Keccak). Without the correct `index_key`, it is impossible to use a CyborgDB Encrypted Index. You cannot upsert vectors, query the index, or even delete it. Hence, it is critical to manage these encryption keys safely. > [!NOTE] > > For multi-tenant scenarios, you can mint per-user keys with scoped read/write permissions instead of sharing the root KEK — see [Access Control (RBAC)](./access-control). To persist an external-KMS wrapping envelope for the KEK, see [External Key Management (KMS)](./kms). *** ## Generating Key Locally (for Development) > [!WARNING] > > **Do not store keys locally for production purposes.** For production environments, always use secure options such as Hardware Security Modules (HSMs) or a Key Management Service (KMS). See [Using Key Management Services (for Production)](#using-key-management-services-for-production). For local development and evaluation, you can generate a 256-bit encryption key locally and use it in your calls to CyborgDB. Here’s how you can do this using OpenSSL and integrate it with CyborgDB in Python. The `index_key` must be **exactly 32 raw bytes**. The simplest way to generate one is with the language's cryptographic RNG. **1. Generate a 32-byte key** ```python Python icon="python" theme={null} import secrets index_key = secrets.token_bytes(32) # 32-byte index KEK ``` Alternatively, generate a key on the command line and persist the raw bytes to a file: ```bash theme={null} openssl rand 32 > index_key.bin ``` This saves 32 raw bytes to `index_key.bin`. Ensure that this file is kept secure and not included in your source control. **2. Use the key with CyborgDB** Pass the key directly to `create_index` (or `load_index`): ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb # Backing store: local disk (or use .s3("bucket") for cloud persistence) client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) # Load the raw 32-byte key (or use the one generated above) with open("index_key.bin", "rb") as key_file: index_key = key_file.read() # Use the encryption key index = client.create_index("test_index", index_key) ``` Again, this should only be used for development and evaluation purposes; do not store encryption keys locally for production use. > [!TIP] > > If you don't have an API key yet, see [Get an API Key](../../../intro/get-api-key). *** ## Using Key Management Services (for Production) For production environments, a Key Management Service (KMS) or Hardware Security Module (HSM) is strongly recommended to securely store and manage encryption keys. This ensures the highest level of security by isolating the keys from application logic and providing robust access controls. ### Overview of KMS A KMS is a managed service that provides centralized control over encryption keys, including: * **Key Generation:** Automatically generating keys with required levels of entropy. * **Secure Storage:** Storing keys in a tamper-proof environment. * **Access Control:** Enforcing strict role-based access control (RBAC) policies. * **Auditing:** Logging key usage for compliance and monitoring. ### Supported KMS Providers CyborgDB can integrate with popular KMS providers, such as: * **AWS Key Management Service (AWS KMS)** * **Google Cloud Key Management (Google Cloud KMS)** * **Azure Key Vault** * **HashiCorp Vault** *** ## Step-by-Step Example: AWS KMS **1. Generate a Data Key Using AWS KMS** **Option A: Command Line** Use the AWS CLI to generate a data key: ```bash theme={null} aws kms generate-data-key \ --key-id \ --key-spec AES_256 \ --output json ``` * Replace `` with your KMS Key ID or ARN. * The command outputs a JSON object containing both the plaintext key and the encrypted key. **Example Output:** ```json theme={null} { "CiphertextBlob": "", "Plaintext": "", "KeyId": "arn:aws:kms:region:account-id:key/Your-Key-Id" } ``` **Note:** The `Plaintext` and `CiphertextBlob` are Base64-encoded binary data. **Option B: Python** ```python theme={null} import boto3 # Initialize AWS KMS client kms_client = boto3.client('kms') # Generate a data key response = kms_client.generate_data_key( KeyId='Your-Key-Id', # Replace with your KMS Key ID or ARN KeySpec='AES_256' ) # Extract the plaintext and encrypted data key plaintext_key = response['Plaintext'] # This is the raw binary key encrypted_key = response['CiphertextBlob'] # This is the encrypted key ``` **2. Store the Encrypted Key** * **Encrypted Key:** Since it's encrypted, you can safely store it in your application's configuration file, environment variable, or secure parameter store. Example of storing the encrypted key in Base64-encoded format: ```python theme={null} import base64 # Base64-encode the encrypted key for storage encrypted_key_b64 = base64.b64encode(encrypted_key).decode('utf-8') # Store 'encrypted_key_b64' in your application's configuration ``` **3. Use the Encrypted Key in Your Application at Runtime** In your application code, decrypt the encrypted key at runtime using AWS KMS: ```python theme={null} import boto3 import base64 import cyborgdb_core as cyborgdb # Backing store: local disk (or use .s3("bucket") for cloud persistence) client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) # Initialize AWS KMS client kms_client = boto3.client('kms') # Load the encrypted key from your configuration encrypted_key_b64 = '...' # Replace with your stored encrypted key (Base64-encoded) # Decode the Base64-encoded encrypted key encrypted_key = base64.b64decode(encrypted_key_b64) # Decrypt the key at runtime — yields the raw 32-byte KEK response = kms_client.decrypt( CiphertextBlob=encrypted_key ) index_key = response['Plaintext'] # This is your 256-bit (32-byte) KEK # Use the key with CyborgDB index = client.create_index("test_index", index_key) ``` **Explanation:** * **Encrypted Key Storage:** The encrypted key (`encrypted_key_b64`) is safe to store in configuration files since it's encrypted. * **Runtime Decryption:** The `kms_client.decrypt` method securely retrieves the plaintext key at runtime. **4. Ensure IAM Permissions** Your application needs permission to use the `kms:Decrypt` action. Attach a policy to your IAM role or user: ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "kms:Decrypt", "Resource": "arn:aws:kms:your-region:your-account-id:key/Your-Key-Id" } ] } ``` ### Benefits of This Approach * **Security:** The plaintext key is never stored persistently. It's only available in memory during runtime. * **Simplicity:** You can generate and manage the key using AWS KMS and standard AWS tools. * **No Need for Secure Storage:** Since the encrypted key is safe to store in your application's configuration, you don't need additional secure storage solutions. By generating the data key using AWS KMS and storing only the encrypted key, you can securely manage your encryption key without needing to store it securely elsewhere. Your application decrypts the encrypted key at runtime using AWS KMS, ensuring that the plaintext key is only available in memory during execution. > [!NOTE] > > CyborgDB can also persist a per-index **KMS envelope** describing how the KEK is wrapped, so a service layer can unwrap it at request time. See [External Key Management (KMS)](./kms) for details on `KMSBlob` and the `create_index_kms` / `push_index_kms` / `get_index_kms` / `delete_index_kms` functions. # CyborgDB Usage Telemetry Source: https://docs.cyborg.co/versions/latest/embedded/guides/advanced/usage-telemetry Since version `v0.11.0`, CyborgDB uses privacy-preserving telemetry to track usage. This usage data is used in order to: * Bill paying customers based on their usage * Improve the product by understanding how it is used > [!TIP] > > No private data is ever collected or shared, and all telemetry data is encrypted before being sent to the server. ### What is Collected Below you can find a comprehensive list of the telemetry events that are collected: | Event Name | Description | | - | - | | `initialize` | Triggered when the CyborgDB library is initialized. | | `create_index` | Triggered when a new index is created. | | `delete_index` | Triggered when an index is deleted. | | `upsert` | Triggered when items are added to an index. A count of the items added is also included. | | `query` | Triggered when a query is performed on an index. Includes the top-k value. | | `delete` | Triggered when items are deleted from an index. A count of the items deleted is also included. | | `get` | Triggered when an item is retrieved from an index. | CyborgDB's usage telemetry was built from the ground up to be privacy-preserving, with data minimization and no third-party sharing. We do **NOT** collect any private data, such as raw content, embeddings, or queries. All telemetry is compliant with our [Privacy Policy](https://www.cyborg.co/privacy-policy). Should you have any questions, please [contact us](https://www.cyborg.co/contact). # Add Items to an Encrypted Index Source: https://docs.cyborg.co/versions/latest/embedded/guides/data-operations/add-items Once you have created or loaded an encrypted index, you can add items to it. To do this, you can use the `upsert()` function: ```python Python icon="python" theme={null} # Items to add to the encrypted index items = [ {"id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4]}, {"id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8]}, {"id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12]} ] # Add items to the encrypted index (index_key is required on every data operation) index.upsert(items, index_key=index_key) ``` > [!NOTE] > > Every data operation takes `index_key` as a keyword argument — the client does not cache the key across calls. You can also pass `user_id=` for an RBAC user. ## Adding Items with Contents It's also possible to store item contents alongside vectors. To do this, include `contents` to the `upsert()` call. The contents field accepts both strings and bytes. All contents are encoded to bytes and encrypted before storage using the index key, and will be returned as bytes when retrieved with `get()`. ```python Python icon="python" theme={null} # Items to add to the encrypted index items = [ {"id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Hello!"}, {"id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "contents": "World!"}, {"id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12], "contents": "Cyborg!"} ] # Add items to the encrypted index index.upsert(items, index_key=index_key) ``` ## Adding Items with Metadata CyborgDB also supports metadata storage, retrieval and filtering. To add metadata to an item, include `metadata` in the `upsert()` call. All metadata fields will be encrypted using the index key. ```python Python icon="python" theme={null} # Items to add to the encrypted index items = [ {"id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "metadata": {"name": "Alice", "age": 30}}, {"id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "metadata": {"name": "Bob", "age": 40}}, {"id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12], "metadata": {"name": "Charlie", "age": 50}} ] # Add items to the encrypted index index.upsert(items, index_key=index_key) ``` For more info on metadata storage and filtering, see [Metadata Filtering](./metadata-filtering). ## Automatic Embedding Generation If you provided an `embedding_model` during index creation, you can automatically generate embeddings for items by providing `contents` to the `upsert()` call: ```python Python icon="python" theme={null} # ... index creation and embedding model setup embedding_model = "all-MiniLM-L6-v2" index = client.create_index( index_name="my_index", index_key=index_key, embedding_model=embedding_model ) # Items to add to the encrypted index items = [ {"id": "item_1", "contents": "Hello, World!"}, {"id": "item_2", "contents": "Hello, Cyborg!"} ] # Add items to the encrypted index index.upsert(items, index_key=index_key) ``` In this example, the `embedding_model` will automatically generate embeddings for the `contents` field. Note that `contents` must be a string. It will also be converted to `bytes` for encrypted item storage. Embeddings are generated by CyborgDB's built-in embedding models; no extra package is needed. `embedding_model` must name one of them. List them with `cyborgdb.supported_embedding_models()`; the bare model name (without the organization prefix) is also accepted, so `"all-MiniLM-L6-v2"` works. ## API Reference For more information on adding items to an encrypted index, refer to the API reference: > [card] [Python API Reference](../../python/encrypted-index/upsert) > > API reference for `upsert()` in Python # Full-text and Hybrid Search Source: https://docs.cyborg.co/versions/latest/embedded/guides/data-operations/bm25-search CyborgDB supports **BM25 full-text search** on designated metadata fields, alongside vector search. This unlocks two new query paths on top of the existing vector query: | Query | Method | Ranks by | | - | - | - | | Full text (no vector) | `query_metadata(text=...)` | BM25 score | | Hybrid (BM25 + vector) | `query(query_vectors=..., text=...)` | weighted RRF of BM25 rank + vector rank | Text-search data is stored encrypted: the backing store never sees a readable term, which terms a document contains, or how many documents contain a given term. ## How it works * **BM25 is enabled by designating fields, not by a flag.** An index with at least one `full_text` field supports text search. An index with none is unaffected. * **Text is sourced from metadata field values**, not from `contents`. `contents` stays arbitrary binary and is never analyzed. * **English only (currently)**: lowercase → split on non-alphanumeric → stopword filter → Porter2 stem. * **Designations are fixed for the index's lifetime.** They cannot currently be changed after creation. * **Fusion is by rank, not score.** BM25 relevance and vector distance have no common unit, so hybrid queries fuse *positions*: `score(d) = Σ w_leg / (k + rank_leg(d))`. `alpha` sets the leg weights, `rrf_k` damps how much a single leg's top hit dominates, and `window_mult` sets how deep each leg retrieves before fusing. ## Designating fields At index creation, mark fields as `full_text` in `metadata_schema` — or use the `text_fields` shorthand: ```python theme={null} import cyborgdb_core as cyborgdb import secrets client = cyborgdb.Client( api_key="", storage_config=cyborgdb.StorageConfig.disk("./my_index"), ) index_key = secrets.token_bytes(32) # Shorthand: text_fields=[...] desugars to full_text: true in metadata_schema. index = client.create_index( "articles", index_key, dimension=128, text_fields=["title", "body"], ) ``` The longhand is equivalent, and is what you need when a field wants other policy too: ```python theme={null} index = client.create_index( "articles", index_key, dimension=128, metadata_schema={ "title": {"full_text": True}, # analyzed for BM25 "body": {"full_text": True}, "author": {"filterable": True}, # ordinary exact-match / filterable field }, bm25_k1=1.2, # term-frequency saturation (default 1.2) bm25_b=0.75, # length-normalization strength (default 0.75) ) ``` > [!NOTE] > > `full_text=True` requires `filterable=False`, and is incompatible with `pattern=True`. In Python, `{"full_text": True}` alone implies `filterable: False` — only writing `filterable: True` yourself is a contradiction. If a field needs to be both searchable and exact-match filterable, store it twice under two names. ## Ingest Nothing special is needed at upsert — text comes from the designated fields' metadata values: ```python theme={null} import numpy as np rng = np.random.default_rng(0) index.upsert([ { "id": "a1", "vector": rng.random(128, dtype=np.float32), "metadata": { "title": "Encrypted vector search", "body": "Searching over encrypted embeddings without decrypting them.", "author": "ann", }, }, { "id": "a2", "vector": rng.random(128, dtype=np.float32), "metadata": { "title": "Index tuning", "body": "Choosing n_lists and probe counts for recall.", "author": "bob", }, }, ], index_key=index_key) ``` A `full_text` field that is missing or whose value is not a JSON string is skipped for that item (the value is never logged) and excluded from that field's document count. An empty or all-stopword value is legal and simply contributes no terms. ## Full-text query — no vector ```python theme={null} results = index.query_metadata( text="encrypted search", top_k=10, index_key=index_key, ) # [{"id": "a1", "score": 2.63}, {"id": "a2", "score": 1.15}, ...] for r in results: print(r["id"], r["score"]) ``` Rows come back descending by BM25 score (ties by id). `score` is present only when there is one — a filter-only `query_metadata()` call has nothing to score, so the key is absent rather than `None`. ### Narrowing the searched fields, weighting, and AND ```python theme={null} # Search only some of the designated fields index.query_metadata(text="encrypted", text_fields=["title"], index_key=index_key) # Weight the fields (parallel to the searched fields — name them explicitly) index.query_metadata( text="encrypted search", text_fields=["title", "body"], text_field_weights=[2.0, 1.0], index_key=index_key, ) # Require every term (AND) instead of any (OR, the default) index.query_metadata(text="encrypted search", require_all_terms=True, index_key=index_key) ``` ### Composing with a filter A filter combines with text as a **pre-filter** — it resolves first, then only its survivors are scored. Document frequency and per-field corpus stats stay corpus-global, so a document's score never depends on the filter: ```python theme={null} index.query_metadata( text="encrypted", filters={"author": "ann"}, index_key=index_key, ) ``` `order_by` is not supported together with `text` — text results rank by score. ## Hybrid query — BM25 + vector Set `text=...` on `query()` to fuse BM25 with vector similarity: ```python theme={null} query_vector = rng.random(128, dtype=np.float32) results = index.query( query_vectors=query_vector, text="encrypted search", top_k=10, alpha=0.5, # 0 = pure BM25, 1 = pure vector; default 0.5 include=["metadata"], index_key=index_key, ) # [{"id": "a1", "score": 0.0161, "metadata": {...}}, ...] ``` Hybrid results carry `score` (fused relevance, larger = better) and **never** `distance` — a document matched by text alone has no vector distance to report. A query vector is required even at `alpha=0` — it fixes the batch shape. For text search with no vector, use `query_metadata(text=...)`. > [!NOTE] > > Hybrid queries narrow which filters are accepted. `$regex` on a non-`pattern` field, and any predicate on an explicitly non-`filterable` field, work in a pure `query()` but are rejected once `text` is set, because the text leg can only be filtered on fields resolvable from the encrypted metadata index. ## Tuning | Knob | Raise it to | Lower it to | | - | - | - | | `bm25_k1` (1.2) | let repeated terms keep adding score | saturate sooner; 0 = presence/absence only | | `bm25_b` (0.75) | punish long documents harder; 1 = full normalization | ignore length; 0 = no normalization | | `alpha` (0.5) | favor vector similarity | favor keyword relevance | | `rrf_k` (60) | reward cross-leg agreement further down each list | trust each leg's top hits more | | `window_mult` (3) | let documents deep in both legs still win on fusion | retrieve less per leg | Two non-obvious properties worth knowing before tuning: * **No positive `rrf_k` lets one leg's rank-1 outrank two legs' rank-2.** Solving `1/(k+1) = 2/(k+2)` gives `k = 0`. If you want a single leg to dominate, use `alpha`, not `rrf_k`. * **`rrf_k` is only meaningful as deep as the legs actually retrieved.** At `window_mult = 3` and `top_k = 10` each leg is 30 deep, and every value of `k` above \~28 makes the same decision — so sweeping `rrf_k` alone at a shallow window will look like the knob does nothing. Sweep the two together. ## Constraints and gotchas * **`full_text` + `filterable=True` (explicit) is an error**, and **`full_text` + `pattern=True` is an error always** — a field can't be both full-text and pattern-indexed. If you need a field both searchable and exact-match filterable, store it twice under two names. * **Designations are fixed for the index's lifetime.** They cannot currently be changed after creation. * **`order_by` cannot be combined with `text`.** Text results rank by score. * **Not currently supported:** phrase queries, `NOT`/exclusion, nested boolean expressions, non-English analysis, and dual-indexing a field as both analyzed and exact-match. * **The analyzer is versioned.** The pipeline version, stopword-list hash, and stemmer identity are stamped into the index at creation. Opening an index with a build whose analyzer differs is a loud error, not silent recall loss — every existing document was indexed by the old analyzer. * **Multi-tenant guidance:** use index-per-tenant. Corpus statistics are per index, so co-mingling tenants behind a `tenant_id` filter gives every tenant blended term rarity — BM25 statistics are deliberately global and never scoped to a filtered subset. ## Common errors | Error | Cause | Fix | | - | - | - | | `text query requires an index with at least one full_text field` | No field designated | Designate at creation; it cannot be added later | | `text query names 'x', which is not a full_text field` | `text_fields` naming an undesignated field | Use a designated field, or drop the argument to search all | | `text_fields / text_field_weights / require_all_terms require non-empty query text` | Text knob set without `text` | Pass `text`, or drop the knob | | `full_text=True requires filterable=False` | Both written explicitly | Drop `filterable`, or use two fields | | `bm25_k1/bm25_b … require at least one full_text field` | Tuning an index with no text | Designate a field, or drop the parameters | | `order_by is not supported together with query text` | Two ordering authorities | Drop `order_by` | | `rrf_k must be > 0` / `window_mult must be >= 1` | Explicit `0` passed | Pass `None` for the default | | `hybrid query cannot filter on a non-indexed metadata field` | Filter on a non-`filterable` / non-`pattern` field with `text` set | Move the filter to a `filterable` / `pattern` field, or drop `text` | | Empty result, no error | Text analyzed to no terms (empty, punctuation, all stopwords), or no term matched | Expected: degenerate input is defined-empty | # Delete Encrypted Items Source: https://docs.cyborg.co/versions/latest/embedded/guides/data-operations/delete-items You can delete items from an encrypted index using `delete()`: ```python Python icon="python" theme={null} index.delete(["item1", "item2"], index_key=index_key) ``` > [!WARNING] > > This operation is irreversible. Once you delete an item, you cannot recover it. ## API Reference For more information on deleting items from an encrypted index, refer to the API reference: > [card] [Python API Reference](../../python/encrypted-index/delete) > > API reference for `delete()` in Python # Get Encrypted Items Source: https://docs.cyborg.co/versions/latest/embedded/guides/data-operations/get-items If you have added items to the index with the `contents` field, you can retrieve them via `get()`. > [!TIP] > > The `contents` field is always returned as bytes, regardless of whether it was originally stored as a string or bytes. All contents are encoded to bytes and encrypted before storage. ```python Python icon="python" theme={null} # IDs of items to retrieve ids = ["item_20", "item_11"] include = ["contents", "metadata"] # Retrieve items from the encrypted index (index_key is required on every data operation) items = index.get(ids, include=include, index_key=index_key) print(items) # Example item (contents returned as bytes) # [{"id": "item_20", "contents": b"Hello, World!", "metadata": {"type": "txt"}}, # {"id": "item_11", "contents": b"Hello, Cyborg!", "metadata": {"type": "md"}}] ``` ## API Reference For more information on getting items from an encrypted index, refer to the API reference: > [card] [Python API Reference](../../python/encrypted-index/get) > > API reference for `get()` in Python # Metadata Filtering Source: https://docs.cyborg.co/versions/latest/embedded/guides/data-operations/metadata-filtering CyborgDB supports metadata tagging and filtering, enabling fine-grained search filters in addition to encrypted vector search. Metadata, like vectors, are end-to-end encrypted and never exposed in plaintext outside of the client. ## Supported Metadata The following metadata types are supported: * Boolean * String * List of strings * Numbers (will be stored as fp64) ## Adding Items with Metadata To add items with metadata tags, you can pass a dictionary of key-value pairs to the `metadata` field during `upsert`: ```python Python icon="python" theme={null} # Example data in the format: # [{id: str, vector: List[float], metadata: Dict}] data = [ {"id": "item_1", "vector": [0.1, 0.1, 0.1, 0.1], "metadata": {"category": "dog"}}, {"id": "item_2", "vector": [0.2, 0.2, 0.2, 0.2], "metadata": {"category": "cat"}} ] # Upsert data with metadata index.upsert(data, index_key=index_key) ``` This metadata will be encrypted and stored in the index. > [!TIP] > > Metadata field names and string values are **case-sensitive**. Ensure that the metadata field names and values are consistent when filtering queries. ## Filtering Queries with Metadata CyborgDB supports a subset of [MongoDB's Query and Projection Operators](https://www.mongodb.com/docs/manual/reference/operator/query/). For more details, see [Metadata Query Operators](#metadata-query-operators) To filter a query with metadata, you can pass a dictionary of filters to the `filters` field during `query`: ```python Python icon="python" theme={null} # Example query query_vectors = [0.5, 0.9, 0.2, 0.7] top_k = 10 # Example filters filters = { "category": {"$in": ["dog", "cat"]} # Will match either 'dog' or 'cat' } # Perform query results = index.query(query_vectors=query_vectors, top_k=top_k, filters=filters, index_key=index_key) ``` ## Metadata Indexing By default, all metadata fields are indexed using encrypted indexing, so filters on indexed fields resolve directly from the index and filtered queries stay fast. Filters on fields declared `filterable: False` in the index's [`metadata_schema`](../../python/client/create-index#metadata-schema), and `$regex` / `$contains` on fields not declared `pattern: True`, are instead evaluated on decrypted metadata after retrieval, which is slower. ## Metadata Query Operators CyborgDB supports a subset of [MongoDB's Query and Projection Operators](https://www.mongodb.com/docs/manual/reference/operator/query/). Specifically, the following operators are supported: | Filter | Types | Description | | :-: | :-: | - | | `$exists` | `any` | Matches vectors that have this field | | `$eq` | `Boolean`, `Number`, `String` | Matches vectors with the metadata that is equal to the filter value | | `$ne` | `Boolean`, `Number`, `String` | Matches vectors with the metadata that is not equal to the filter value | | `$in` | `Number`, `String` | Matches vectors with metadata that is in the filter array | | `$nin` | `Number`, `String` | Matches vectors with metadata that is not in the filter array | | `$gt` | `Number` | Matches vectors with metadata that is greater than the filter value | | `$gte` | `Number` | Matches vectors with metadata that is greater than or equal to the filter value | | `$lt` | `Number` | Matches vectors with metadata that is less than the filter value | | `$lte` | `Number` | Matches vectors with metadata that is less than or equal to the filter value | | `$regex` | `String` | Matches vectors whose metadata string matches the given pattern (see [Regex patterns](#regex-patterns)) | | `$contains` | `String` | Matches vectors whose metadata string contains the given substring | ### Regex patterns `$regex` and `$contains` patterns are evaluated by [RE2](https://github.com/google/re2/wiki/Syntax), matched **unanchored** — the same convention as MongoDB's `$regex`. Anchor with `^` and `$` explicitly if you need a full-string match. RE2 is linear-time and safe against catastrophic-backtracking patterns, but accepts a narrower syntax than PCRE / ECMAScript regex. In particular: * **Lookahead** and **lookbehind** (`(?=…)`, `(?!…)`, `(?<=…)`, `(? [card] [Python API Reference](../../python/encrypted-index/query) > > API reference for `query()` in Python # Create Client Source: https://docs.cyborg.co/versions/latest/embedded/guides/encrypted-indexes/create-client The `Client` class provides an interface to initialize, create, load and list Encrypted Indexes. Encrypted Indexes, in turn, expose data-related functionality such as upserting, querying, and deleting. ## Creating the Client To create the client, supply a [backing store](../../../intro/backing-stores) (`StorageConfig`) which it will use to persist all encrypted index data. No API key is required — without one the client runs in free-tier mode, capped at 1,000,000 items per index. The simplest backing store is a local directory on disk: ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb # Local disk backing store client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb-dev")) ``` To lift the free-tier cap, pass an API key as the first argument (`cyborgdb.Client(api_key, storage_config=...)`). Get a key from the [CyborgDB Admin Dashboard](https://cyborgdb.co/new); for more info, follow [this guide](../../../intro/get-api-key). Bear in mind that all contents stored in the backing store are end-to-end encrypted, meaning that **no index contents are stored in plaintext**. ## Persistent Backing Stores `StorageConfig` exposes two static factories: `disk(path)` (local disk) and `s3(bucket)` (AWS S3 or S3-compatible). ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb # Local persistent storage on disk client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) # Or AWS S3 / S3-compatible (MinIO, etc.) client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.s3( "my-bucket", region="us-east-1", credentials=cyborgdb.S3Credentials(access_key="...", secret_key="..."), # omit for the default credential chain )) ``` Omit `credentials=` to use the AWS default credential provider chain (environment variables, `~/.aws/credentials`, EC2 instance profile, EKS IRSA). The disk store also accepts cache options (`cache_vectors`, `cache_metadata`, `cache_ids`) to keep hot data in memory. ## Setting Device Configurations CyborgDB can be accelerated in two ways: * CPU Multithreading (via `OpenMP`) -> can scale with the number of CPU cores available * GPU Acceleration (via `CUDA` & `cuVS`) -> can increase the speed of certain operations (e.g., ingestion) by an order of magnitude. You can control either of these with the optional `cpu_threads` and `gpu_config` parameters: ```python Python icon="python" theme={null} # ... existing setup # Enable GPU for specific operations (upsert and train) gpu_config = cyborgdb.GPUConfig(upsert=True, train=True) client = cyborgdb.Client( storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb"), cpu_threads=4, gpu_config=gpu_config ) ``` > [!NOTE] > > `gpu_config` can only be set if running on a CUDA-enabled system with the CUDA driver installed. Use [`GPUConfig`](../../python/types#gpuconfig) to specify which operations (upsert, train, query) should use GPU acceleration. By default, `cpu_threads` will use all available cores, and `gpu_config` will be `None` (no GPU acceleration). ## API Reference For more information on the `Client` class, refer to the API Reference: > [card] [Python API Reference](../../python/client/client) > > API reference for `Client` in Python # Create a New Encrypted Index Source: https://docs.cyborg.co/versions/latest/embedded/guides/encrypted-indexes/create-index To create an encrypted index, you need to specify an index name (must be unique) and an index key: ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb import secrets # Create a client (use the same backing store you'll load the index with) client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) # Generate an encryption key for the index index_key = secrets.token_bytes(32) # Create an encrypted index index = client.create_index("my_index", index_key) ``` This creates a new encrypted index. The vector dimension is auto-detected from the first upsert (or derived from an `embedding_model`); you can also set it explicitly with the keyword-only `dimension` parameter. Other optional parameters include `metric` (`"euclidean"` default, `"cosine"`, or `"squared_euclidean"`) and `storage_precision`. `storage_precision` picks the on-disk format for the rerank vectors: `"float32"` (default) or `"float16"` to halve the footprint at a slight precision cost, or one of the TurboQuant tiers `"tq12"` / `"tq8"` / `"tq6"` / `"tq4"` (12/8/6/4 bits per dimension) to trade storage for a small recall/latency cost — `"tq4"` is the most aggressive (\~8x smaller than `float32`, \~94% recall\@100 on a 768-dimensional benchmark dataset). All tiers work with every metric; the choice is fixed at create time. > [!NOTE] > > Vector dimension is capped at **65535** (`0xFFFF`). Passing `dimension=0` still means auto-detect. Explicit values outside `[0, 65535]`, including negatives, raise `ValueError` at `create_index()` time. > [!WARNING] > > **Store `index_key` before you upsert any data.** CyborgDB has no key-recovery path — data encrypted with a lost key is unrecoverable. For anything past evaluation, keep the key in AWS Secrets Manager, Vault, or your KMS. See [Managing Keys](../advanced/managing-keys). > [!NOTE] > > To lift the free-tier 1M-items-per-index cap, pass an API key as the first argument (`cyborgdb.Client(api_key, storage_config=...)`). Get a key from the [CyborgDB Admin Dashboard](https://cyborgdb.co/new). See [Get an API Key](../../../intro/get-api-key). ## Automatic Embedding Generation > [!TIP] > > Text embedding is built into `cyborgdb-core` — no `[embeddings]` extra or `sentence-transformers`/`torch` install required. Call `cyborgdb.supported_embedding_models()` for the accepted model names. Enable automatic embedding generation for the encrypted index by setting `embedding_model` in `create_index()`: ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb import secrets # Create a client (use the same backing store you'll load the index with) client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) # Generate an encryption key for the index index_key = secrets.token_bytes(32) # Create an encrypted index with managed embedding generation index = client.create_index( "my_index", index_key, embedding_model="all-MiniLM-L6-v2" ) ``` ## API Reference For more information on creating encrypted indexes, refer to the API reference: > [card] [Python API Reference](../../python/client/create-index) > > API reference for `create_index()` in Python # Delete an Encrypted Index Source: https://docs.cyborg.co/versions/latest/embedded/guides/encrypted-indexes/delete-index > [!WARNING] > > This action is irreversible. Proceed with caution. To delete an existing encrypted index, you can [load it](./load-index) and then call the `delete_index()` method. ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb # Create a client (use the same backing store the index was created with) client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) # Provide the SAME 32-byte key used when the index was created. # Retrieve it from your KMS/secret store — a fresh random key here would fail the load. index_key = bytes.fromhex("...") # the 64-char hex of your existing 32-byte index key # Load the encrypted index index = client.load_index("my_index", index_key) # Delete the index (index_key is required) index.delete_index(index_key=index_key) ``` ## API Reference For more information on deleting an encrypted index, refer to the API reference: > [card] [Python API Reference](../../python/encrypted-index/delete-index) > > API reference for `delete_index()` in Python # Introduction to Encrypted Indexes Source: https://docs.cyborg.co/versions/latest/embedded/guides/encrypted-indexes/introduction Encrypted Indexes are the main organizational unit of CyborgDB. One encrypted index is secured with one index key, which provides useful segmentation: * **Cryptographic isolation**: each index is isolated via encryption keys, making it impossible to query/view the contents of an index without proper access/authorization. * **Multi-tenancy**: this separation makes it easy to separate data scopes (e.g., tenants) in a robust and secure manner. One client can manage an arbitrary number of indexes, and an index can contain an arbitrary amount of items/vectors. All contents of the index are end-to-end encrypted, meaning that they remain encrypted throughout their lifecycle (at-rest and in-use). # List Encrypted Indexes Source: https://docs.cyborg.co/versions/latest/embedded/guides/encrypted-indexes/list-indexes To see which existing encrypted indexes are available to your CyborgDB client, you can use `list_indexes`: ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) indexes = client.list_indexes() print(indexes) # Example output: # ["index_one", "index_two", "index_three"] ``` ## API Reference For more information on listing encrypted indexes, refer to the API reference: > [card] [Python API Reference](../../python/client/list-indexes) > > API reference for `list_indexes()` in Python # Load an Existing Encrypted Index Source: https://docs.cyborg.co/versions/latest/embedded/guides/encrypted-indexes/load-index If you've previously created an encrypted index, you can connect to it to add, query or delete data from it. You will need to know the index's name as well as its key to do so: ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb # Create a client (use the same backing store the index was created with) client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) # Provide the SAME 32-byte key used when the index was created. # Retrieve it from your KMS/secret store — a fresh random key here would fail the load. index_key = bytes.fromhex("...") # the 64-char hex of your existing 32-byte index key # Load an encrypted index index = client.load_index("my_index", index_key) ``` > [!NOTE] > > For role-based access control (RBAC), a per-user load passes the user's 16-byte identifier: `load_index("my_index", user_kek, user_id=user_id)`. The supplied key then acts as that user's key-encryption key, and per-operation permissions are enforced. > [!WARNING] > > You will need to replace `index_key` with your own index encryption key. > For production use, we recommend that you use an HSM or KMS solution. > For more details, see [Managing Encryption Keys](../advanced/managing-keys). ## API Reference For more information on loading an encrypted index, refer to the API reference: > [card] [Python API Reference](../../python/client/load-index) > > API reference for `load_index()` in Python # Train an Encrypted Index Source: https://docs.cyborg.co/versions/latest/embedded/guides/encrypted-indexes/train-index CyborgDB uses an IVF index, which leverages clustering algorithms to segment the index into smaller sections for efficient querying. These clustering algorithms must be trained on the specific data being indexed in order to adequately represent that data. In the embedded library version of CyborgDB, this training must be explicitly called once enough vectors have been added: ```python Python icon="python" theme={null} # Train the encrypted index (index_key is required on every data operation) index.train(index_key=index_key) # Train the index with a specific number of clusters index.train(n_lists=1024, index_key=index_key) # Train the index with specific configuration index.train( n_lists=1024, batch_size=64, max_iters=100, index_key=index_key, ) ``` > [!TIP] > > Training needs at least `10,000` vectors in the index (ingested via `upsert`) **and** at least `2 * n_lists` vectors. Below either threshold, `train` does not raise: it logs a warning and leaves the index untrained. Check `is_trained()` to confirm training took effect. ## Training Parameters Parameters are available to customize the training process: | Parameter | Type | Default | Description | | - | - | - | - | | `n_lists` | `int` | `None` | *(Optional)* Number of inverted index lists to create in the index. When `None`, auto-determines based on the number of vectors in the index. | | `batch_size` | `int` | `None` | *(Optional)* Size of each batch for training. When `None`, defaults to `0` (auto-selected). | | `max_iters` | `int` | `None` | *(Optional)* Maximum number of iterations for training. When `None`, defaults to `100`. | | `tolerance` | `float` | `None` | *(Optional)* Convergence tolerance for training. When `None`, defaults to `1e-6`. | | `max_memory` | `int` | `None` | *(Optional)* Maximum memory to use for training. When `None`, defaults to `0` (no limit). | `n_lists` is the number of clusters into which each vector in the index can be categorized. Typically, the higher the value, the higher the recall (but also the slower the indexing process). As a good rule of thumb, `n_lists` should be: * A base-2 number (e.g., `2,048`, `4,096`). Not a requirement, but yields performance optimizations. * Each cluster should have between `100` - `10,000` vectors; so `n_lists` should be roughly between `1/100` - `1/10,000` of the total number of items which will be indexed. If not provided, `n_lists` will be auto-selected based on the number of vectors in the index. ## Avoid the large-untrained-query warning While training is technically optional (you can use CyborgDB without ever calling `train`), it is recommended that you do so once you have a large number of vectors in the index (e.g., `> 50,000`). If you don't, and you call `query`, you will see a warning in the console, stating: ``` Warning: querying untrained index with more than 50000 indexed vectors. ``` ## API Reference For more information on training an encrypted index, refer to the API reference: > [card] [Python API Reference](../../python/encrypted-index/train) > > API reference for `train()` in Python # CyborgDB Embedded Source: https://docs.cyborg.co/versions/latest/embedded/guides/intro/about CyborgDB Embedded provides a native Python library, enabling you to integrate confidential vector search directly into your applications. This deployment model gives you maximum control, performance, and security by running entirely within your infrastructure. ## Why Choose CyborgDB Embedded? **Maximum Security**\ Your data never leaves your environment. Vector embeddings remain encrypted on your hardware with keys under your complete control. **Ultimate Performance**\ Direct integration eliminates network overhead and serialization costs. Take advantage of local CPU/GPU resources and custom optimizations. **Full Control**\ Configure every aspect of the system - from index parameters to memory management. Perfect for custom requirements and specialized deployments. **Any Environment**\ Deploy in air-gapped networks, edge devices, or custom infrastructure where external APIs aren't suitable. Air-gapped use requires running without an API key (free tier). *** ## Quick Start > [card] [Embedded Quickstart](/versions/latest/embedded/guides/intro/quickstart) > > *Get running in 5 minutes with Python* > > Step-by-step guide covering embedded library setup and usage. > [!NOTE] > > **Free API Key Users**: If you're using a free API key, CyborgDB Embedded will be limited to 1,000,000 items per index. > > Upgrade to a [paid plan](https://www.cyborg.co/pricing) to remove this limitation. *** ## Architecture Overview CyborgDB Embedded integrates directly into your application process: ```mermaid theme={null} flowchart TB subgraph Your_Applications [Your Application] Library("CyborgDB Library (Python)") end Library --> Disk("Disk (local)") Library --> S3("S3 (AWS or S3-compatible)") ``` **Key Benefits:** * No external API dependencies without an API key * Sub-millisecond query latency potential * Complete data sovereignty * Custom integration possibilities *** ## When to Use Embedded vs Service > [tab] Choose CyborgDB Embedded > > * **Data must stay on-premises** - Regulatory or security requirements > * **Ultra-low latency needed** - Sub-millisecond response requirements > * **Custom integration required** - Unique workflow or system requirements > * **Cost optimization critical** - High-volume usage with cost sensitivity > * **Air-gapped deployment** - No external network access available (free tier without an API key) > * **Single application focus** - One primary application using vector search > [tab] Consider CyborgDB Service > > * **Multi-language teams** - Need SDKs in multiple languages > * **Microservice architecture** - Want to separate vector operations from application logic > * **Operational simplicity** - Prefer service-based deployment patterns > * **Independent scaling** - Need to scale vector operations separately > * **Team collaboration** - Multiple teams need access to the same vector data ## Next Steps > [card] [Start Building](/versions/latest/embedded/guides/intro/quickstart) > > *Get hands-on with the quickstart guide* > > Follow our comprehensive guide covering Python setup > [card] [Browse Capabilities](../encrypted-indexes/introduction) > > *Explore detailed integration examples* > > Learn about encrypted index operations and data management > [card] [Framework Integration](../../../integrations/langchain/introduction) > > *LangChain and other integrations* > > Drop-in replacement for existing vector stores Ready to build confidential AI applications with complete control? Start with our [Embedded Quickstart](/versions/latest/embedded/guides/intro/quickstart) guide! # CyborgDB Embedded Quickstart Source: https://docs.cyborg.co/versions/latest/embedded/guides/intro/quickstart Get started with CyborgDB in minutes. **1. Install CyborgDB** Install CyborgDB on your machine. CyborgDB needs Python 3.10 or newer. The `python3` that ships with macOS is 3.9, so check `python3 --version` before installing. ```bash Python theme={null} # Install CyborgDB: pip install cyborgdb-core # For LangChain integration, install with: pip install "cyborgdb-core[langchain]" ``` **2. Create a Client** Create a CyborgDB client: ```python Python icon="python" theme={null} import cyborgdb_core as cyborgdb import secrets # Backing store: local disk, for simple persistent storage. # Use .s3("bucket") for cloud persistence. client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) ``` > [!NOTE] > > Without an API key the client runs in free-tier mode, capped at 1,000,000 items per index. Pass a key from the [CyborgDB Admin Dashboard](https://cyborgdb.co/new) as the first argument (`cyborgdb.Client(api_key, storage_config=...)`) for unlimited usage. See [Get an API Key](../../../intro/get-api-key). For more info, refer to [Create a Client](../encrypted-indexes/create-client). **3. Create an Encrypted Index** Create an encrypted index with CyborgDB: ```python Python icon="python" theme={null} # ... Continuing from the previous step # Generate an encryption key for the index index_key = secrets.token_bytes(32) # Create an encrypted index index = client.create_index( index_name="my_index", index_key=index_key ) ``` > [!WARNING] > > **Store `index_key` before you upsert any data.** CyborgDB has no key-recovery path — data encrypted with a lost key is unrecoverable. For anything past evaluation, keep the key in AWS Secrets Manager, Vault, or your KMS. See [Managing Keys](../advanced/managing-keys). For more info, refer to [Create an Encrypted Index](../encrypted-indexes/create-index). **4. Add Items to Encrypted Index** Add data to the encrypted index via Upsert: ```python Python icon="python" theme={null} # ... Continuing from the previous step # Add items to the encrypted index items = [ {"id": "item_1", "vector": [0.1, 0.2, 0.3, 0.4], "contents": "Hello!"}, {"id": "item_2", "vector": [0.5, 0.6, 0.7, 0.8], "contents": "Bonjour!"}, {"id": "item_3", "vector": [0.9, 0.10, 0.11, 0.12], "contents": "Hola!"} ] # index_key must be supplied on every data operation index.upsert(items, index_key=index_key) ``` For more info, refer to [Add Items](../data-operations/add-items). **5. Query Encrypted Index** Query the encrypted index for similar vectors and chain `get()` for contents. CyborgDB's encrypted search index stores only embeddings — contents live in separately encrypted item records retrieved via `get()`, so a real result reads with a two-step pattern: ```python Python icon="python" theme={null} # ... Continuing from the previous step # Query the encrypted index — include distance and metadata on results. results = index.query( query_vectors=[0.1, 0.2, 0.3, 0.4], top_k=2, include=["distance", "metadata"], index_key=index_key, ) # Retrieve contents for the top matches (contents come back as bytes). top_items = index.get([r["id"] for r in results], index_key=index_key) by_id = {item["id"]: item for item in top_items} for r in results: contents = by_id[r["id"]]["contents"].decode() print(f"ID: {r['id']} Distance: {r['distance']:.4f} Contents: {contents}") # Delete the index so the example can be run again (the key above is not saved). index.delete_index(index_key=index_key) ``` > [!NOTE] > > `include=["contents"]` is not a valid query option — contents are only retrievable via `get()`. See [Query an Encrypted Index](../data-operations/query) and [Get Items](../data-operations/get-items) for the full API. **6. Next Steps** Learn more about CyborgDB: > [card] [Python API Reference](../../python/introduction) > > Explore the Python API reference to learn how to use CyborgDB in your applications. # Client Source: https://docs.cyborg.co/versions/latest/embedded/python/client/client `Client` is the main class exposed by CyborgDB. It exposes the functionality necessary to create, load, list and delete indexes. Operations within encrypted indexes (such as `upsert` and `query`) are contained within the `EncryptedIndex` class returned by `create_index` and `load_index`. ## Constructor ```text theme={null} Client(api_key: str = "", storage_config: StorageConfig, cpu_threads: int = 0, gpu_config: GPUConfig | None = None, *, embedding_threads: int | None = None) ``` Initializes a new CyborgDB `Client` instance. ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `api_key` | `str` | `""` | *(Optional)* API key for your CyborgDB account. If omitted or empty, the client runs in free-tier mode, capped at 1,000,000 items per index. Pass a key from the [Admin Dashboard](../../../intro/get-api-key) for unlimited usage. When omitted, pass `storage_config` as a keyword argument. | | `storage_config` | [`StorageConfig`](../types#storageconfig) | - | Backing store for all index keystores. Built via the static factories `StorageConfig.disk(path)` or `StorageConfig.s3(bucket)`. | | `cpu_threads` | `int` | `0` | *(Optional)* Number of CPU threads to use for computations (defaults to `0` = all cores). | | `gpu_config` | [`GPUConfig`](../types#gpuconfig) \| `None` | `None` | *(Optional)* GPU operations configuration. Specify which operations use GPU acceleration (defaults to `None`, no GPU). | | `embedding_threads` | `int` \| `None` | `None` | *(Optional, keyword-only)* Threads per text-embedding call (defaults to `1`; concurrent callers already run in parallel). | > [!NOTE] > > A single `storage_config` replaces the former `index_location` / `config_location` / `items_location` trio. The store is shared across all per-index keystores. ### Exceptions > [accordion] ValueError > > * Throws if the `cpu_threads` parameter is less than `0`. > * Throws if the [`StorageConfig`](../types#storageconfig) is invalid. > * Throws if the GPU is not available when `gpu_config` is set. > * Throws if the backing store is not available. > * Throws if the Client could not be initialized. ### Example Usage ```python theme={null} import cyborgdb_core as cyborgdb # Example 1: Local disk backing store, free-tier (no API key) client1 = cyborgdb.Client( storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb-dev"), cpu_threads=4 ) # Example 2: With an API key for unlimited usage, GPU on upsert and train # Get an API key from https://cyborgdb.co/new gpu_config = cyborgdb.GPUConfig(upsert=True, train=True) client2 = cyborgdb.Client( api_key="cyborg_...", storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb"), cpu_threads=4, gpu_config=gpu_config ) # Proceed with further operations ``` > [!TIP] > > Use `StorageConfig.disk("/path")` for local persistence or `StorageConfig.s3("bucket")` for S3-backed persistence. See [`StorageConfig`](../types#storageconfig). *** ## Methods ### get_cpu_threads() Returns the number of CPU threads configured for this client. ```python theme={null} def get_cpu_threads(self) -> int: ... ``` #### Returns `int`: The number of CPU threads. #### Example Usage ```python theme={null} threads = client.get_cpu_threads() print(f"Using {threads} CPU threads") ``` *** ### is_gpu_enabled() Checks if GPU acceleration is enabled for this client. ```python theme={null} def is_gpu_enabled(self) -> bool: ... ``` #### Returns `bool`: True if GPU acceleration is enabled, False otherwise. #### Example Usage ```python theme={null} gpu_enabled = client.is_gpu_enabled() print(f"GPU acceleration is {'enabled' if gpu_enabled else 'disabled'}") ``` *** ### get_gpu_config() Returns the GPU operations configuration for this client. ```python theme={null} def get_gpu_config(self) -> GPUConfig: ... ``` #### Returns [`GPUConfig`](../types#gpuconfig): The GPU operations configuration. #### Example Usage ```python theme={null} gpu_config = client.get_gpu_config() print(f"GPU operations: upsert={gpu_config.upsert}, train={gpu_config.train}, query={gpu_config.query}") ``` # Create Index Source: https://docs.cyborg.co/versions/latest/embedded/python/client/create-index Creates and returns a new encrypted index. CyborgDB uses a single IVF index type, so there is no `index_config` parameter to choose between index variants. ```python theme={null} def create_index(self, index_name: str, index_key: bytes, *, dimension: int | None = None, storage_precision = None, embedding_model: str | None = None, metric: str | None = None, metadata_schema: dict | None = None, text_fields: list[str] | None = None, bm25_k1: float | None = None, bm25_b: float | None = None, logger: Logger | None = None) -> EncryptedIndex ``` > [!NOTE] > > All parameters after `index_key` are keyword-only. ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `index_name` | `str` | - | Name of the index to create. Must be unique. | | `index_key` | `bytes` | - | 32-byte encryption key (KEK) for the index, used to secure the index data. | | `dimension` | `int` \| `None` | `None` | *(Optional, keyword-only)* Dimensionality of vector embeddings. When `None`, auto-detected from the first upsert (or derived from `embedding_model`). | | `storage_precision` | `str` \| `np.float32` \| `np.float16` | `StoragePrecision.FLOAT32` | *(Optional, keyword-only)* On-disk format for vectors, fixed at create time. The raw strings (`"float32"`, `"float16"`, `"tq12"`, `"tq8"`, `"tq6"`, `"tq4"`) as well as numpy's dtypes `np.float32` / `np.float16` are accepted. | | `embedding_model` | `str` \| `None` | `None` | *(Optional, keyword-only)* Name of a built-in embedding model for automatic text embeddings. Sets the index `dimension`; an explicit `dimension` must match; call `cyborgdb.supported_embedding_models()` for the full list. | | `metric` | `str` \| `None` | `"euclidean"` | *(Optional, keyword-only)* Distance metric to use: `"euclidean"`, `"cosine"`, or `"squared_euclidean"`. See [`DistanceMetric`](../types#distancemetric). | | `metadata_schema` | `dict` \| `None` | `None` | *(Optional, keyword-only)* Per-field metadata indexing policy, keyed by field name (dot-paths for nested fields). Fixed at create time and immutable. See [Metadata Schema](#metadata-schema) below. | | `text_fields` | `list[str]` \| `None` | `None` | *(Optional, keyword-only)* Shorthand for marking each listed field `full_text: True` in `metadata_schema`. | | `bm25_k1` | `float` \| `None` | `1.2` | *(Optional, keyword-only)* BM25 term-frequency saturation, `>= 0`. Requires at least one `full_text` field. | | `bm25_b` | `float` \| `None` | `0.75` | *(Optional, keyword-only)* BM25 length-normalization strength, in `[0, 1]`. Requires at least one `full_text` field. | | `logger` | [`Logger`](./logger) | `None` | *(Optional, keyword-only)* Logger instance for capturing operation logs. | > [!NOTE] > > For more info on auto-generating embeddings, refer to [Auto-Generate Embeddings](../../guides/data-operations/add-items#automatic-embedding-generation). ### Metadata Schema `metadata_schema` sets the per-field indexing policy. Metadata stays schemaless — this controls how each field is indexed, not what may be stored. Fields left out inherit the default (indexed and filterable). ```python theme={null} metadata_schema = { "title": {"filterable": True, "pattern": True}, # regex-searchable "internal_blob": {"filterable": False}, # stored, not index-filterable } ``` Three knobs per field: * `filterable` (default `True`) — index the field so filters on it resolve from the encrypted metadata index (pre-filter path, and the only path [`query_metadata()`](../encrypted-index/query-metadata) uses). Setting `False` still stores the field, but a filter referencing it forces the dense post-filter path on [`query()`](../encrypted-index/query#filters) — cheaper writes, slower filtered queries. * `pattern` (default `False`) — additionally index the field for pattern matching, which is what makes `$regex` / `$contains` index-resolvable. Requires `filterable=True`. * `full_text` (default `False`) — route the field's string value through the BM25 analyzer instead of exact-match indexing, which is what enables full-text search. Incompatible with `pattern=True` and with an explicit `filterable=True`; implies `filterable=False`. On `query()` these are a performance hint: filters that miss the index just fall back to a post-filter over the decrypted metadata, same rows either way. On `query_metadata()` they are enforced — `$regex` / `$contains` on a non-`pattern` field, or any filter on a `filterable=False` field, raises `ValueError`. ### Returns `EncryptedIndex`: An instance of the newly created encrypted index. ### Exceptions > [accordion] ValueError > > * Throws if the index name is not unique. > * Throws if the index configuration is invalid. > * Throws if `metadata_schema` sets `pattern=True` without `filterable=True`. > * Throws if `metadata_schema` sets `full_text=True` together with `pattern=True` or an explicit `filterable=True`. > * Throws if `bm25_k1` or `bm25_b` is set and no field is `full_text`. > * Throws if `dimension` is negative. > * Throws if the index could not be created. > [accordion] EmbeddingModelUnavailable > > * Throws if `embedding_model` cannot be downloaded or loaded (network or model-hub failure, offline cache miss). Often transient. ### Example Usage #### Automatic Setup ```python theme={null} import cyborgdb_core as cyborgdb import secrets api_key = "your_api_key_here" # Replace with your CyborgDB API key client = cyborgdb.Client(api_key, cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) index_name = "my_index" index_key = secrets.token_bytes(32) # 32-byte index KEK — store securely # Dimension auto-detected from the first upsert index = client.create_index(index_name, index_key) ``` #### Explicit Setup ```python theme={null} import cyborgdb_core as cyborgdb import numpy as np import secrets api_key = "your_api_key_here" # Replace with your CyborgDB API key client = cyborgdb.Client(api_key, cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) index_name = "my_index" index_key = secrets.token_bytes(32) # 32-byte index KEK — store securely # Optional: Set up logging logger = cyborgdb.Logger.instance() logger.configure(level="info", to_file=True, file_path="index_creation.log") index = client.create_index( index_name, index_key, dimension=128, storage_precision=np.float16, # halve the on-disk footprint of stored vectors metric="cosine", logger=logger, ) ``` #### With TurboQuant Storage Precision ```python theme={null} import cyborgdb_core as cyborgdb import secrets client = cyborgdb.Client("your_api_key_here", cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) # TQ8 → 8 bits per dimension. On 768-dim vectors that's ~4x smaller than float32 index = client.create_index( "compact_index", secrets.token_bytes(32), dimension=768, storage_precision="tq8", metric="cosine", ) ``` #### With Per-Field Metadata Policy ```python theme={null} # Opt `title` into pattern matching; keep `internal_blob` out of the # metadata index (still stored, still filterable via post-filter on query()). index = client.create_index( "docs_index", index_key, dimension=384, metadata_schema={ "title": {"filterable": True, "pattern": True}, "internal_blob": {"filterable": False}, }, ) # $regex now resolves from the index on query_metadata() and query() alike. results = index.query_metadata(filters={"title": {"$regex": "^intro"}}, index_key=index_key) ``` # List Indexes Source: https://docs.cyborg.co/versions/latest/embedded/python/client/list-indexes Returns a list of all encrypted index names accessible via the client's [`StorageConfig`](../types#storageconfig). ```python theme={null} def list_indexes(self) -> list[str] ``` ### Returns `list[str]`: A list of index names. ### Exceptions > [accordion] ValueError > > * Throws if the list of indexes could not be retrieved. ### Example Usage ```python theme={null} import cyborgdb_core as cyborgdb client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) print(client.list_indexes()) # Example output: # ["index_one", "index_two", "index_three"] ``` # Load Index Source: https://docs.cyborg.co/versions/latest/embedded/python/client/load-index Loads an existing encrypted index and returns an instance of `EncryptedIndex`. ```python theme={null} def load_index(self, index_name: str, index_key: bytes, logger: Logger | None = None, *, user_id: bytes | None = None) -> EncryptedIndex ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `index_name` | `str` | - | Name of the index to load. | | `index_key` | `bytes` | - | 32-byte encryption key. For a normal load this is the index KEK used during [`create_index()`](./create-index). For an RBAC user-scoped load (`user_id` set), this is that user's 32-byte KEK. | | `logger` | [`Logger`](./logger) | `None` | *(Optional)* Logger instance for capturing operation logs. | | `user_id` | `bytes` \| `None` | `None` | *(Optional, keyword-only)* 16-byte RBAC user identifier. When set, the index is loaded scoped to that user and `index_key` is interpreted as the user's KEK; per-operation permissions are enforced. | > [!NOTE] > > RBAC user keys are minted by the root KEK holder via `create_user_keys`. A user then loads with `load_index(name, their_user_kek, user_id=their_id)`. See [access control](../../guides/advanced/access-control). ### Returns `EncryptedIndex`: An instance of the loaded encrypted index. ### Exceptions > [accordion] ValueError > > * Throws if the index name does not exist. > * Throws if the index could not be loaded or decrypted. ### Example Usage ```python theme={null} import cyborgdb_core as cyborgdb client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) index_name = "my_index" index_key = my_index_key # Same 32-byte KEK used during index creation # Optional: Set up logging logger = cyborgdb.Logger.instance() logger.configure(level="info", to_file=True, file_path="index_loading.log") # Load the existing index with logging enabled index = client.load_index(index_name, index_key, logger=logger) ``` #### RBAC user-scoped load ```python theme={null} # Load the index scoped to an RBAC user, passing that user's KEK as index_key index = client.load_index( index_name, user_kek, # the user's 32-byte KEK user_id=user_id, # the user's 16-byte identifier ) ``` # Logger Source: https://docs.cyborg.co/versions/latest/embedded/python/client/logger The `Logger` class provides logging capabilities for CyborgDB operations. ## Configure Logger ```python theme={null} def configure(self, level: str, to_file: bool = False, file_path: str = None) ``` Configures the logger with the specified log level and output options. ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `level` | `str` | - | Log level. Must be one of: "debug", "info", "warning", "error", "critical". | | `to_file` | `bool` | `False` | Whether to write logs to a file instead of stdout/stderr. | | `file_path` | `str` | `"cyborg_client.log"` | *(Optional)* Path to the log file. Only used when `to_file` is `True`. | ### Exceptions > [accordion] ValueError > > * Throws if the log level is invalid. > * Throws if `level` is `"debug"` in a non-debug build. ### Example Usage ```python theme={null} # Get the logger instance logger = cyborgdb.Logger.instance() # Configure logger to write INFO level logs to console logger.configure(level="info") # Configure logger to write ERROR level logs to a file logger.configure(level="error", to_file=True, file_path="/path/to/logs/cyborgdb.log") ``` > [!TIP] > > The DEBUG level is only available in debug builds of the library. # Delete Source: https://docs.cyborg.co/versions/latest/embedded/python/encrypted-index/delete > [!WARNING] > > This action is irreversible. Proceed with caution. Deletes the specified encrypted items stored in the index, including all its associated fields (`vector`, `contents`, `metadata`). ```python theme={null} def delete(self, ids: List[str], *, index_key: bytes, user_id: bytes = None) ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `ids` | `List[str]` | IDs to delete. | | `index_key` | `bytes` | *(Required, keyword-only)* 32-byte index KEK. See [Index key](#index-key). | | `user_id` | `bytes` | *(Optional, keyword-only)* 16-byte RBAC user identifier. See [Index key](#index-key). | ### Exceptions > [accordion] ValueError > > * Throws if the items could not be deleted. ### Example Usage ```python theme={null} # Load index index = client.load_index( index_name=index_name, index_key=index_key ) # Delete "item_1" and "item_2" index.delete(["item_1", "item_2"], index_key=index_key) ``` ### Index key `index_key` is required on every call. Pass the same 32-byte index KEK you used with [`create_index()`](../client/create-index) / [`load_index()`](../client/load-index). For an [RBAC user](./manage-users), pass the user's KEK as `index_key=` together with their `user_id=`: ```python theme={null} index.delete(["item_1", "item_2"], index_key=user_kek, user_id=user_id) ``` > [!NOTE] > > Deleting items requires write permission. An [RBAC user](./manage-users) without a write wrap cannot delete items. # Delete Index Source: https://docs.cyborg.co/versions/latest/embedded/python/encrypted-index/delete-index > [!WARNING] > > This action is irreversible. Proceed with caution. Deletes the current index and all its associated data. ```python theme={null} def delete_index(self, *, index_key: bytes, user_id: bytes = None) ``` Deletes the current index and its associated data. This action is irreversible, so proceed with caution. ### Parameters | Parameter | Type | Description | | - | - | - | | `index_key` | `bytes` | *(Required, keyword-only)* The 32-byte **root** index KEK. | | `user_id` | `bytes` | *(Optional, keyword-only)* 16-byte RBAC user identifier. | > [!WARNING] > > Deleting an index is an admin operation gated on the **root** index KEK. It rejects [RBAC user](./manage-users) contexts — a per-user key cannot delete the index. ### Exceptions > [accordion] ValueError > > * Throws if the index could not be deleted. ### Example Usage ```python theme={null} # Load index index = client.load_index( index_name=index_name, index_key=index_key ) # Delete the index index.delete_index(index_key=index_key) ``` # Get Source: https://docs.cyborg.co/versions/latest/embedded/python/encrypted-index/get ## Get Retrieves, decrypts and returns items from their IDs. If an item does not exist at that ID, it will return an empty object. ```python theme={null} def get(self, ids: List[str], include: List[str] = ["vector", "contents", "metadata"], *, index_key: bytes, user_id: bytes = None) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `ids` | `List[str]` | - | Item IDs to retrieve & decrypt | | `include` | `List[str]` | `"vector", "contents", "metadata"` | *(Optional)* List of item fields to return. Can include `vector`, `contents`, and `metadata`. | | `index_key` | `bytes` | - | *(Required, keyword-only)* 32-byte index KEK. See [Index key](#index-key). | | `user_id` | `bytes` | `None` | *(Optional, keyword-only)* 16-byte RBAC user identifier. See [Index key](#index-key). | ### Returns `List[Dict]`: Decrypted item fields for each item, including `id` and specified fields (e.g., `vector`, `contents`, and `metadata`). > [!TIP] > > The `contents` field is always returned as bytes, regardless of whether it was originally stored as a string or bytes. All contents are encoded to bytes and encrypted before storage. ### Exceptions > [accordion] ValueError > > * Throws if the item could not be retrieved or decrypted. > * Throws if an unexpected error occurs during retrieval. ### Example Usage ```python theme={null} # Load index index = client.load_index( index_name=index_name, index_key=index_key ) # Retrieve the items using their IDs items = index.get(["item_1", "item_2"], index_key=index_key) print(items) # Example output (contents returned as bytes): # [{"id": "item_1", "vector": [0.1, 0.2], "contents": b"Example contents...", "metadata": {"type": "txt"}}, # {"id": "item_2", "vector": [0.3, 0.4], "contents": b"Example contents...", "metadata": {"type": "md"}}, # Retrieve only the item contents items = index.get(["item_1", "item_2"], include=["contents"], index_key=index_key) print(items) # Example output (contents returned as bytes): # [{"id": "item_1", "contents": b"Example contents..."}, # {"id": "item_2", "contents": b"Example contents..."}] ``` ### Index key `index_key` is required on every call. Pass the same 32-byte index KEK you used with [`create_index()`](../client/create-index) / [`load_index()`](../client/load-index). For an [RBAC user](./manage-users), pass the user's KEK as `index_key=` together with their `user_id=`: ```python theme={null} items = index.get(["item_1", "item_2"], index_key=user_kek, user_id=user_id) ``` # Manage Users (RBAC) Source: https://docs.cyborg.co/versions/latest/embedded/python/encrypted-index/manage-users CyborgDB supports per-user access control (RBAC) on an encrypted index. The holder of the **root** index KEK can mint per-user wrapped keys, each granting `read` and/or `write` access. A user then loads the index with their own per-user key (KEK) and is restricted to the permissions they were granted. > [!NOTE] > > **Key model.** Each index is encrypted under a 32-byte Key-Encryption-Key (KEK) — the `index_key`. The root KEK holder mints per-user keys; **the set of wraps that exist defines the permission set** — there is no separate permission flag. A read-only user simply has no write wrap. Managing users (create / delete / list) is always gated on the root KEK. *** ## create_user_keys Creates per-user wrapped keys granting the specified permissions on the index. Gated on the root index KEK. ```python theme={null} def create_user_keys(self, user_id: bytes, user_kek: bytes, permissions: List[str], *, index_key: bytes) ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `user_id` | `bytes` | 16-byte unique identifier for the user. | | `user_kek` | `bytes` | 32-byte per-user key (KEK). This is the key the user will pass as `index_key` when loading the index. | | `permissions` | `List[str]` | Subset of `{"read", "write"}`. At least one permission must be granted. | | `index_key` | `bytes` | *(Keyword-only, required)* The 32-byte **root** index KEK. Acts as the admin gate authorizing user management. | ### Exceptions > [accordion] ValueError > > * Throws if `permissions` is empty or contains values outside `{"read", "write"}`. > * Throws if `user_id` or the keys are the wrong length. > * Throws if the supplied `index_key` is not the root KEK. > * Throws if the user keys could not be created. ### Example Usage ```python theme={null} import secrets # Admin (root KEK holder) mints a read-only user user_id = secrets.token_bytes(16) # 16-byte user identifier user_kek = secrets.token_bytes(32) # 32-byte per-user key index.create_user_keys( user_id=user_id, user_kek=user_kek, permissions=["read"], index_key=index_key, # root index KEK — the admin gate ) # Distribute (user_id, user_kek) securely to the user. ``` *** ## delete_user_keys Revokes a user's keys. Idempotent — revoking a non-existent user is a no-op. Gated on the root index KEK. ```python theme={null} def delete_user_keys(self, user_id: bytes, *, index_key: bytes) ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `user_id` | `bytes` | 16-byte identifier of the user to revoke. | | `index_key` | `bytes` | *(Keyword-only, required)* The 32-byte **root** index KEK. | ### Example Usage ```python theme={null} # Revoke a user (idempotent) index.delete_user_keys(user_id=user_id, index_key=index_key) ``` *** ## list_user_keys Lists the users with keys on the index and their effective permissions. Gated on the root index KEK. ```python theme={null} def list_user_keys(self, *, index_key: bytes) -> List[dict] ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `index_key` | `bytes` | *(Keyword-only, required)* The 32-byte **root** index KEK. | ### Returns `List[dict]`: One dictionary per user, each with the keys: * `user_id` (`bytes`): the 16-byte user identifier * `has_read` (`bool`): whether the user has a read wrap * `has_write` (`bool`): whether the user has a write wrap ### Example Usage ```python theme={null} users = index.list_user_keys(index_key=index_key) for u in users: print(u["user_id"], "read:", u["has_read"], "write:", u["has_write"]) # Example output: # [{"user_id": b"...", "has_read": True, "has_write": False}] ``` *** ## Loading the index as an RBAC user A user loads the index by passing their own `user_kek` as the `index_key` and their `user_id` (keyword-only) to [`load_index()`](../client/load-index): ```python theme={null} import cyborgdb_core as cyborgdb client = cyborgdb.Client(storage_config=cyborgdb.StorageConfig.disk("/tmp/cyborgdb")) # user_id and user_kek were issued by the root KEK holder via create_user_keys() index = client.load_index("my_index", user_kek, user_id=user_id) # Permitted: this user has the "read" wrap results = index.query(query_vectors=[0.1, 0.2, 0.3], top_k=5, index_key=user_kek, user_id=user_id) # Denied: a read-only user cannot write — this raises index.upsert([{"id": "item_1", "vector": [0.1, 0.2, 0.3]}], index_key=user_kek, user_id=user_id) ``` The permission gate is enforced per operation: a read-only user can `query` / `get` / `list_ids`, but `upsert`, `delete`, and `train` are rejected. Admin operations (`create_user_keys`, `delete_user_keys`, `list_user_keys`, [`delete_index()`](./delete-index)) always require the **root** KEK and reject per-user contexts. > [!TIP] > > Every data operation requires keyword-only `index_key=`. As an RBAC user, pass your `user_kek` as `index_key=` and your `user_id=` on each call. # Query Source: https://docs.cyborg.co/versions/latest/embedded/python/encrypted-index/query ## Single Query Retrieves the nearest neighbors for a given query vector. Passing `text` alongside `query_vectors` turns this into a **hybrid** query that fuses BM25 full-text ranking with the vector ranking (see [Full-text and hybrid search](../../guides/data-operations/bm25-search)). ```python theme={null} def query(self, query_vectors: List[float] = None, query_contents: str = None, top_k: int = None, n_probes: int = None, filters: Dict[str, Any] = None, include: List[str] = None, greedy: bool = False, rerank_mult: int = None, *, text: str = None, text_fields: List[str] = None, text_field_weights: List[float] = None, require_all_terms: bool = False, alpha: float = None, rrf_k: float = None, window_mult: int = None, index_key: bytes, user_id: bytes = None) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `query_vectors` | `List[float]` | - | A single query vector as a list of floats (for single query). | | `query_contents` | `str` | `None` | *(Optional)* Text content to auto-embed as query vector (requires `embedding_model` set during index creation). | | `top_k` | `int` | `None` | *(Optional)* Number of nearest neighbors to return. When `None`, defaults to 100. | | `n_probes` | `int` | `None` | *(Optional)* Number of lists probed during the query; higher values may increase recall but can also reduce performance. When `None` or `0`, automatically determines the optimal value. | | `filters` | `Dict[str, Any]` | `None` | *(Optional)* A dictionary of filters to apply to vector metadata, limiting search scope to these vectors. | | `include` | `List[str]` | `None` | *(Optional)* List of item fields to return. Can include `distance` and `metadata`. When empty, only IDs are returned. | | `greedy` | `bool` | `False` | *(Optional)* Whether to use greedy search (higher recall with same `n_probes`). | | `rerank_mult` | `int` | `50` | *(Optional)* Stage-1 retrieval multiplier for reranking. The index retrieves `rerank_mult * top_k` candidates before reranking them against the stored vectors to produce the final `top_k`. Higher values improve recall at some cost to performance. | | `text` | `str` | `None` | *(Optional, keyword-only)* Query text for a BM25 full-text leg. Setting it makes the query **hybrid**: BM25 ranking is fused with the vector ranking by weighted RRF and each result carries `score` instead of `distance`. Requires an index with at least one `full_text` field. | | `text_fields` | `List[str]` | `None` | *(Optional, keyword-only)* Which `full_text` fields the text leg searches. `None` = all designated fields. Naming a non-`full_text` field raises. | | `text_field_weights` | `List[float]` | `None` | *(Optional, keyword-only)* Per-field weights on the summed per-field BM25 scores, parallel to the searched fields. `None` = 1.0 each. | | `require_all_terms` | `bool` | `False` | *(Optional, keyword-only)* Require every query term to match (AND) instead of any (OR, the default). | | `alpha` | `float` | `None` (default `0.5`) | *(Optional, keyword-only)* Leg blend in `[0, 1]`: `0` = pure BM25, `1` = pure vector. An exact endpoint skips the dead leg's retrieval. | | `rrf_k` | `float` | `None` (default `60`) | *(Optional, keyword-only)* RRF rank-smoothing constant (must be `> 0`). Higher rewards agreement further down each leg's list. | | `window_mult` | `int` | `None` (default `3`) | *(Optional, keyword-only)* Per-leg candidate depth as a **multiple of `top_k`** (must be `>= 1`), so each leg looks deeper than the final cut. | | `index_key` | `bytes` | - | *(Required, keyword-only)* 32-byte index KEK. See [Index key](#index-key). | | `user_id` | `bytes` | `None` | *(Optional, keyword-only)* 16-byte RBAC user identifier. See [Index key](#index-key). | > [!NOTE] > > If embedding auto-generation is enabled (by setting the `embedding_model` parameter in [`create_index()`](../client/create-index), then the `query_contents` parameter can be used instead of `query_vectors`. > [!NOTE] > > Hybrid queries **still require a query vector** — including at `alpha=0`, where it only fixes the batch shape. For text search with no vector at all, use [`query_metadata(text=...)`](./query-metadata). > [!TIP] > > `filters` use a subset of the [MongoDB Query and Projection Operators](https://www.mongodb.com/docs/manual/reference/operator/query/). > For instance: `filters: { "$and": [ { "label": "cat" }, { "confidence": { "$gte": 0.9 } } ] }` means that only vectors where `label == "cat"` and `confidence >= 0.9` will be considered for encrypted vector search. > For more info on metadata, see [Metadata Filtering](../../guides/data-operations/metadata-filtering). > [!NOTE] > > Hybrid queries narrow which filters are accepted. `$regex` on a non-`pattern` field, and any predicate on an explicitly non-`filterable` field, work in a pure `query()` but are rejected once `text` is set, because the text leg can only be filtered on fields resolvable from the encrypted metadata index. Move the filter to a `pattern` / `filterable` field or drop `text`. ### Returns `List[Dict[str, Union[int, float, Dict[]]]]`: List of results for the query vector. Each result is a list of `top_k` dictionaries, each containing `id` (always included), and optionally `distance` (pure vector query), `score` (hybrid query — fused BM25 + vector relevance, larger = more relevant), and `metadata` based on `include`. A hybrid result carries `score` in place of `distance` — never both, since a text-only match has no vector distance. When `include` is empty (the default), only `id` is returned. ### Exceptions > [accordion] ValueError > > * Throws if the query vector has incompatible dimensions with the index. > * Throws if the index was not created or loaded yet. > * Throws if `text` is passed but the index has no `full_text` field. > * Throws if `text_fields` names a field that is not `full_text`. > * Throws if any `text_*` knob is set without a non-empty `text`. > * Throws if `rrf_k <= 0` or `window_mult < 1` is passed explicitly (pass `None` for defaults). > * Throws if a filter references a field the index cannot resolve when `text` is set (e.g. `$regex` on a non-`pattern` field, or any predicate on an explicitly non-`filterable` field). > * Throws if the query could not be executed. > [accordion] EmbeddingModelUnavailable > > * Throws if `query_contents` needs embedding and the index's built-in model cannot be downloaded or loaded (offline cache miss, network failure). Often transient. ### Example Usage *Single Query with Distances*: ```python theme={null} # Load index index = client.load_index( index_name=index_name, index_key=index_key ) # Define a single query vector query_vectors = [0.1, 0.2, 0.3] # Single query vector of dimension 3 # Perform a single query with distances results = index.query( query_vectors=query_vectors, top_k=2, n_probes=5, include=["distance"], index_key=index_key ) # Example output: # [{"id": "101", "distance": 0.05}, {"id": "102", "distance": 0.1}] ``` *Hybrid Query (BM25 + Vector)*: Requires an index created with at least one `full_text` field (see [Full-text and hybrid search](../../guides/data-operations/bm25-search)). ```python theme={null} # text=... turns this into a hybrid query. A query vector is still required. results = index.query( query_vectors=[0.1, 0.2, 0.3], text="encrypted search", top_k=10, alpha=0.5, # 0 = pure BM25, 1 = pure vector; default 0.5 include=["metadata"], index_key=index_key, ) # Hybrid results carry `score` (fused relevance, higher = better) instead of `distance`. # Example output: # [{"id": "a1", "score": 0.0161, "metadata": {...}}, ...] ``` *Single Query without Distances*: ```python theme={null} results = index.query( query_vectors=query_vectors, top_k=10, n_probes=5, include=[], index_key=index_key ) # Example output: # [{"id": "101"}, {"id": "102"}] ``` *Single Query with Metadata*: ```python theme={null} results = index.query( query_vectors=query_vectors, top_k=10, n_probes=5, filters={"label": "dog"}, include=["metadata"], index_key=index_key ) # Example output: # [{"id": "101", "metadata": {"label": "dog", "temperament": "good boy"}}, # {"id": "102", "metadata": {"label": "dog", "temperament": "hyper"})]] ``` Results are plain dictionaries — access fields by string key (`r['id']`, `r['distance']`, `r['metadata']`): ```python theme={null} for r in results: print(r['id'], r['distance']) ``` ### Index key `index_key` is required on every call. Pass the same 32-byte index KEK you used with [`create_index()`](../client/create-index) / [`load_index()`](../client/load-index). For an [RBAC user](./manage-users), pass the user's KEK as `index_key=` together with their `user_id=`: ```python theme={null} results = index.query( query_vectors=[0.1, 0.2, 0.3], top_k=2, index_key=user_kek, user_id=user_id, ) ``` ## Batched Queries Retrieves the nearest neighbors for one or more query vectors. ```python theme={null} def query(self, query_vectors: Union[np.ndarray, List[List[float]]], query_contents: Union[str, List[str]] = None, top_k: int = None, n_probes: int = None, filters: Dict[str, Any] = None, include: List[str] = None, greedy: bool = False, rerank_mult: int = None, *, index_key: bytes, user_id: bytes = None) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `query_vectors` | `np.ndarray` or `List[List[float]]` | - | A 2D NumPy array or list of lists, where each inner list represents a query vector (for batch query). | | `query_contents` | `str` or `List[str]` | `None` | *(Optional)* Text content to auto-embed as query vectors (requires `embedding_model` set during index creation). A list is a batch. | | `top_k` | `int` | `None` | *(Optional)* Number of nearest neighbors to return. When `None`, defaults to 100. | | `n_probes` | `int` | `None` | *(Optional)* Number of lists probed during the query; higher values may increase recall but can also reduce performance. When `None` or `0`, automatically determines the optimal value. | | `filters` | `Dict[str, Any]` | `None` | *(Optional)* A dictionary of filters to apply to vector metadata, limiting search scope to these vectors. | | `include` | `List[str]` | `None` | *(Optional)* List of item fields to return. Can include `distance` and `metadata`. When empty, only IDs are returned. | | `greedy` | `bool` | `False` | *(Optional)* Whether to use greedy search (higher recall with same `n_probes`). | | `rerank_mult` | `int` | `50` | *(Optional)* Stage-1 retrieval multiplier for reranking. The index retrieves `rerank_mult * top_k` candidates before reranking them against the stored vectors to produce the final `top_k`. Higher values improve recall at some cost to performance. | | `index_key` | `bytes` | - | *(Required, keyword-only)* 32-byte index KEK. See [Index key](#index-key). | | `user_id` | `bytes` | `None` | *(Optional, keyword-only)* 16-byte RBAC user identifier. See [Index key](#index-key). | > [!TIP] > > `filters` use a subset of the [MongoDB Query and Projection Operators](https://www.mongodb.com/docs/manual/reference/operator/query/). > For instance: `filters: { "$and": [ { "label": "cat" }, { "confidence": { "$gte": 0.9 } } ] }` means that only vectors where `label == "cat"` and `confidence >= 0.9` will be considered for encrypted vector search. > For more info on metadata, see [Metadata Filtering](../../guides/data-operations/metadata-filtering). > [!NOTE] > > Batched queries accept the same BM25 keyword-only params as the single-query form (`text`, `text_fields`, `text_field_weights`, `require_all_terms`, `alpha`, `rrf_k`, `window_mult`); the same `text` value applies to every row in the batch. ### Returns `List[List[Dict[str, Union[int, float, Dict[]]]]]`: List of results for each query vector. Each result is a list of `top_k` dictionaries, each containing `id` (always included), and optionally `distance` (pure vector query), `score` (hybrid query), and `metadata` based on `include`. When `include` is empty (the default), only `id` is returned. ### Exceptions > [accordion] ValueError > > * Throws if the query vectors have incompatible dimensions with the index. > * Throws if the index was not created or loaded yet. > * Throws if the query could not be executed. ### Example Usage *Batch Query with Distances*: ```python theme={null} import numpy as np # Multiple query vectors query_vectors = np.array([ [0.1, 0.2, 0.3], [0.4, 0.5, 0.6] ]) # Query with distances included results = index.query(query_vectors=query_vectors, include=["distance"], index_key=index_key) # Example output: # [ # [{"id": "item_101", "distance": 0.05}, {"id": "item_202", "distance": 0.1}], # [{"id": "item_202", "distance": 0.2}, {"id": "item_303", "distance": 0.3}] # ] ``` *** ## NumPy Query A high-performance query variant that returns only integer IDs as a NumPy array. This is optimized for performance-critical workloads where metadata and distances are not needed. ```python theme={null} def query_numpy(self, query_vectors: np.ndarray, top_k: int = 100, n_probes: int = 0, greedy: bool = False, batch: bool = False, rerank_mult: int = 50, *, index_key: bytes, user_id: bytes = None) -> np.ndarray ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `query_vectors` | `np.ndarray` | - | Query vectors as a NumPy array. For a single query, a 1D array; for batch queries, a 2D array. | | `top_k` | `int` | `100` | *(Optional)* Number of nearest neighbors to return. | | `n_probes` | `int` | `0` (auto) | *(Optional)* Number of lists probed during the query. When set to `0`, automatically determines the optimal value. | | `greedy` | `bool` | `False` | *(Optional)* Whether to use greedy search (higher recall with same `n_probes`). | | `batch` | `bool` | `False` | *(Optional)* Whether to treat the input as a batch of query vectors. | | `rerank_mult` | `int` | `50` | *(Optional)* Stage-1 retrieval multiplier for reranking (retrieves `rerank_mult * top_k` candidates before reranking). | | `index_key` | `bytes` | - | *(Required, keyword-only)* 32-byte index KEK. See [Index key](#index-key). | | `user_id` | `bytes` | `None` | *(Optional, keyword-only)* 16-byte RBAC user identifier. | ### Returns `np.ndarray`: A NumPy array of integer IDs for the nearest neighbors. For a single query, returns a 1D array of shape `(top_k,)`. For batch queries, returns a 2D array of shape `(num_queries, top_k)`. Slots beyond the number of results found, and IDs that cannot be converted to integers, are set to `-1`. ### Exceptions > [accordion] ValueError > > * Throws if the query vectors have incompatible dimensions with the index. > * Throws if the index was not created or loaded yet. > * Throws if the query could not be executed. > [accordion] TypeError > > * Throws if the `query_vectors` format does not match the `batch` parameter. ### Example Usage ```python theme={null} import numpy as np # Single query query_vector = np.array([0.1, 0.2, 0.3], dtype=np.float32) ids = index.query_numpy(query_vectors=query_vector, top_k=10, index_key=index_key) # ids is a 1D np.ndarray of integer IDs, e.g. array([101, 102, 103, ...]) # Batch query query_vectors = np.array([ [0.1, 0.2, 0.3], [0.4, 0.5, 0.6] ], dtype=np.float32) ids = index.query_numpy(query_vectors=query_vectors, top_k=5, batch=True, index_key=index_key) # ids is a 2D np.ndarray of shape (2, 5) ``` > [!NOTE] > > `query_numpy` is a high-performance variant that returns only integer IDs. Use the standard `query()` method if you need distances, metadata, or string IDs. # Query Metadata Source: https://docs.cyborg.co/versions/latest/embedded/python/encrypted-index/query-metadata Runs a metadata-only query — no query vector required. `query_metadata()` evaluates a filter expression entirely against the encrypted metadata index and returns the matching items. Pass `text` to rank matches by BM25 full-text relevance instead (see [Full-text and hybrid search](../../guides/data-operations/bm25-search)). ```python theme={null} def query_metadata(self, filters: Dict[str, Any] = None, top_k: int = None, order_by: Union[str, Dict[str, int]] = None, ascending: bool = True, *, text: str = None, text_fields: List[str] = None, text_field_weights: List[float] = None, require_all_terms: bool = False, index_key: bytes, user_id: bytes = None) -> List[Dict[str, Any]] ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `filters` | `Dict[str, Any]` | `None` | *(Optional)* A dictionary of filters to apply to vector metadata, using a subset of the [MongoDB Query and Projection Operators](https://www.mongodb.com/docs/manual/reference/operator/query/). | | `top_k` | `int` | `None` | *(Optional)* Maximum number of matching IDs to return. When `None`, **all** matches are returned. Applied **after** sorting when `order_by` is set. | | `order_by` | `str` or `Dict[str, int]` | `None` | *(Optional)* Sort the matches by a metadata field before `top_k` is applied. Accepts a field name (direction controlled by `ascending`) or a MongoDB-style single-field dict, e.g. `{"views": -1}` for descending. | | `ascending` | `bool` | `True` | *(Optional)* Sort direction when `order_by` is a field name. Ignored when `order_by` is a dict (the dict's `1` / `-1` value controls direction). | | `text` | `str` | `None` | *(Optional, keyword-only)* Query text for BM25 full-text search over the index's `full_text` fields. When set, results are ranked by BM25 score and carry a `score`. Requires an index with at least one `full_text` field. Not supported together with `order_by`. | | `text_fields` | `List[str]` | `None` | *(Optional, keyword-only)* Which `full_text` fields to search. `None` = all designated fields. Naming a non-`full_text` field raises. | | `text_field_weights` | `List[float]` | `None` | *(Optional, keyword-only)* Per-field weights on the summed per-field BM25 scores, parallel to the searched fields. `None` = 1.0 each. | | `require_all_terms` | `bool` | `False` | *(Optional, keyword-only)* Require every query term to match (AND) instead of any (OR, the default). | | `index_key` | `bytes` | - | *(Required, keyword-only)* 32-byte index KEK. For an [RBAC user](./manage-users), pass the user's KEK together with `user_id=`. | | `user_id` | `bytes` | `None` | *(Optional, keyword-only)* 16-byte RBAC user identifier. | > [!NOTE] > > * Without `order_by` (and without `text`), the result is an **unordered** subset of matching items. > * Items missing the `order_by` field (or holding a non-scalar value) sort last. > * Metadata-only queries work on **untrained** indexes. > * `$type` is not supported on this endpoint. `$regex` / `$contains` require the field to have been declared `pattern: true` in the index's [`metadata_schema`](../client/create-index#metadata-schema); a field declared `filterable: false` cannot be filtered on here at all. Both raise `ValueError` — run the same filter through [`query()`](./query) with a vector if you need to bypass the schema constraint. Nested dot-paths (`owner.name`) are supported. ### Returns `List[Dict[str, Any]]`: One dictionary per matching item. Each carries `id` (`str`). When `text` is set, each also carries `score` (`float`, the BM25 score) and results are sorted by descending score; without `text`, there is no `score` key. ### Exceptions > [accordion] ValueError > > * Throws if `order_by` is a dict with more than one field. > * Throws if `order_by` is neither a field name (`str`) nor a single-field dict. > * Throws if `text` is passed but the index has no `full_text` field, or `text_fields` names a field that is not `full_text`. > * Throws if any `text_*` parameter is set without a non-empty `text`. > * Throws if the query could not be executed. ### Example Usage *Filter only (all matches, unordered)*: ```python theme={null} results = index.query_metadata(filters={"label": "dog"}, index_key=index_key) # Example output: # [{"id": "101"}, {"id": "102"}, {"id": "205"}] ``` *Filter with operators and a result cap*: ```python theme={null} results = index.query_metadata( filters={"$and": [{"label": "cat"}, {"confidence": {"$gte": 0.9}}]}, top_k=10, index_key=index_key, ) ``` *Sorted by a metadata field*: ```python theme={null} # Ascending by "views" (field name + ascending flag) results = index.query_metadata(filters={"label": "dog"}, order_by="views", index_key=index_key) # Descending by "views" (MongoDB-style dict); top_k applies after the sort results = index.query_metadata( filters={"label": "dog"}, order_by={"views": -1}, top_k=5, index_key=index_key, ) ``` *Full-text search (BM25)*: ```python theme={null} results = index.query_metadata( text="encrypted search", top_k=10, index_key=index_key, ) # Example output: # [{"id": "a1", "score": 3.42}, {"id": "b7", "score": 2.18}, ...] ``` For metadata syntax and supported operators, see [Metadata Filtering](../../guides/data-operations/metadata-filtering). # Train Index Source: https://docs.cyborg.co/versions/latest/embedded/python/encrypted-index/train Builds the index using the specified training configuration. Required before efficient querying. Prior to calling this, all queries will be conducted using encrypted exhaustive search. After, they will be conducted using encrypted ANN search. ```python theme={null} def train(self, n_lists: int = None, batch_size: int = None, max_iters: int = None, tolerance: float = None, max_memory: int = None, *, index_key: bytes, user_id: bytes = None) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `n_lists` | `int` | `None` | *(Optional)* Number of inverted index lists to create in the index. When `None`, auto-determines based on the number of vectors in the index (equivalent to `0`). | | `batch_size` | `int` | `None` | *(Optional)* Size of each batch for training. When `None`, defaults to `0` (auto — the optimal batch size is selected automatically). | | `max_iters` | `int` | `None` | *(Optional)* Maximum number of iterations for training. When `None`, defaults to `100`. | | `tolerance` | `float` | `None` | *(Optional)* Convergence tolerance for training. When `None`, defaults to `1e-6`. | | `max_memory` | `int` | `None` | *(Optional)* Maximum memory to use for training. When `None`, defaults to `0` (no limit). | | `index_key` | `bytes` | - | *(Required, keyword-only)* 32-byte index KEK. See [Index key](#index-key). | | `user_id` | `bytes` | `None` | *(Optional, keyword-only)* 16-byte RBAC user identifier. See [Index key](#index-key). | > [!TIP] > > Training needs at least `10,000` vectors in the index **and** at least `2 * n_lists` vectors. Below either threshold, `train()` does not raise: it logs a warning and leaves the index untrained. Check [`is_trained()`](../getters#is_trained) afterwards. ### Exceptions > [accordion] ValueError > > * Raises an exception if the index was not created or loaded yet. > * Raises an exception if the index could not be trained. ### Example Usage ```python theme={null} # Load index index = client.load_index( index_name=index_name, index_key=index_key ) # Train the index with custom settings index.train( batch_size=128, max_iters=10, tolerance=1e-4, index_key=index_key ) # Train with default settings (auto-selected configuration) index.train(index_key=index_key) ``` ### Index key `index_key` is required on every call. Pass the same 32-byte index KEK you used with [`create_index()`](../client/create-index) / [`load_index()`](../client/load-index). For an [RBAC user](./manage-users), pass the user's KEK as `index_key=` together with their `user_id=`: ```python theme={null} index.train(index_key=user_kek, user_id=user_id) ``` > [!NOTE] > > Training requires write permission. An [RBAC user](./manage-users) without a write wrap cannot train the index. # Upsert Source: https://docs.cyborg.co/versions/latest/embedded/python/encrypted-index/upsert Adds or updates vector embeddings in the index. Accepts a list of dictionaries, where each dictionary represents a vector with its ID. ```python theme={null} def upsert(self, items: List[Dict[str, Any]], *, index_key: bytes, user_id: bytes = None) ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `items` | `List[Dict[str, Any]]` | A list of dictionaries, where each dictionary has the format `{"id": str, "vector": List[float], "contents": Union[bytes, str], "metadata": Dict[str, Any]}`. | | `index_key` | `bytes` | *(Required, keyword-only)* 32-byte index KEK. See [Index key](#index-key). | | `user_id` | `bytes` | *(Optional, keyword-only)* 16-byte RBAC user identifier. See [Index key](#index-key). | Where each `item` dictionary has the following fields: | Parameter | Type | Description | | - | - | - | | `id` | `str` | Unique string identifier for the item. | | `vector` | `List[float]` | Embedding vector as a list of floats (*optional* if index is configured to compute embeddings). | | `contents` | `bytes` or `str` | Item contents (*optional*). Accepts strings or bytes; all are encoded to bytes and encrypted before storage. Must be a `str` if index is configured to compute embeddings. | | `metadata` | `Dict[str, any]` | Dictionary of key-value metadata pairs associated with the vector (*optional*). | > [!TIP] > > The `contents` field accepts strings or bytes. All contents are encoded to bytes and encrypted before storage, and will be returned as bytes when retrieved with `get()`. > [!NOTE] > > If embedding auto-generation is enabled (by setting the `embedding_model` parameter in [`create_index()`](../client/create-index)), then the `vector` parameter is optional. > If `vector` provided, then it will be used (its dimensionality must match that of the `embedding_model`). > If `vector` is not provided, a vector embedding is generated in-process from `contents` using the index's built-in model — no `sentence-transformers` or `torch` install required. `contents` must be a `str` in this case. > [!TIP] > > For more info on metadata, see [Metadata Filtering](../../guides/data-operations/metadata-filtering). ### Exceptions > [accordion] ValueError > > * Throws if the vector dimensions are incompatible with the index configuration. > * Throws if the index was not created or loaded yet. > * Throws if the vectors could not be upserted. > [accordion] EmbeddingModelUnavailable > > * Throws if `contents` need embedding and the index's built-in model cannot be downloaded or loaded (offline cache miss, network failure). Often transient. > [accordion] TypeError > > * Throws if the arguments do not match the expected types. ### Example Usage ```python theme={null} # Initial configuration already done... # Load Index index = client.load_index( index_name=index_name, index_key=index_key ) # Single upsert (wrapped in a list) index.upsert([{"id": "item_1", "vector": [0.1, 0.2, 0.3]}], index_key=index_key) # Upsert with metadata index.upsert([ {"id": "item_1", "vector": [0.1, 0.2, 0.3], "metadata": {"type": "dog", "temperament": "good boy"} } ], index_key=index_key) # Batch upsert index.upsert([ {"id": "item_1", "vector": [0.1, 0.2, 0.3]}, {"id": "item_2", "vector": [0.4, 0.5, 0.6]} ], index_key=index_key) # Upsert with items index.upsert([ {"id": "item_1", "vector": [0.1, 0.1, 0.1, 0.1], "contents": b'item_contents_here...'}, # Bytes {"id": "item_2", "vector": [0.2, 0.2, 0.2, 0.2], "contents": "item_contents_here..."} # Text ], index_key=index_key) ``` ### Index key `index_key` is required on every call. Pass the same 32-byte index KEK you used with [`create_index()`](../client/create-index) / [`load_index()`](../client/load-index). For an [RBAC user](./manage-users), pass the user's KEK as `index_key=` together with their `user_id=`: ```python theme={null} index.upsert( [{"id": "item_1", "vector": [0.1, 0.2, 0.3]}], index_key=user_kek, user_id=user_id, ) ``` *** ## Upsert Secondary Overload: NumPy Array Format > [!TIP] > > This format is optimal for large batches due to its memory efficiency and compatibility with batch processing optimizations. > It is primarily intended for benchmarking purposes (hence the use of `int` for IDs). ```python theme={null} def upsert(self, ids: Union[list[str], np.ndarray], vectors: np.ndarray, *, index_key: bytes, user_id: bytes = None) ``` Accepts a list of string IDs (or a NumPy array) and a NumPy array of vectors: * A list of strings or 1D array of identifiers for the unique IDs. * A 2D array of float32 values for the vector embeddings. This structure is suited for efficient handling of large batches, with type safety for IDs and embeddings. ### Parameters | Parameter | Type | Description | | - | - | - | | `ids` | `list[str]` or `np.ndarray` | A list of strings or 1D NumPy array of shape `(num_items,)` containing unique identifiers for each vector. Can be string or integer dtype. Length must match `vectors`. | | `vectors` | `np.ndarray` | 2D NumPy array of shape `(num_items, vector_dim)` with `dtype=float32`, representing vector embeddings. | ### Exceptions > [accordion] ValueError > > * Throws if the vector dimensions are incompatible with the index configuration. > * Throws if the index was not created or loaded yet. > * Throws if the vectors could not be upserted. > [accordion] TypeError > > * Throws if the arguments do not match the expected types. ### Example Usage ```python theme={null} import numpy as np # Load index index = client.load_index(index_name=index_name, index_key=index_key) # NumPy-based upsert with two arrays vectors = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], dtype=np.float32) # 2 vectors of dimension 3 ids = np.array(["item_101", "item_102"]) # Unique string IDs for each vector index.upsert(ids, vectors, index_key=index_key) ``` # Getter Functions Source: https://docs.cyborg.co/versions/latest/embedded/python/getters ## is_trained Returns `True` only when training is **complete**, enabling efficient approximate nearest neighbor search. An untrained index defaults to exhaustive search. ```python theme={null} def is_trained(self) -> bool: ... ``` ### Returns `bool`: `True` only when the index is fully trained; otherwise, `False`. > [!NOTE] > > `is_trained()` returns `False` while a (re)train rebuild is in progress. During that window, queries transparently fall back to the untrained (exhaustive) search path. To distinguish "untrained" from "currently (re)training", use [`is_training()`](#is_training) or [`training_state()`](#training_state). ### Example Usage ```python theme={null} # Check if index is trained if index.is_trained(): print("The index is ready for efficient querying.") else: print("The index is not trained; consider calling train().") ``` *** ## is_training Returns `True` while a (re)train rebuild is in progress. While this is `True`, [`is_trained()`](#is_trained) returns `False` and queries fall back to exhaustive search. ```python theme={null} def is_training(self) -> bool: ... ``` ### Returns `bool`: `True` if a training rebuild is currently running; otherwise, `False`. ### Example Usage ```python theme={null} if index.is_training(): print("A training rebuild is in progress; queries use exhaustive search for now.") ``` *** ## training_state Returns the current training state of the index as a string. ```python theme={null} def training_state(self) -> str: ... ``` ### Returns `str`: One of `"untrained"`, `"training"`, or `"trained"`. ### Example Usage ```python theme={null} state = index.training_state() print(f"Training state: {state}") # "untrained" | "training" | "trained" ``` *** ## index_name Retrieves the name of the current index. ```python theme={null} def index_name(self) -> str: ... ``` ### Returns `str`: Name of the currently loaded or created index. ### Example Usage ```python theme={null} # Retrieve the index name print("Current index name:", index.index_name()) ``` *** ## index_type Returns the type of the current index. CyborgDB uses a single IVF index type, so this returns `"disk_ivf"`. ```python theme={null} def index_type(self) -> str: ... ``` ### Returns | Return Type | Description | | - | - | | `str` | Type of the current index (`"disk_ivf"`). | ### Example Usage ```python theme={null} # Retrieve the type of index print("Index type:", index.index_type()) ``` *** ## index_config Retrieves the configuration details of the current index. ```python theme={null} def index_config(self) -> dict: ... ``` ### Returns `dict`: A dictionary containing the configuration of the index with the following keys: * `dimension`: The dimensionality of the vectors * `metric`: The distance metric used (e.g., `'euclidean'`, `'cosine'`) * `index_type`: The type of the index (`'disk_ivf'`) * `n_lists`: The number of inverted lists in the index * `embedding_model`: The configured embedding-model name, or `""` if none * `metadata_schema`: Per-field metadata indexing overrides as a flat map `{field: {'filterable': bool, 'pattern': bool, 'full_text': bool}}`; empty when using the default index-everything posture * `bm25`: `{'k1': float, 'b': float, 'analyzer_version': str}` when the index has at least one `full_text` field, else `None` ### Example Usage ```python theme={null} # Retrieve index config config = index.index_config() print(f"Dimension: {config['dimension']}") print(f"Metric: {config['metric']}") print(f"Index type: {config['index_type']}") ``` *** ## n_lists Returns the number of inverted lists in the index. This property is set during training and initially defaults to 1. ```python theme={null} @property def n_lists(self) -> int: ... ``` ### Returns `int`: The number of inverted lists in the index. ### Example Usage ```python theme={null} # Access the n_lists property num_lists = index.n_lists print(f"Index has {num_lists} inverted lists") ``` *** ## dimension Returns the dimensionality of the vectors in the index. ```python theme={null} @property def dimension(self) -> int: ... ``` ### Returns `int`: The dimensionality of the vectors. ### Example Usage ```python theme={null} # Access the dimension property vector_dim = index.dimension print(f"Vector dimension: {vector_dim}") ``` *** ## metric Returns the distance metric used by the index. ```python theme={null} @property def metric(self) -> str: ... ``` ### Returns `str`: The distance metric used (e.g., `"euclidean"`, `"cosine"`, `"squared_euclidean"`). ### Example Usage ```python theme={null} # Access the metric property dist_metric = index.metric print(f"Distance metric: {dist_metric}") ``` *** ## get_num_vectors Returns the number of vectors currently stored in the index. ```python theme={null} def get_num_vectors(self, *, index_key: bytes, user_id: bytes = None) -> int: ... ``` ### Returns `int`: The number of vectors in the index. > [!NOTE] > > `index_key=` is required. For an [RBAC user](./encrypted-index/manage-users), pass the user's KEK as `index_key=` together with their `user_id=`. ### Example Usage ```python theme={null} # Get the number of vectors in the index num_vectors = index.get_num_vectors(index_key=index_key) print(f"The index contains {num_vectors} vectors.") ``` *** ## list_ids Lists all item IDs currently stored in the index. ```python theme={null} def list_ids(self, *, index_key: bytes, user_id: bytes = None) -> List[str]: ... ``` ### Returns `List[str]`: A list containing all item IDs in the index. > [!NOTE] > > `index_key=` is required. For an [RBAC user](./encrypted-index/manage-users), pass the user's KEK as `index_key=` together with their `user_id=`. ### Exceptions > [accordion] ValueError > > * Throws if the index was not created or loaded yet. > * Throws if an error occurs during retrieval. ### Example Usage ```python theme={null} # List all IDs in the index all_ids = index.list_ids(index_key=index_key) print(f"Total items in index: {len(all_ids)}") # Print first 10 IDs for id in all_ids[:10]: print(f"ID: {id}") ``` # CyborgDB Embedded - Python API Reference Source: https://docs.cyborg.co/versions/latest/embedded/python/introduction `v0.18.x` The Python API for CyborgDB is split into two main classes within the `cyborgdb_core` module: * `Client` – Handles configuration, index creation/loading, and listing available indexes. * `EncryptedIndex` – Provides data operations on a specific encrypted index such as upserting vectors, training the index, querying, and retrieving stored items. ## Module-level helpers Two module-level helpers report on CUDA/GPU support in the current build and environment: ```python theme={null} def cuda_available() -> bool # True if a usable CUDA device is present at runtime def cuda_built() -> bool # True if this build of cyborgdb_core was compiled with CUDA support ``` ```python theme={null} import cyborgdb_core as cyborgdb if cyborgdb.cuda_built() and cyborgdb.cuda_available(): print("GPU acceleration is available.") ``` The module also exports: * Types: [`StorageConfig`](./types#storageconfig), [`S3Credentials`](./types#s3credentials), [`GPUConfig`](./types#gpuconfig), [`StoragePrecision`](./types#storageprecision), [`KMSBlob`](./types#kmsblob), [`Logger`](./client/logger), `MetadataResult` (the row type returned by [`query_metadata()`](./encrypted-index/query-metadata)). * KMS functions: [`create_index_kms`, `push_index_kms`, `get_index_kms`, `delete_index_kms`](./kms). * Embedding helpers: `supported_embedding_models()`, `find_embedding_model(name)`, the `EmbeddingModel` class (`embed_documents()` / `embed_queries()`), and the `EmbeddingModelUnavailable` exception (a `RuntimeError` subclass). * Datetime helpers: `to_epoch_millis(value)` and `from_epoch_millis(millis)`. Metadata has no native datetime type; `datetime` / `date` values are stored as epoch milliseconds. * `__version__`. # KMS Key Management Source: https://docs.cyborg.co/versions/latest/embedded/python/kms CyborgDB can persist a per-index **KMS envelope** — a small record describing how an index's KEK is wrapped by an external Key Management Service. AES-256-GCM wraps the 32-byte KEK. These module-level functions read and write that envelope; the envelope itself is represented by the [`KMSBlob`](./types#kmsblob) type and stored alongside the index. > [!NOTE] > > KMS is an **advanced / optional** feature primarily for the service layer. Embedded SDK users who supply their own KEK can ignore it entirely, or use `provider="none"` (the SDK supplies the plaintext KEK per request and nothing key-derived is stored). > [!NOTE] > > **Envelope model.** Each index is encrypted with AES-256-GCM under a 32-byte KEK. The KMS envelope records how that KEK is wrapped by an external KMS so a service layer can unwrap it at request time. Supported providers: > > * `"aws"` — the KEK is wrapped with AES-256-GCM under a value stored in AWS Secrets Manager. > * `"aws-kms"` — the KEK is wrapped via `kms.Encrypt` using an AWS KMS key. > * `"none"` — no external wrapping; the caller supplies the plaintext KEK per request and nothing is stored. > > Customer-managed keys (CMK) are supported via `"aws-kms"`, not yet for the other providers. > > By default the plaintext KEK lives in caller process memory; the wrapped KEK lives next to the index keystore ([`StorageConfig`](./types#storageconfig)). All functions take a `config_location` ([`StorageConfig`](./types#storageconfig)) identifying where the index keystore lives, plus the index name. *** ## create_index_kms Creates a KMS envelope for an index. **Strict insert** — fails if an envelope already exists for `index_name`. ```python theme={null} def create_index_kms(config_location: StorageConfig, index_name: str, blob: KMSBlob) ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `config_location` | [`StorageConfig`](./types#storageconfig) | Backing store where the index keystore lives. | | `index_name` | `str` | Name of the index the envelope belongs to. | | `blob` | [`KMSBlob`](./types#kmsblob) | The KMS envelope to store. | ### Example Usage ```python theme={null} import cyborgdb_core as cyborgdb config = cyborgdb.StorageConfig.disk("/tmp/cyborgdb") blob = cyborgdb.KMSBlob( kms_name="prod-kms", provider="aws-kms", key_id="arn:aws:kms:us-east-1:123456789012:key/abcd-...", region="us-east-1", wrapped_kek=b"...", # KEK wrapped by the external KMS version=1, ) cyborgdb.create_index_kms(config, "my_index", blob) ``` *** ## push_index_kms Stores a KMS envelope for an index. **Idempotent upsert** — creates the envelope if missing, otherwise overwrites it. ```python theme={null} def push_index_kms(config_location: StorageConfig, index_name: str, blob: KMSBlob) ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `config_location` | [`StorageConfig`](./types#storageconfig) | Backing store where the index keystore lives. | | `index_name` | `str` | Name of the index the envelope belongs to. | | `blob` | [`KMSBlob`](./types#kmsblob) | The KMS envelope to store (replaces any existing one). | ### Example Usage ```python theme={null} # Rotate the wrapped KEK without caring whether an envelope already exists blob.wrapped_kek = b"...new wrapped kek..." blob.version = 2 cyborgdb.push_index_kms(config, "my_index", blob) ``` *** ## get_index_kms Retrieves the KMS envelope for an index. ```python theme={null} def get_index_kms(config_location: StorageConfig, index_name: str) -> KMSBlob ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `config_location` | [`StorageConfig`](./types#storageconfig) | Backing store where the index keystore lives. | | `index_name` | `str` | Name of the index the envelope belongs to. | ### Returns [`KMSBlob`](./types#kmsblob): The stored KMS envelope for the index. ### Example Usage ```python theme={null} blob = cyborgdb.get_index_kms(config, "my_index") print(blob.provider, blob.key_id, blob.version) ``` *** ## delete_index_kms Deletes the KMS envelope for an index. **Idempotent** — deleting a non-existent envelope is a no-op. ```python theme={null} def delete_index_kms(config_location: StorageConfig, index_name: str) ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `config_location` | [`StorageConfig`](./types#storageconfig) | Backing store where the index keystore lives. | | `index_name` | `str` | Name of the index the envelope belongs to. | ### Example Usage ```python theme={null} cyborgdb.delete_index_kms(config, "my_index") ``` *** ## Rotation To rotate the wrapped KEK, re-wrap it with your external KMS and store the new envelope with [`push_index_kms`](#push_index_kms) (an idempotent upsert), bumping `version`: ```python theme={null} blob = cyborgdb.get_index_kms(config, "my_index") blob.wrapped_kek = b"...newly wrapped kek..." blob.version += 1 cyborgdb.push_index_kms(config, "my_index", blob) ``` For end-to-end key-rotation guidance, see the [CyborgDB documentation](https://docs.cyborg.co). # Types Source: https://docs.cyborg.co/versions/latest/embedded/python/types ## StorageConfig The `StorageConfig` class specifies the backing store for an index's keystores. It is immutable and is built via static factory methods. A single `StorageConfig` is shared across all per-index keystores and is passed to the [`Client`](./client/client) constructor. CyborgDB supports two backing stores: **disk** and **s3**. ### Factories ```text theme={null} StorageConfig.disk(path: str, *, cache_vectors: bool = False, cache_metadata: bool = False, cache_ids: bool = False, cache_metadata_index: bool = False) # Local persistent storage on disk. StorageConfig.s3(bucket: str, *, region: str | None = None, endpoint: str | None = None, prefix: str = "", credentials: S3Credentials | None = None) # AWS S3 / S3-compatible (MinIO, Ceph, R2, etc.). ``` | Factory | Description | | - | - | | `disk(path, ...)` | Local persistent store on disk. Optional `cache_*` flags keep vectors / metadata / IDs / the metadata index in memory for faster reads. | | `s3(bucket, ...)` | S3 or S3-compatible object store. Set `endpoint` for non-AWS providers (path-style addressing is auto-selected). Omit `credentials` to use the AWS default credential provider chain. | ### Properties (Read-Only) | Property | Type | Description | | - | - | - | | `cache_vectors` | `bool` | Whether the vectors store is served from the in-RAM cache. | | `cache_metadata` | `bool` | Whether the metadata store is served from the in-RAM cache. | | `cache_ids` | `bool` | Whether the ids store is served from the in-RAM cache. | | `cache_metadata_index` | `bool` | Whether the encrypted metadata index store is served from the in-RAM cache. | ### Example Usage ```python theme={null} import cyborgdb_core as cyborgdb # Local disk, caching vectors in memory disk_store = cyborgdb.StorageConfig.disk("/tmp/cyborgdb", cache_vectors=True) # AWS S3 with explicit credentials s3_store = cyborgdb.StorageConfig.s3( "my-bucket", region="us-east-1", credentials=cyborgdb.S3Credentials(access_key="...", secret_key="..."), ) # S3-compatible (e.g. MinIO) with default credential chain minio_store = cyborgdb.StorageConfig.s3( "my-bucket", endpoint="http://localhost:9000", ) ``` For more info, you can read about supported backing stores [here](../../intro/backing-stores). *** ## S3Credentials Explicit credentials for the `StorageConfig.s3(...)` factory. Omit `credentials=` on `.s3()` to use the AWS default credential provider chain (environment variables, `~/.aws/credentials`, EC2 instance profile, EKS IRSA). ```text theme={null} S3Credentials(access_key: str, secret_key: str, session_token: str | None = None) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `access_key` | `str` | - | S3 access key ID. | | `secret_key` | `str` | - | S3 secret access key. | | `session_token` | `str` \| `None` | `None` | *(Optional)* Temporary session token (for STS / assumed roles). | ### Example Usage ```python theme={null} import cyborgdb_core as cyborgdb creds = cyborgdb.S3Credentials(access_key="AKIA...", secret_key="...") store = cyborgdb.StorageConfig.s3("my-bucket", region="us-east-1", credentials=creds) ``` *** ## GPUConfig The `GPUConfig` class configures which operations should use GPU acceleration. GPU acceleration requires CUDA support. ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `upsert` | `bool` | `False` | *(Optional)* Enable GPU for upsert operations | | `train` | `bool` | `False` | *(Optional)* Enable GPU for training operations | ### Properties (Read-Only) | Property | Type | Description | | - | - | - | | `upsert` | `bool` | Whether GPU is enabled for upsert operations | | `train` | `bool` | Whether GPU is enabled for training operations | | `query` | `bool` | Whether GPU is enabled for query operations | | `all` | `bool` | Whether all GPU operations are enabled | | `none` | `bool` | Whether no GPU operations are enabled | ### Example Usage ```python theme={null} import cyborgdb_core as cyborgdb # Enable GPU for upsert and training gpu_config1 = cyborgdb.GPUConfig(upsert=True, train=True) # Enable GPU only for training gpu_config2 = cyborgdb.GPUConfig(train=True) # Disable GPU (default) gpu_config3 = cyborgdb.GPUConfig() # Check GPU configuration if gpu_config1.all: print("All GPU operations enabled") if gpu_config2.train: print("GPU enabled for training") ``` *** ## DistanceMetric `DistanceMetric` is a string representing the distance metric used for the index. Options include: * `"cosine"`: Cosine similarity. * `"euclidean"`: Euclidean distance. * `"squared_euclidean"`: Squared Euclidean distance. *** ## StoragePrecision `StoragePrecision` is a `str` enum naming the on-disk rerank-vector format, chosen at create time and immutable. Each member's value is its lowercase string, so the raw strings (and `np.float32` / `np.float16`) are also accepted wherever `storage_precision` is. ```python theme={null} class StoragePrecision(str, Enum): FLOAT32 = "float32" FLOAT16 = "float16" TQ12 = "tq12" TQ8 = "tq8" TQ6 = "tq6" TQ4 = "tq4" ``` *** ## KMSBlob `KMSBlob` describes a per-index envelope recording how the index KEK is wrapped by an external KMS. It is used with the module-level KMS functions (`create_index_kms`, `push_index_kms`, `get_index_kms`, `delete_index_kms`). This is an advanced, optional surface primarily for the service layer; embedded SDK users supplying their own KEK can ignore it or use `provider="none"`. ```text theme={null} KMSBlob(kms_name: str = "", provider: str = "", key_id: str = "", region: str = "", wrapped_kek: bytes = b"", version: int = 1, created_at: int = 0) ``` ### Fields | Field | Type | Description | | - | - | - | | `kms_name` | `str` | Human-readable name of the KMS configuration. | | `provider` | `str` | KMS provider: `"aws"`, `"aws-kms"`, or `"none"`. | | `key_id` | `str` | Identifier of the wrapping key within the KMS. | | `region` | `str` | Region of the KMS / key. | | `wrapped_kek` | `bytes` | The wrapped index KEK. | | `version` | `int` | Envelope version. | | `created_at` | `int` | Creation timestamp (unix epoch seconds). | ### Example Usage ```python theme={null} import cyborgdb_core as cyborgdb blob = cyborgdb.KMSBlob( kms_name="prod", provider="aws-kms", key_id="arn:aws:kms:us-east-1:111122223333:key/abcd", region="us-east-1", wrapped_kek=wrapped_bytes, ) ``` # CyborgDB Integrations Source: https://docs.cyborg.co/versions/latest/integrations/about CyborgDB seamlessly integrates with popular AI and machine learning frameworks, enabling you to leverage confidential vector search within your existing workflows. These integrations provide native support for CyborgDB's encrypted vector operations while maintaining compatibility with familiar APIs and patterns. ## Available Integrations ### 🦜🔗 LangChain The LangChain integration provides a `CyborgVectorStore` class that implements the standard VectorStore interface, enabling confidential vector search for RAG pipelines and LLM applications. This integration is available for `cyborgdb-core` (Embedded), `cyborgdb` (Python SDK), and `cyborgdb` (JS/TS SDK), and includes: * Full VectorStore API compatibility (add_texts, similarity_search, etc.) * Async operations support * Configurable distance metrics (cosine, euclidean, squared_euclidean) * Document ID tracking and management * Max marginal relevance search (Embedded and JS/TS) > [!TIP] > > See the [LangChain Integration Guide](./langchain/introduction) for detailed usage instructions. ## Getting Started Each integration includes detailed installation instructions and usage examples. Choose the integration that matches your current tech stack to get started with confidential vector search in minutes. For deployment-specific guidance, see our [Deployment Models Guide](../intro/deployment-models) to understand the differences between `cyborgdb` and `cyborgdb-core`. # add_documents Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/add_documents Adds LangChain Document objects to the vector store. > [tab] Embedded > > ```python theme={null} > add_documents( > documents: List[Document], > ids: Optional[List[str]] = None, > **kwargs > ) -> List[str] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `documents` | `List[Document]` | List of LangChain Document objects to add | > | `ids` | `Optional[List[str]]` | *(Optional)* List of IDs for the documents (auto-generated if not provided) | > | `**kwargs` | `Any` | Additional keyword arguments passed to add_texts | > > ### Returns > > `List[str]`: List of IDs for the added documents > > ### Example Usage > > ```python theme={null} > from langchain_core.documents import Document > > # Create documents with metadata > documents = [ > Document( > page_content="Introduction to machine learning", > metadata={"chapter": 1, "topic": "ML basics"} > ), > Document( > page_content="Deep learning fundamentals", > metadata={"chapter": 2, "topic": "Neural networks"} > ) > ] > > # Add documents to the store > ids = store.add_documents(documents) > print(f"Added {len(ids)} documents") > ``` > [tab] Python SDK > > ```python theme={null} > add_documents( > documents: List[Document], > ids: Optional[List[str]] = None, > **kwargs > ) -> List[str] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `documents` | `List[Document]` | List of LangChain Document objects to add | > | `ids` | `Optional[List[str]]` | *(Optional)* List of IDs for the documents (auto-generated if not provided) | > | `**kwargs` | `Any` | Additional keyword arguments passed to add_texts | > > ### Returns > > `List[str]`: List of IDs for the added documents > > ### Example Usage > > ```python theme={null} > from langchain_core.documents import Document > > documents = [ > Document( > page_content="Introduction to machine learning", > metadata={"chapter": 1, "topic": "ML basics"} > ), > Document( > page_content="Deep learning fundamentals", > metadata={"chapter": 2, "topic": "Neural networks"} > ) > ] > > ids = store.add_documents(documents) > ``` > [tab] JS/TS > > ```typescript theme={null} > addDocuments( > documents: Document[], > options?: { ids?: string[] } > ): Promise > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `documents` | `Document[]` | Array of LangChain Document objects to add | > | `options` | `object` | *(Optional)* Options object with optional `ids` array | > > ### Returns > > `Promise`: Array of IDs for the added documents > > ### Example Usage > > ```typescript theme={null} > import { Document } from '@langchain/core/documents'; > > const documents = [ > new Document({ > pageContent: "Introduction to machine learning", > metadata: { chapter: 1, topic: "ML basics" } > }), > new Document({ > pageContent: "Deep learning fundamentals", > metadata: { chapter: 2, topic: "Neural networks" } > }) > ]; > > const ids = await store.addDocuments(documents); > ``` ### Async > [accordion] Python async variants > > The Embedded and Python SDK provide async versions of this method prefixed with `a`: > > ```python theme={null} > # aadd_documents — async variant > ids = await store.aadd_documents(documents) > ``` > [!NOTE] > > JS/TS methods are natively async — all signatures above already return `Promise<...>`. No separate async variant is needed. # add_texts Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/add_texts Adds text documents to the vector store with optional metadata. > [tab] Embedded > > ```python theme={null} > add_texts( > texts: Iterable[str], > metadatas: Optional[List[dict]] = None, > *, > ids: Optional[List[str]] = None, > **kwargs: Any > ) -> List[str] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `texts` | `Iterable[str]` | Iterable of text strings to add | > | `metadatas` | `Optional[List[dict]]` | *(Optional)* List of metadata dictionaries for each text | > | `ids` | `Optional[List[str]]` | *(Optional)* List of IDs for the texts (auto-generated if not provided) | > | `**kwargs` | `Any` | Additional keyword arguments (currently unused) | > > ### Returns > > `List[str]`: List of IDs for the added texts > > ### Example Usage > > ```python theme={null} > # Add texts with auto-generated IDs > texts = ["Document about AI", "Document about ML", "Document about NLP"] > ids = store.add_texts(texts) > print(f"Added {len(ids)} documents") > > # Add texts with metadata and custom IDs > texts = ["Python tutorial", "JavaScript guide"] > metadatas = [ > {"language": "python", "level": "beginner"}, > {"language": "javascript", "level": "intermediate"} > ] > custom_ids = ["doc1", "doc2"] > ids = store.add_texts(texts, metadatas=metadatas, ids=custom_ids) > ``` > [tab] Python SDK > > ```python theme={null} > add_texts( > texts: Iterable[str], > metadatas: Optional[List[dict]] = None, > *, > ids: Optional[List[str]] = None, > **kwargs: Any > ) -> List[str] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `texts` | `Iterable[str]` | Iterable of text strings to add | > | `metadatas` | `Optional[List[dict]]` | *(Optional)* List of metadata dictionaries for each text | > | `ids` | `Optional[List[str]]` | *(Optional)* List of IDs for the texts (auto-generated if not provided) | > | `**kwargs` | `Any` | Additional keyword arguments | > > ### Returns > > `List[str]`: List of IDs for the added texts > > > [!NOTE] > > > > The Python SDK supports passing pre-computed embeddings via `kwargs` for cases where you want to skip the embedding step. > > ### Example Usage > > ```python theme={null} > texts = ["Document about AI", "Document about ML"] > metadatas = [{"topic": "ai"}, {"topic": "ml"}] > ids = store.add_texts(texts, metadatas=metadatas) > ``` > [tab] JS/TS > > ```typescript theme={null} > addTexts( > texts: string[], > metadatas?: Record[], > options?: { ids?: string[] } > ): Promise > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `texts` | `string[]` | Array of text strings to add | > | `metadatas` | `Record[]` | *(Optional)* Array of metadata objects for each text | > | `options` | `object` | *(Optional)* Options object with optional `ids` array | > > ### Returns > > `Promise`: Array of IDs for the added texts > > > [!NOTE] > > > > The JS/TS SDK also provides `addVectors()` for adding pre-computed embedding vectors directly, bypassing the embedding step. > > ### Example Usage > > ```typescript theme={null} > const texts = ["Document about AI", "Document about ML"]; > const metadatas = [{ topic: "ai" }, { topic: "ml" }]; > const ids = await store.addTexts(texts, metadatas); > ``` ### Exceptions > [accordion] ValueError > > * Throws if length of ids doesn't match length of texts ### Async > [accordion] Python async variants > > The Embedded and Python SDK provide async versions of this method prefixed with `a`: > > ```python theme={null} > # aadd_texts — async variant > ids = await store.aadd_texts(texts, metadatas=metadatas) > ``` > [!NOTE] > > JS/TS methods are natively async — all signatures above already return `Promise<...>`. No separate async variant is needed. # as_retriever Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/as_retriever Returns a LangChain `VectorStoreRetriever` for use in chains and agents. > [tab] Embedded > > ```python theme={null} > as_retriever(**kwargs) -> VectorStoreRetriever > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `**kwargs` | `Any` | Arguments passed to `VectorStoreRetriever` (e.g., `search_type`, `search_kwargs`) | > > ### Returns > > `VectorStoreRetriever`: A retriever backed by this vector store > > ### Example Usage > > ```python theme={null} > from langchain.chains import RetrievalQA > from langchain_openai import ChatOpenAI > > # Create a retriever from the vector store > retriever = store.as_retriever( > search_type="similarity", > search_kwargs={"k": 5} > ) > > # Use in a RetrievalQA chain > qa_chain = RetrievalQA.from_chain_type( > llm=ChatOpenAI(), > retriever=retriever > ) > > answer = qa_chain.invoke("What is machine learning?") > > # MMR retriever for diverse results > mmr_retriever = store.as_retriever( > search_type="mmr", > search_kwargs={"k": 5, "fetch_k": 20, "lambda_mult": 0.5} > ) > ``` > [tab] Python SDK > > ```python theme={null} > as_retriever(**kwargs) -> VectorStoreRetriever > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `**kwargs` | `Any` | Arguments passed to `VectorStoreRetriever` (e.g., `search_type`, `search_kwargs`) | > > ### Returns > > `VectorStoreRetriever`: A retriever backed by this vector store > > ### Example Usage > > ```python theme={null} > from langchain.chains import RetrievalQA > from langchain_openai import ChatOpenAI > > retriever = store.as_retriever( > search_type="similarity", > search_kwargs={"k": 5} > ) > > qa_chain = RetrievalQA.from_chain_type( > llm=ChatOpenAI(), > retriever=retriever > ) > > answer = qa_chain.invoke("What is machine learning?") > ``` > [tab] JS/TS > > ```typescript theme={null} > asRetriever(options?: VectorStoreRetrieverInput): VectorStoreRetriever > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `options` | `VectorStoreRetrieverInput` | *(Optional)* Retriever configuration options (e.g., `k`, `searchType`, `filter`) | > > ### Returns > > `VectorStoreRetriever`: A retriever backed by this vector store > > > [!NOTE] > > > > The JS/TS `asRetriever()` is inherited from the LangChain base `VectorStore` class. There is no CyborgDB-specific override — it uses the standard LangChain retriever behavior. > > ### Example Usage > > ```typescript theme={null} > import { ChatOpenAI } from '@langchain/openai'; > import { RetrievalQAChain } from 'langchain/chains'; > > const retriever = store.asRetriever({ k: 5 }); > > const chain = RetrievalQAChain.fromLLM( > new ChatOpenAI(), > retriever > ); > > const result = await chain.invoke({ > query: "What is machine learning?" > }); > ``` # delete Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/delete Deletes documents from the vector store or deletes the entire index. > [tab] Embedded > > ```python theme={null} > delete( > ids: Optional[List[str]] = None, > delete_index: bool = False > ) -> bool > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `ids` | `Optional[List[str]]` | *(Optional)* List of document IDs to delete | > | `delete_index` | `bool` | If True, deletes the entire index regardless of `ids` (default: False) | > > ### Returns > > `bool`: True if deletion was successful, False otherwise > > ### Example Usage > > ```python theme={null} > # Delete specific documents > doc_ids = ["doc1", "doc2", "doc3"] > success = store.delete(ids=doc_ids) > if success: > print("Documents deleted successfully") > > # Delete the entire index > success = store.delete(delete_index=True) > if success: > print("Index deleted successfully") > ``` > [tab] Python SDK > > ```python theme={null} > delete( > ids: Optional[List[str]] = None, > delete_index: bool = False > ) -> bool > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `ids` | `Optional[List[str]]` | *(Optional)* List of document IDs to delete | > | `delete_index` | `bool` | If True, deletes the entire index regardless of `ids` (default: False) | > > ### Returns > > `bool`: True if deletion was successful, False otherwise > > ### Example Usage > > ```python theme={null} > # Delete specific documents > success = store.delete(ids=["doc1", "doc2"]) > > # Delete the entire index > success = store.delete(delete_index=True) > ``` > [tab] JS/TS > > ```typescript theme={null} > delete(params: { ids?: string[] }): Promise > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `params.ids` | `string[]` | *(Optional)* Array of document IDs to delete | > > ### Returns > > `Promise`: Resolves on success, throws on failure > > > [!WARNING] > > > > The JS/TS SDK does not support the `delete_index` parameter. To delete an entire index, use the CyborgDB service client directly. > > > [!NOTE] > > > > Unlike the Python SDKs which return `bool`, the JS/TS method returns `void` and throws an error on failure. > > ### Example Usage > > ```typescript theme={null} > // Delete specific documents > await store.delete({ ids: ["doc1", "doc2", "doc3"] }); > ``` ### Async > [accordion] Python async variants > > The Embedded and Python SDK provide async versions of this method prefixed with `a`: > > ```python theme={null} > # adelete — async variant > success = await store.adelete(ids=["doc1", "doc2"]) > ``` > [!NOTE] > > JS/TS methods are natively async — all signatures above already return `Promise<...>`. No separate async variant is needed. # from_documents Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/from_documents Creates a CyborgVectorStore instance from a list of LangChain Document objects. > [tab] Embedded > > ```python theme={null} > @classmethod > from_documents( > documents: List[Document], > embedding: Union[str, Embeddings], > **kwargs > ) -> CyborgVectorStore > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `documents` | `List[Document]` | List of LangChain Document objects | > | `embedding` | `Union[str, Embeddings]` | Embedding model or model name | > | `**kwargs` | `Any` | Additional arguments passed to from_texts | > > ### Returns > > `CyborgVectorStore`: Initialized vector store with documents added > > ### Example Usage > > ```python theme={null} > from langchain_core.documents import Document > from cyborgdb_core import StorageConfig > > # Create documents > documents = [ > Document( > page_content="Introduction to natural language processing", > metadata={"source": "nlp_guide.pdf", "page": 1} > ), > Document( > page_content="Tokenization and text preprocessing", > metadata={"source": "nlp_guide.pdf", "page": 15} > ), > Document( > page_content="Word embeddings and semantic similarity", > metadata={"source": "nlp_guide.pdf", "page": 42} > ) > ] > > # Create store from documents > store = CyborgVectorStore.from_documents( > documents=documents, > embedding="sentence-transformers/all-mpnet-base-v2", > index_name="nlp_documents", > index_key=CyborgVectorStore.generate_key(), > api_key="your-api-key", > storage_config=StorageConfig.disk("/tmp/cyborgdb-langchain") > ) > ``` > [tab] Python SDK > > ```python theme={null} > @classmethod > from_documents( > documents: List[Document], > embedding: Union[str, Embeddings, SentenceTransformer], > **kwargs > ) -> CyborgVectorStore > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `documents` | `List[Document]` | List of LangChain Document objects | > | `embedding` | `Union[str, Embeddings, SentenceTransformer]` | Embedding model or model name | > | `**kwargs` | `Any` | Additional arguments passed to from_texts (includes `base_url`, `api_key`, etc.) | > > ### Returns > > `CyborgVectorStore`: Initialized vector store with documents added > > ### Example Usage > > ```python theme={null} > from langchain_core.documents import Document > > documents = [ > Document( > page_content="Introduction to natural language processing", > metadata={"source": "nlp_guide.pdf", "page": 1} > ), > Document( > page_content="Tokenization and text preprocessing", > metadata={"source": "nlp_guide.pdf", "page": 15} > ) > ] > > store = CyborgVectorStore.from_documents( > documents=documents, > embedding="sentence-transformers/all-mpnet-base-v2", > index_name="nlp_documents", > index_key=CyborgVectorStore.generate_key(save=True), > api_key="your-api-key", > base_url="http://localhost:8000" > ) > ``` > [tab] JS/TS > > ```typescript theme={null} > static fromDocuments( > documents: Document[], > embeddings: EmbeddingsInterface, > config: CyborgVectorStoreConfig > ): Promise > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `documents` | `Document[]` | Array of LangChain Document objects | > | `embeddings` | `EmbeddingsInterface` | LangChain embeddings instance | > | `config` | `CyborgVectorStoreConfig` | Configuration object with `baseUrl`, `apiKey`, `indexName`, `indexKey`, etc. | > > ### Returns > > `Promise`: Initialized vector store with documents added > > ### Example Usage > > ```typescript theme={null} > import { CyborgVectorStore } from 'cyborgdb/integrations/langchain'; > import { OpenAIEmbeddings } from '@langchain/openai'; > import { Document } from '@langchain/core/documents'; > > const documents = [ > new Document({ > pageContent: "Introduction to natural language processing", > metadata: { source: "nlp_guide.pdf", page: 1 } > }), > new Document({ > pageContent: "Tokenization and text preprocessing", > metadata: { source: "nlp_guide.pdf", page: 15 } > }) > ]; > > const store = await CyborgVectorStore.fromDocuments( > documents, > new OpenAIEmbeddings(), > { > baseUrl: "http://localhost:8000", > apiKey: "your-api-key", > indexName: "nlp_documents", > indexKey: CyborgVectorStore.generateKey() > } > ); > ``` # from_texts Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/from_texts Creates a CyborgVectorStore instance from a list of texts. > [tab] Embedded > > ```python theme={null} > @classmethod > from_texts( > cls, > texts: List[str], > embedding: Union[str, Embeddings], > metadatas: Optional[List[dict]] = None, > *, > ids: Optional[List[str]] = None, > **kwargs: Any > ) -> CyborgVectorStore > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `texts` | `List[str]` | List of text strings to add to the store | > | `embedding` | `Union[str, Embeddings]` | Embedding model or model name | > | `metadatas` | `Optional[List[dict]]` | *(Optional)* List of metadata dictionaries for each text | > | `**kwargs` | `Any` | Additional arguments passed to constructor and add_texts | > > ### Keyword Arguments > > | Parameter | Type | Description | > | - | - | - | > | `ids` | `List[str]` | *(Optional)* IDs for the texts | > | `index_name` | `str` | Name of the index (default: "langchain_index") | > | `index_key` | `bytes` | 32-byte encryption key (required) | > | `api_key` | `str` | API key for CyborgDB (required; pass `""` for free-tier mode) | > | `storage_config` | `StorageConfig` | Backing-store configuration (required) | > | `dimension` | `int` | *(Optional)* Embedding dimension (auto-inferred if not provided) | > | `metric` | `str` | Distance metric (default: "cosine") | > > ### Returns > > `CyborgVectorStore`: Initialized vector store with texts added > > ### Example Usage > > ```python theme={null} > from cyborgdb_core import StorageConfig > > # Create store from texts > texts = [ > "Introduction to Python", > "Advanced Python techniques", > "Python for data science" > ] > metadatas = [ > {"chapter": 1}, > {"chapter": 2}, > {"chapter": 3} > ] > > store = CyborgVectorStore.from_texts( > texts=texts, > embedding="sentence-transformers/all-MiniLM-L6-v2", > metadatas=metadatas, > index_name="python_docs", > index_key=CyborgVectorStore.generate_key(), > api_key="your-api-key", > storage_config=StorageConfig.s3("my-bucket", region="us-east-1") > ) > ``` > [tab] Python SDK > > ```python theme={null} > @classmethod > from_texts( > cls, > texts: List[str], > embedding: Union[str, Embeddings, SentenceTransformer], > metadatas: Optional[List[dict]] = None, > *, > ids: Optional[List[str]] = None, > **kwargs: Any > ) -> CyborgVectorStore > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `texts` | `List[str]` | List of text strings to add to the store | > | `embedding` | `Union[str, Embeddings, SentenceTransformer]` | Embedding model or model name | > | `metadatas` | `Optional[List[dict]]` | *(Optional)* List of metadata dictionaries for each text | > | `**kwargs` | `Any` | Additional arguments passed to constructor and add_texts | > > ### Keyword Arguments > > | Parameter | Type | Description | > | - | - | - | > | `ids` | `List[str]` | *(Optional)* IDs for the texts | > | `index_name` | `str` | Name of the index (default: "langchain_index") | > | `index_key` | `bytes` | 32-byte encryption key (required) | > | `api_key` | `str` | API key for CyborgDB (required) | > | `base_url` | `str` | Base URL of CyborgDB microservice (required) | > | `verify_ssl` | `bool` | *(Optional)* SSL verification | > | `metric` | `str` | Distance metric (default: "cosine") | > > ### Returns > > `CyborgVectorStore`: Initialized vector store with texts added > > > [!NOTE] > > > > The `embeddings` parameter can optionally accept pre-computed embedding vectors instead of a model, for cases where you generate embeddings externally. > > ### Example Usage > > ```python theme={null} > store = CyborgVectorStore.from_texts( > texts=["Introduction to Python", "Advanced Python techniques"], > embedding="sentence-transformers/all-MiniLM-L6-v2", > metadatas=[{"chapter": 1}, {"chapter": 2}], > index_name="python_docs", > index_key=CyborgVectorStore.generate_key(save=True), > api_key="your-api-key", > base_url="http://localhost:8000" > ) > ``` > [tab] JS/TS > > ```typescript theme={null} > static fromTexts( > texts: string[], > metadatas: Record[], > embeddings: EmbeddingsInterface, > config: CyborgVectorStoreConfig > ): Promise > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `texts` | `string[]` | Array of text strings to add to the store | > | `metadatas` | `Record[]` | Array of metadata objects for each text | > | `embeddings` | `EmbeddingsInterface` | LangChain embeddings instance | > | `config` | `CyborgVectorStoreConfig` | Configuration object with `baseUrl`, `apiKey`, `indexName`, `indexKey`, etc. | > > ### Returns > > `Promise`: Initialized vector store with texts added > > ### Example Usage > > ```typescript theme={null} > import { CyborgVectorStore } from 'cyborgdb/integrations/langchain'; > import { OpenAIEmbeddings } from '@langchain/openai'; > > const store = await CyborgVectorStore.fromTexts( > ["Introduction to Python", "Advanced Python techniques"], > [{ chapter: 1 }, { chapter: 2 }], > new OpenAIEmbeddings(), > { > baseUrl: "http://localhost:8000", > apiKey: "your-api-key", > indexName: "python_docs", > indexKey: CyborgVectorStore.generateKey() > } > ); > ``` ### Exceptions > [accordion] ValueError > > * Throws if index_key is not provided # generate_key Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/generate_key Generates a secure random 32-byte encryption key for index encryption. > [tab] Embedded > > ```python theme={null} > @staticmethod > generate_key() -> bytes > ``` > > ### Returns > > `bytes`: Cryptographically secure 32-byte key > > ### Example Usage > > ```python theme={null} > from cyborgdb_core import StorageConfig > > # Generate a new encryption key > index_key = CyborgVectorStore.generate_key() > print(f"Key length: {len(index_key)} bytes") > > # Use the key to create a store > store = CyborgVectorStore( > index_name="secure_index", > index_key=index_key, > api_key="your-api-key", > embedding="all-MiniLM-L6-v2", > storage_config=StorageConfig.s3("secure-bucket", region="us-east-1") > ) > > # Store the key securely for future use > import base64 > encoded_key = base64.b64encode(index_key).decode('utf-8') > print(f"Base64 encoded key: {encoded_key}") > ``` > [tab] Python SDK > > ```python theme={null} > @staticmethod > generate_key(save: bool = False) -> bytes > ``` > > ### Parameters > > | Parameter | Type | Default | Description | > | - | - | - | - | > | `save` | `bool` | `False` | Whether to save/load the generated key to/from a local file | > > ### Returns > > `bytes`: Cryptographically secure 32-byte key > > ### Example Usage > > ```python theme={null} > index_key = CyborgVectorStore.generate_key(save=True) > > store = CyborgVectorStore( > index_name="secure_index", > index_key=index_key, > api_key="your-api-key", > embedding="all-MiniLM-L6-v2", > base_url="http://localhost:8000" > ) > ``` > [tab] JS/TS > > ```typescript theme={null} > static generateKey(): Uint8Array > ``` > > ### Returns > > `Uint8Array`: Cryptographically secure 32-byte key > > > [!NOTE] > > > > The JS/TS SDK does not have a `save` parameter. Key persistence must be handled by your application. The return type is `Uint8Array` instead of Python's `bytes`. > > ### Example Usage > > ```typescript theme={null} > const indexKey = CyborgVectorStore.generateKey(); > console.log(`Key length: ${indexKey.length} bytes`); > > const store = new CyborgVectorStore( > new OpenAIEmbeddings(), > { > baseUrl: "http://localhost:8000", > apiKey: "your-api-key", > indexName: "secure_index", > indexKey: indexKey > } > ); > ``` ### Security Notes > [!WARNING] > > Store encryption keys securely! Never commit keys to version control or expose them in logs. Consider using a key management service for production deployments. # get Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/get Retrieves documents by their IDs from the vector store. > [!NOTE] > > Available in Python SDK and JS/TS SDK. For the Embedded library, use `get_by_id()`, `get_by_ids()`, `get_document()`, or `get_documents()` directly on the CyborgVectorStore instance. > [tab] Python SDK > > ```python theme={null} > get(ids: List[str]) -> List[Document] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `ids` | `List[str]` | List of document IDs to retrieve | > > ### Returns > > `List[Document]`: List of Document objects matching the given IDs > > ### Example Usage > > ```python theme={null} > # Retrieve specific documents by ID > doc_ids = ["doc1", "doc2", "doc3"] > documents = store.get(doc_ids) > > for doc in documents: > print(f"Content: {doc.page_content[:100]}...") > print(f"Metadata: {doc.metadata}") > ``` > [tab] JS/TS > > ```typescript theme={null} > get(ids: string[]): Promise > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `ids` | `string[]` | Array of document IDs to retrieve | > > ### Returns > > `Promise`: Array of Document objects matching the given IDs > > ### Example Usage > > ```typescript theme={null} > const docIds = ["doc1", "doc2", "doc3"]; > const documents = await store.get(docIds); > > for (const doc of documents) { > console.log(`Content: ${doc.pageContent.slice(0, 100)}...`); > console.log(`Metadata:`, doc.metadata); > } > ``` # get_embeddings Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/get_embeddings Generates embeddings for the given texts using the configured embedding model. > [!NOTE] > > Available in Embedded and Python SDK. The JS/TS SDK handles embedding generation internally. > [tab] Embedded > > ```python theme={null} > get_embeddings(texts: Union[str, List[str]]) -> np.ndarray > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `texts` | `Union[str, List[str]]` | Single text string or list of text strings to embed | > > ### Returns > > `np.ndarray`: NumPy array of embeddings > > * If single text: 1-D array of shape `(dimension,)` > * If list of texts: 2-D array of shape `(num_texts, dimension)` > > ### Exceptions > > > [accordion] RuntimeError > > > > * Throws if no embedding model is available > > > [accordion] TypeError > > > > * Throws if embedding model type is not supported > > ### Example Usage > > ```python theme={null} > # Single text embedding > embedding = store.get_embeddings("Hello, world!") > print(f"Embedding shape: {embedding.shape}") # (384,) > > # Multiple text embeddings > texts = ["First document", "Second document", "Third document"] > embeddings = store.get_embeddings(texts) > print(f"Embeddings shape: {embeddings.shape}") # (3, 384) > ``` > [tab] Python SDK > > ```python theme={null} > get_embeddings(texts: Union[str, List[str]]) -> np.ndarray > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `texts` | `Union[str, List[str]]` | Single text string or list of text strings to embed | > > ### Returns > > `np.ndarray`: NumPy array of embeddings > > * If single text: 1-D array of shape `(dimension,)` > * If list of texts: 2-D array of shape `(num_texts, dimension)` > > Delegates to the configured LangChain Embeddings object for embedding generation. > > ### Example Usage > > ```python theme={null} > embedding = store.get_embeddings("Hello, world!") > print(f"Embedding shape: {embedding.shape}") # (384,) > > texts = ["First document", "Second document"] > embeddings = store.get_embeddings(texts) > print(f"Embeddings shape: {embeddings.shape}") # (2, 384) > ``` # __init__ Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/init Initializes a new CyborgVectorStore instance for use with LangChain. > [tab] Embedded > > ```python theme={null} > CyborgVectorStore( > index_name: str, > index_key: bytes | list[int] | tuple[int, ...] | np.ndarray, > api_key: str, > embedding: Union[str, Embeddings], > storage_config: StorageConfig, > gpu_config: Optional[GPUConfig] = None, > dimension: Optional[int] = None, > metric: str = "cosine" > ) > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `index_name` | `str` | Name of the index (must be unique) | > | `index_key` | `bytes \| list[int] \| tuple[int, ...] \| np.ndarray` | 32-byte encryption key for securing index data | > | `api_key` | `str` | API key for CyborgDB authentication | > | `embedding` | `Union[str, Embeddings]` | LangChain Embeddings instance, or the name of a built-in embedding model | > | `storage_config` | `StorageConfig` | Backing-store configuration, built with `StorageConfig.disk(...)` or `StorageConfig.s3(...)` | > | `gpu_config` | `Optional[GPUConfig]` | *(Optional)* GPU configuration for accelerated operations | > | `dimension` | `Optional[int]` | *(Optional)* Embedding dimension (auto-inferred if not provided) | > | `metric` | `str` | Distance metric: `"cosine"`, `"euclidean"`, or `"squared_euclidean"` (default: `"cosine"`) | > > ### Returns > > `CyborgVectorStore`: Initialized vector store instance > > ### Example Usage > > ```python theme={null} > from cyborgdb_core.integrations.langchain import CyborgVectorStore > from cyborgdb_core import StorageConfig > from langchain_openai import OpenAIEmbeddings > > # Generate a secure key > index_key = CyborgVectorStore.generate_key() > > # Initialize with LangChain Embeddings > store = CyborgVectorStore( > index_name="my_documents", > index_key=index_key, > api_key="your-api-key", > embedding=OpenAIEmbeddings(), > storage_config=StorageConfig.disk("/var/lib/cyborgdb"), > metric="cosine" > ) > ``` > [tab] Python SDK > > ```python theme={null} > CyborgVectorStore( > index_name: str, > index_key: bytes, > api_key: str, > embedding: Union[str, Embeddings, SentenceTransformer], > base_url: str, > dimension: Optional[int] = None, > metric: str = "cosine", > verify_ssl: Optional[bool] = None > ) > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `index_name` | `str` | Name of the index (must be unique) | > | `index_key` | `bytes` | 32-byte encryption key for securing index data | > | `api_key` | `str` | API key for CyborgDB authentication | > | `embedding` | `Union[str, Embeddings, SentenceTransformer]` | Embedding model name or instance | > | `base_url` | `str` | Base URL of the CyborgDB microservice endpoint | > | `verify_ssl` | `Optional[bool]` | *(Optional)* SSL verification. When `None`, automatically disabled for `localhost` and `http://` URLs | > | `dimension` | `Optional[int]` | *(Optional)* Embedding dimension (auto-inferred if not provided) | > | `metric` | `str` | Distance metric: "cosine", "euclidean", or "squared_euclidean" (default: "cosine") | > > ### Returns > > `CyborgVectorStore`: Initialized vector store instance > > > [!NOTE] > > > > The Python SDK requires a running CyborgDB service. Use `base_url` to point to your service endpoint instead of providing a `StorageConfig`; storage is configured on the service. > > ### Example Usage > > ```python theme={null} > from cyborgdb.integrations.langchain import CyborgVectorStore > > # Generate a secure key > index_key = CyborgVectorStore.generate_key(save=True) > > # Initialize with string embedding model name > store = CyborgVectorStore( > index_name="my_documents", > index_key=index_key, > api_key="your-api-key", > embedding="sentence-transformers/all-MiniLM-L6-v2", > base_url="http://localhost:8000", > metric="cosine" > ) > ``` > [tab] JS/TS > > ```typescript theme={null} > new CyborgVectorStore(embeddings: EmbeddingsInterface, config: CyborgVectorStoreConfig) > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `embeddings` | `EmbeddingsInterface` | LangChain embeddings instance | > | `config` | `CyborgVectorStoreConfig` | Configuration object (see below) | > > ### CyborgVectorStoreConfig > > | Parameter | Type | Description | > | - | - | - | > | `baseUrl` | `string` | Base URL of the CyborgDB microservice endpoint | > | `apiKey` | `string` | API key for CyborgDB authentication | > | `indexName` | `string` | Name of the index (must be unique) | > | `indexKey` | `Uint8Array` | 32-byte encryption key for securing index data | > | `dimension` | `number` | *(Optional)* Embedding dimension (auto-inferred if not provided) | > | `metric` | `string` | *(Optional)* Distance metric: `"cosine"`, `"euclidean"`, or `"squared_euclidean"` (default: `"cosine"`) | > | `verifySsl` | `boolean` | *(Optional)* SSL verification (default: `true`) | > > ### Returns > > `CyborgVectorStore`: Initialized vector store instance > > > [!NOTE] > > > > The JS/TS SDK requires a running CyborgDB service. Use `baseUrl` to point to your service endpoint; storage is configured on the service. > > ### Example Usage > > ```typescript theme={null} > import { CyborgVectorStore } from 'cyborgdb/integrations/langchain'; > import { OpenAIEmbeddings } from '@langchain/openai'; > > const store = new CyborgVectorStore( > new OpenAIEmbeddings(), > { > baseUrl: "http://localhost:8000", > apiKey: "your-api-key", > indexName: "my_documents", > indexKey: CyborgVectorStore.generateKey(), > metric: "cosine" > } > ); > ``` ### Exceptions > [accordion] RuntimeError > > * Throws if no embedding model provided and dimension not specified # list_ids Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/list_ids Returns a list of all document IDs stored in the vector store. > [tab] Embedded > > ```python theme={null} > list_ids() -> List[str] > ``` > > ### Returns > > `List[str]`: List of all document IDs in the store > > ### Example Usage > > ```python theme={null} > ids = store.list_ids() > print(f"Store contains {len(ids)} documents") > print(f"First 5 IDs: {ids[:5]}") > ``` > [tab] Python SDK > > ```python theme={null} > list_ids() -> List[str] > ``` > > ### Returns > > `List[str]`: List of all document IDs in the store > > ### Example Usage > > ```python theme={null} > ids = store.list_ids() > print(f"Store contains {len(ids)} documents") > ``` > [tab] JS/TS > > ```typescript theme={null} > listIds(): Promise > ``` > > ### Returns > > `Promise`: Array of all document IDs in the store > > ### Example Usage > > ```typescript theme={null} > const ids = await store.listIds(); > console.log(`Store contains ${ids.length} documents`); > ``` # max_marginal_relevance_search Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/max_marginal_relevance_search Returns documents selected using maximal marginal relevance to balance relevance and diversity. > [!NOTE] > > Available in Embedded and JS/TS SDK. The Python SDK does not currently support MMR search. > [tab] Embedded > > ```python theme={null} > max_marginal_relevance_search( > query: str, > k: int = 4, > fetch_k: int = 20, > lambda_mult: float = 0.5, > filter: Optional[Dict[str, Any]] = None, > **kwargs > ) -> List[Document] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `query` | `str` | Query text to search for | > | `k` | `int` | Number of documents to return (default: 4) | > | `fetch_k` | `int` | Number of documents to fetch before reranking (default: 20) | > | `lambda_mult` | `float` | Diversity control: 0 = max diversity, 1 = min diversity (default: 0.5) | > | `filter` | `Optional[Dict[str, Any]]` | *(Optional)* Metadata filters to apply | > | `**kwargs` | `Any` | Additional keyword arguments (currently unused) | > > ### Returns > > `List[Document]`: List of diverse, relevant Document objects > > ### Example Usage > > ```python theme={null} > # Search with balanced relevance and diversity > results = store.max_marginal_relevance_search( > "Python programming concepts", > k=5, > fetch_k=20, > lambda_mult=0.5 # Balance relevance and diversity > ) > > # Maximum diversity (avoid similar documents) > diverse_results = store.max_marginal_relevance_search( > "data structures", > k=5, > lambda_mult=0.0 # Maximum diversity > ) > > # Maximum relevance (similar to standard search) > relevant_results = store.max_marginal_relevance_search( > "algorithms", > k=5, > lambda_mult=1.0 # Maximum relevance > ) > ``` > > ### By Vector Variant > > The Embedded library also provides `max_marginal_relevance_search_by_vector` for searching with a pre-computed embedding vector: > > ```python theme={null} > max_marginal_relevance_search_by_vector( > embedding: Union[List[float], np.ndarray], > k: int = 4, > fetch_k: int = 20, > lambda_mult: float = 0.5, > filter: Optional[Dict[str, Any]] = None, > **kwargs > ) -> List[Document] > ``` > > **Parameters:** > > | Parameter | Type | Description | > | - | - | - | > | `embedding` | `Union[List[float], np.ndarray]` | Query embedding vector | > | `k` | `int` | Number of documents to return (default: 4) | > | `fetch_k` | `int` | Number of documents to fetch before reranking (default: 20) | > | `lambda_mult` | `float` | Diversity control: 0 = max diversity, 1 = min diversity (default: 0.5) | > | `filter` | `Optional[Dict[str, Any]]` | *(Optional)* Metadata filters to apply | > | `**kwargs` | `Any` | Additional keyword arguments (currently unused) | > > **Example:** > > ```python theme={null} > # Get query embedding > query_embedding = store.get_embeddings("machine learning algorithms") > > # MMR search with embedding > results = store.max_marginal_relevance_search_by_vector( > query_embedding, > k=5, > fetch_k=30, > lambda_mult=0.3 # Favor diversity > ) > > # With metadata filter > filtered_results = store.max_marginal_relevance_search_by_vector( > query_embedding, > k=4, > filter={"category": "tutorial"}, > lambda_mult=0.7 # Favor relevance > ) > ``` > [tab] JS/TS > > ```typescript theme={null} > maxMarginalRelevanceSearch( > query: string, > options: { k?: number; fetchK?: number; lambda?: number; filter?: Record } > ): Promise > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `query` | `string` | Query text to search for | > | `options.k` | `number` | *(Optional)* Number of documents to return | > | `options.fetchK` | `number` | *(Optional)* Number of documents to fetch before reranking | > | `options.lambda` | `number` | *(Optional)* Diversity control: 0 = max diversity, 1 = min diversity | > | `options.filter` | `Record` | *(Optional)* Metadata filters to apply | > > ### Returns > > `Promise`: Array of diverse, relevant Document objects > > > [!NOTE] > > > > The JS/TS SDK does not have a separate by-vector variant. Use `maxMarginalRelevanceSearch` with a text query. > > ### Example Usage > > ```typescript theme={null} > const results = await store.maxMarginalRelevanceSearch( > "Python programming concepts", > { k: 5, fetchK: 20, lambda: 0.5 } > ); > > // Maximum diversity > const diverse = await store.maxMarginalRelevanceSearch( > "data structures", > { k: 5, lambda: 0.0 } > ); > ``` ### Async > [accordion] Python async variants > > The Embedded library provides an async version of this method prefixed with `a`: > > ```python theme={null} > # amax_marginal_relevance_search — async variant > docs = await store.amax_marginal_relevance_search("query", k=5, lambda_mult=0.5) > ``` > [!NOTE] > > JS/TS methods are natively async — all signatures above already return `Promise<...>`. No separate async variant is needed. # similarity_search Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/similarity_search Returns documents most similar to the query text. > [tab] Embedded > > ```python theme={null} > similarity_search( > query: str, > k: int = 4, > filter: Optional[Dict[str, Any]] = None, > **kwargs > ) -> List[Document] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `query` | `str` | Query text to search for | > | `k` | `int` | Number of documents to return (default: 4) | > | `filter` | `Optional[Dict[str, Any]]` | *(Optional)* Metadata filters to apply | > | `**kwargs` | `Any` | Additional keyword arguments (currently unused) | > > ### Returns > > `List[Document]`: List of most similar Document objects > > ### Example Usage > > ```python theme={null} > # Basic similarity search > results = store.similarity_search("machine learning algorithms", k=5) > for doc in results: > print(f"Content: {doc.page_content[:100]}...") > print(f"Metadata: {doc.metadata}") > > # Search with metadata filter > filter_dict = {"language": "python", "level": "beginner"} > results = store.similarity_search( > "python tutorial", > k=3, > filter=filter_dict > ) > ``` > [tab] Python SDK > > ```python theme={null} > similarity_search( > query: str, > k: Optional[int] = None, > filter: Optional[Dict[str, Any]] = None, > **kwargs > ) -> List[Document] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `query` | `str` | Query text to search for | > | `k` | `Optional[int]` | *(Optional)* Number of documents to return (default: `None`, uses server default) | > | `filter` | `Optional[Dict[str, Any]]` | *(Optional)* Metadata filters to apply | > | `**kwargs` | `Any` | Additional keyword arguments | > > ### Returns > > `List[Document]`: List of most similar Document objects > > > [!NOTE] > > > > When `k` is `None`, the server default number of results is returned. > > ### Example Usage > > ```python theme={null} > results = store.similarity_search("machine learning algorithms", k=5) > for doc in results: > print(f"Content: {doc.page_content[:100]}...") > ``` > [tab] JS/TS > > ```typescript theme={null} > similaritySearch( > query: string, > k?: number, > filter?: Record > ): Promise > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `query` | `string` | Query text to search for | > | `k` | `number` | *(Optional)* Number of documents to return | > | `filter` | `Record` | *(Optional)* Metadata filters to apply | > > ### Returns > > `Promise`: Array of most similar Document objects > > ### Example Usage > > ```typescript theme={null} > const results = await store.similaritySearch("machine learning algorithms", 5); > for (const doc of results) { > console.log(`Content: ${doc.pageContent.slice(0, 100)}...`); > console.log(`Metadata:`, doc.metadata); > } > > // Search with metadata filter > const filtered = await store.similaritySearch( > "python tutorial", > 3, > { language: "python", level: "beginner" } > ); > ``` ### Async > [accordion] Python async variants > > The Embedded and Python SDK provide async versions of this method prefixed with `a`: > > ```python theme={null} > # asimilarity_search — async variant > docs = await store.asimilarity_search("query", k=5) > ``` > [!NOTE] > > JS/TS methods are natively async — all signatures above already return `Promise<...>`. No separate async variant is needed. # similarity_search_by_vector Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/similarity_search_by_vector Returns documents most similar to an embedding vector. > [tab] Embedded > > ```python theme={null} > similarity_search_by_vector( > embedding: Union[List[float], np.ndarray], > k: int = 4, > filter: Optional[Dict[str, Any]] = None, > **kwargs > ) -> List[Document] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `embedding` | `Union[List[float], np.ndarray]` | Embedding vector to search with | > | `k` | `int` | Number of documents to return (default: 4) | > | `filter` | `Optional[Dict[str, Any]]` | *(Optional)* Metadata filters to apply | > | `**kwargs` | `Any` | Additional keyword arguments (currently unused) | > > ### Returns > > `List[Document]`: List of most similar Document objects > > ### Example Usage > > ```python theme={null} > # Get embedding for a query > query_embedding = store.get_embeddings("data science concepts") > > # Search using the embedding > results = store.similarity_search_by_vector(query_embedding, k=5) > > # Search with custom embedding > custom_embedding = np.random.rand(384) # Example 384-dim embedding > results = store.similarity_search_by_vector(custom_embedding, k=3) > ``` > [tab] Python SDK > > ```python theme={null} > similarity_search_by_vector( > embedding: Union[List[float], np.ndarray], > k: Optional[int] = None, > filter: Optional[Dict[str, Any]] = None, > **kwargs > ) -> List[Document] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `embedding` | `Union[List[float], np.ndarray]` | Embedding vector to search with | > | `k` | `Optional[int]` | *(Optional)* Number of documents to return (default: `None`, uses server default) | > | `filter` | `Optional[Dict[str, Any]]` | *(Optional)* Metadata filters to apply | > | `**kwargs` | `Any` | Additional keyword arguments | > > ### Returns > > `List[Document]`: List of most similar Document objects > > ### Example Usage > > ```python theme={null} > query_embedding = store.get_embeddings("data science concepts") > results = store.similarity_search_by_vector(query_embedding, k=5) > ``` > [tab] JS/TS > > ```typescript theme={null} > similaritySearchVectorWithScore( > query: number[], > k: number, > filter?: Record > ): Promise<[Document, number][]> > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `query` | `number[]` | Embedding vector to search with | > | `k` | `number` | Number of documents to return | > | `filter` | `Record` | *(Optional)* Metadata filters to apply | > > ### Returns > > `Promise<[Document, number][]>`: Array of \[Document, score] tuples > > > [!WARNING] > > > > The JS/TS method name is `similaritySearchVectorWithScore` (not `similaritySearchByVector`), and it returns score tuples unlike the Python SDKs which return documents only. > > ### Example Usage > > ```typescript theme={null} > const queryEmbedding = [0.1, 0.2, 0.3, /* ... */]; > const results = await store.similaritySearchVectorWithScore(queryEmbedding, 5); > > for (const [doc, score] of results) { > console.log(`Score: ${score.toFixed(4)} - ${doc.pageContent.slice(0, 100)}...`); > } > ``` ### Async > [accordion] Python async variants > > The Embedded and Python SDK provide async versions of this method prefixed with `a`: > > ```python theme={null} > # asimilarity_search_by_vector — async variant > docs = await store.asimilarity_search_by_vector(embedding, k=5) > ``` > [!NOTE] > > JS/TS methods are natively async — all signatures above already return `Promise<...>`. No separate async variant is needed. # similarity_search_with_score Source: https://docs.cyborg.co/versions/latest/integrations/langchain/client/similarity_search_with_score Returns documents most similar to the query along with relevance scores. > [tab] Embedded > > ```python theme={null} > similarity_search_with_score( > query: str, > k: int = 4, > filter: Optional[Dict[str, Any]] = None, > **kwargs > ) -> List[Tuple[Document, float]] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `query` | `str` | Query text to search for | > | `k` | `int` | Number of documents to return (default: 4) | > | `filter` | `Optional[Dict[str, Any]]` | *(Optional)* Metadata filters to apply | > | `**kwargs` | `Any` | Additional keyword arguments (currently unused) | > > ### Returns > > `List[Tuple[Document, float]]`: List of (Document, score) tuples where score is normalized \[0, 1] > > ### Example Usage > > ```python theme={null} > # Search with scores > results = store.similarity_search_with_score("neural networks", k=3) > > for doc, score in results: > print(f"Score: {score:.4f}") > print(f"Content: {doc.page_content[:100]}...") > print(f"Metadata: {doc.metadata}") > print("---") > > # Filter results by score threshold > threshold = 0.7 > high_score_results = [ > (doc, score) for doc, score in results if score >= threshold > ] > ``` > > > [accordion] \_similarity_search_with_relevance_scores (internal method) > > > > The Embedded library also exposes `_similarity_search_with_relevance_scores`, an internal method that supports a `score_threshold` keyword argument for server-side score filtering: > > > > ```python theme={null} > > _similarity_search_with_relevance_scores( > > query: str, > > k: int, > > **kwargs > > ) -> List[Tuple[Document, float]] > > ``` > > > > **Keyword Arguments:** > > > > | Parameter | Type | Description | > > | - | - | - | > > | `filter` | `Dict[str, Any]` | *(Optional)* Metadata filters to apply | > > | `score_threshold` | `float` | *(Optional)* Minimum score threshold for results | > > > > **Example:** > > > > ```python theme={null} > > # Search with relevance scores and threshold > > results = store._similarity_search_with_relevance_scores( > > "machine learning", > > k=10, > > score_threshold=0.5 > > ) > > > > print(f"Found {len(results)} documents above threshold") > > for doc, score in results: > > print(f"Relevance: {score:.2%} - {doc.page_content[:50]}...") > > ``` > [tab] Python SDK > > ```python theme={null} > similarity_search_with_score( > query: str, > k: Optional[int] = None, > filter: Optional[Dict[str, Any]] = None, > **kwargs > ) -> List[Tuple[Document, float]] > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `query` | `str` | Query text to search for | > | `k` | `Optional[int]` | *(Optional)* Number of documents to return (default: `None`, uses server default) | > | `filter` | `Optional[Dict[str, Any]]` | *(Optional)* Metadata filters to apply | > | `**kwargs` | `Any` | Additional keyword arguments | > > ### Returns > > `List[Tuple[Document, float]]`: List of (Document, score) tuples where score is normalized \[0, 1] > > ### Example Usage > > ```python theme={null} > results = store.similarity_search_with_score("neural networks", k=3) > > for doc, score in results: > print(f"Score: {score:.4f} - {doc.page_content[:100]}...") > ``` > [tab] JS/TS > > ```typescript theme={null} > similaritySearchWithScore( > query: string, > k?: number, > filter?: Record > ): Promise<[Document, number][]> > ``` > > ### Parameters > > | Parameter | Type | Description | > | - | - | - | > | `query` | `string` | Query text to search for | > | `k` | `number` | *(Optional)* Number of documents to return | > | `filter` | `Record` | *(Optional)* Metadata filters to apply | > > ### Returns > > `Promise<[Document, number][]>`: Array of \[Document, score] tuples > > ### Example Usage > > ```typescript theme={null} > const results = await store.similaritySearchWithScore("neural networks", 3); > > for (const [doc, score] of results) { > console.log(`Score: ${score.toFixed(4)}`); > console.log(`Content: ${doc.pageContent.slice(0, 100)}...`); > } > ``` ### Async > [accordion] Python async variants > > The Embedded and Python SDK provide async versions of this method prefixed with `a`: > > ```python theme={null} > # asimilarity_search_with_score — async variant > results = await store.asimilarity_search_with_score("query", k=3) > ``` > [!NOTE] > > JS/TS methods are natively async — all signatures above already return `Promise<...>`. No separate async variant is needed. # CyborgDB - LangChain Integration Source: https://docs.cyborg.co/versions/latest/integrations/langchain/introduction `v0.18.x` CyborgDB provides a seamless integration with [LangChain](https://www.langchain.com/), enabling developers to leverage encrypted vector search for large language models (LLMs) and RAG pipelines. This integration is implemented via the `CyborgVectorStore` class, which conforms to the `VectorStore` interface from `langchain-core`. ## Installation > [tab] Embedded > > Install `cyborgdb-core` with the `langchain` extra (Python 3.10 or newer; the `python3` that ships with macOS is 3.9): > > ```bash theme={null} > pip install "cyborgdb-core[langchain]" > ``` > [tab] Python SDK > > Install the `cyborgdb` package with the `langchain` extra (Python 3.10 or newer): > > ```bash theme={null} > pip install "cyborgdb[langchain]" > ``` > [tab] JS/TS > > Install the `cyborgdb` npm package and `@langchain/core` (an optional peer of `cyborgdb`, only required for this integration): > > ```bash theme={null} > npm install cyborgdb @langchain/core > ``` > [!TIP] > > To learn more about the differences between `cyborgdb` and `cyborgdb-core`, refer to the [Deployment Models Guide](../../intro/deployment-models). ## Import > [tab] Embedded > > ```python theme={null} > from cyborgdb_core.integrations.langchain import CyborgVectorStore > ``` > [tab] Python SDK > > ```python theme={null} > from cyborgdb.integrations.langchain import CyborgVectorStore > ``` > [tab] JS/TS > > ```typescript theme={null} > import { CyborgVectorStore } from 'cyborgdb/integrations/langchain'; > ``` ## Key Features * Full VectorStore API compatibility (`add_texts`, `similarity_search`, etc.) * Async operations support * Configurable distance metrics (`cosine`, `euclidean`, `squared_euclidean`) * Document ID tracking and management * Max marginal relevance search * Factory methods (`from_texts`, `from_documents`) for quick setup ## Key Classes ### `CyborgVectorStore` Implements the LangChain-compatible vector store interface. Supports: * `.add_texts()` / `.add_documents()` * `.similarity_search()` / `.similarity_search_with_score()` * `.max_marginal_relevance_search()` * `.get()` / `.list_ids()` / `.delete()` * `.as_retriever()` for use in LangChain chains * Async variants (`.aadd_texts()`, `.asimilarity_search()`, etc.) * Reversible document ID tracking * Configurable distance metric (`cosine`, `euclidean`, `squared_euclidean`) ### `StorageConfig` (Embedded only) Configuration object for defining where index data is stored, built with `StorageConfig.disk(path)` or `StorageConfig.s3(bucket, ...)`. Used only with the Embedded library (`cyborgdb-core`). ## Quick Start > [tab] Embedded > > ```python theme={null} > import secrets > from cyborgdb_core import StorageConfig > from cyborgdb_core.integrations.langchain import CyborgVectorStore > > # Generate an encryption key for the index. > # WARNING: store this key securely — data encrypted with a lost key is unrecoverable. > index_key = secrets.token_bytes(32) > > store = CyborgVectorStore.from_texts( > texts=["hello world", "goodbye world"], > embedding="all-MiniLM-L6-v2", # built-in model: no extra install, no paid key > index_key=index_key, > api_key="", # free tier; pass your key to lift the 1M-item cap > storage_config=StorageConfig.disk("./cyborgdb-langchain"), > metric="cosine", > ) > > for doc in store.similarity_search("hello"): > print(doc.page_content) > > # Delete the index so the example can be run again (the key above is not saved). > store.delete(delete_index=True) > ``` > > To keep the index between runs, store `index_key` and construct `CyborgVectorStore(index_name="langchain_index", index_key=index_key, api_key="", embedding="all-MiniLM-L6-v2", storage_config=...)` directly: it reopens an existing index instead of creating one. > > To embed with OpenAI instead of the built-in model, install `langchain-openai` (it is not part of the `langchain` extra), set `OPENAI_API_KEY`, and pass `embedding=OpenAIEmbeddings()`: > > ```bash theme={null} > pip install langchain-openai > ``` > [tab] Python SDK > > ```python theme={null} > from cyborgdb.integrations.langchain import CyborgVectorStore > > store = CyborgVectorStore.from_texts( > texts=["hello world", "goodbye world"], > embedding="all-MiniLM-L6-v2", > index_key=CyborgVectorStore.generate_key(save=True), > api_key="your-api-key", > base_url="http://localhost:8000", > metric="cosine" > ) > > docs = store.similarity_search("hello") > ``` > [tab] JS/TS > > ```typescript theme={null} > import { CyborgVectorStore } from 'cyborgdb/integrations/langchain'; > import { OpenAIEmbeddings } from '@langchain/openai'; > > const store = await CyborgVectorStore.fromTexts( > ["hello world", "goodbye world"], > [{ source: "greeting" }, { source: "farewell" }], > new OpenAIEmbeddings(), > { > baseUrl: "http://localhost:8000", > apiKey: "your-api-key", > indexName: "my_documents", > indexKey: CyborgVectorStore.generateKey(), > metric: "cosine" > } > ); > > const docs = await store.similaritySearch("hello"); > ``` > > > [!NOTE] > > > > `fromExistingIndex()` is available as a JS/TS-only convenience factory method for connecting to an already-created index without re-adding documents. > [!WARNING] > > **Store `index_key` before you upsert any data.** CyborgDB has no key-recovery path — losing the key means losing the data. For anything past evaluation, keep the key in AWS Secrets Manager, Vault, or your KMS. See [Managing Keys](../../embedded/guides/advanced/managing-keys). > [!NOTE] > > `generate_key(save=True)` exists in the Python SDK only. The embedded library's `generate_key()` returns the bytes and nothing else, so persist the key yourself as shown above. # Types Source: https://docs.cyborg.co/versions/latest/integrations/langchain/types > [tab] Embedded > > ## StorageConfig > > The `StorageConfig` class specifies where the index data is stored. Build it with one of the static factories: > > | Factory | Description | > | - | - | > | `StorageConfig.disk(path, *, cache_vectors=False, cache_metadata=False, cache_ids=False, cache_metadata_index=False)` | Persistent local storage at `path` (recommended for embedded/local deployments). | > | `StorageConfig.s3(bucket, *, region=None, endpoint=None, prefix="", credentials=None)` | AWS S3 or any S3-compatible object store (MinIO, Cloudflare R2). Uses the AWS default credential chain unless `credentials` is set. | > > ### Example Usage > > ```python theme={null} > from cyborgdb_core import StorageConfig, S3Credentials > > # Local disk (persistent local storage) > disk_storage = StorageConfig.disk("/path/to/data") > > # S3 (cloud-native) > s3_storage = StorageConfig.s3("my-bucket", region="us-east-1") > > # S3-compatible store with explicit credentials > minio_storage = StorageConfig.s3( > "my-bucket", > endpoint="http://localhost:9000", > credentials=S3Credentials(access_key="minioadmin", secret_key="minioadmin"), > ) > ``` > > *** > > ## Embeddings > > The Embedded LangChain integration accepts any LangChain `Embeddings` implementation: > > ### Supported Embedding Types > > | Type | Description | Example | > | - | - | - | > | `str` | Name of a built-in embedding model | `"all-MiniLM-L6-v2"` | > | `Embeddings` | Any LangChain Embeddings implementation | `OpenAIEmbeddings()`, `HuggingFaceEmbeddings()` | > > ### Example Usage > > ```python theme={null} > from langchain_openai import OpenAIEmbeddings > from cyborgdb_core.integrations.langchain import CyborgVectorStore > from cyborgdb_core import StorageConfig > > # Using LangChain Embeddings > store = CyborgVectorStore( > index_name="docs", > index_key=key, > api_key="your-api-key", > embedding=OpenAIEmbeddings(), > storage_config=StorageConfig.disk("/tmp/cyborgdb-langchain") > ) > ``` > > *** > > ## DistanceMetric > > `DistanceMetric` is a string representing the distance metric used for the index. Options include: > > * `"cosine"`: Cosine similarity (recommended for normalized embeddings) > * `"euclidean"`: Euclidean distance > * `"squared_euclidean"`: Squared Euclidean distance > > ### Metric Characteristics > > | Metric | Range | Best Match | Use Case | > | - | - | - | - | > | `cosine` | \[0, 2] | 0 | Text embeddings, normalized vectors | > | `euclidean` | \[0, ∞) | 0 | Raw feature vectors | > | `squared_euclidean` | \[0, ∞) | 0 | When avoiding sqrt computation | > > *** > > ## Document > > LangChain Document object used for storing text with metadata. > > ### Attributes > > | Attribute | Type | Description | > | - | - | - | > | `page_content` | `str` | The text content of the document | > | `metadata` | `dict` | Optional metadata associated with the document | > > ### Example Usage > > ```python theme={null} > from langchain_core.documents import Document > > # Create a document > doc = Document( > page_content="This is the content of my document", > metadata={ > "source": "manual", > "author": "John Doe", > "timestamp": "2024-01-01" > } > ) > > # Add to vector store > store.add_documents([doc]) > ``` > > *** > > ## Filter Format > > Metadata filters use a dictionary format for querying documents. > > ### Simple Filters > > ```python theme={null} > # Exact match > filter = {"category": "technology"} > > # Multiple conditions (AND) > filter = { > "category": "technology", > "year": 2024 > } > ``` > > ### Advanced Filters > > ```python theme={null} > # Range queries > filter = { > "price": {"$gte": 100, "$lte": 500} > } > > # IN queries > filter = { > "tags": {"$in": ["python", "machine-learning"]} > } > > # Nested fields > filter = { > "metadata.author": "John Doe" > } > ``` > > ### Supported Operators > > | Operator | Description | Example | > | - | - | - | > | `$eq` | Equal to | `{"age": {"$eq": 25}}` | > | `$ne` | Not equal to | `{"status": {"$ne": "archived"}}` | > | `$gt` | Greater than | `{"price": {"$gt": 100}}` | > | `$gte` | Greater than or equal | `{"score": {"$gte": 0.8}}` | > | `$lt` | Less than | `{"quantity": {"$lt": 10}}` | > | `$lte` | Less than or equal | `{"rating": {"$lte": 5}}` | > | `$in` | In array | `{"tags": {"$in": ["ai", "ml"]}}` | > | `$nin` | Not in array | `{"category": {"$nin": ["draft", "deleted"]}}` | > > *** > > ## Return Types > > ### Query Results > > Query operations return documents with optional scores: > > ```python theme={null} > # similarity_search returns List[Document] > docs = store.similarity_search("query", k=5) > # Returns: [Document(...), Document(...), ...] > > # similarity_search_with_score returns List[Tuple[Document, float]] > results = store.similarity_search_with_score("query", k=5) > # Returns: [(Document(...), 0.95), (Document(...), 0.87), ...] > ``` > > ### Score Normalization > > Scores are normalized to \[0, 1] range where: > > * **1.0** = Perfect match > * **0.0** = Worst match > > The normalization depends on the distance metric used. > > *** > > ## Async Support > > All methods have async variants prefixed with `a`: > > | Sync Method | Async Method | > | - | - | > | `add_texts` | `aadd_texts` | > | `add_documents` | `aadd_documents` | > | `similarity_search` | `asimilarity_search` | > | `similarity_search_with_score` | `asimilarity_search_with_score` | > | `similarity_search_by_vector` | `asimilarity_search_by_vector` | > | `max_marginal_relevance_search` | `amax_marginal_relevance_search` | > | `delete` | `adelete` | > > ### Example Usage > > ```python theme={null} > import asyncio > > async def main(): > # Async text addition > ids = await store.aadd_texts(["async text 1", "async text 2"]) > > # Async search > docs = await store.asimilarity_search("query", k=5) > > # Async deletion > success = await store.adelete(ids) > > asyncio.run(main()) > ``` > [tab] Python SDK > > ## Connection Configuration > > The Python SDK connects to a running CyborgDB service instead of using a `StorageConfig`. > > | Parameter | Type | Default | Description | > | - | - | - | - | > | `base_url` | `str` | - | Base URL of the CyborgDB microservice endpoint | > | `api_key` | `str` | - | API key for authentication with the microservice | > | `verify_ssl` | `bool` | `None` | *(Optional)* SSL verification. When `None`, automatically disabled for `localhost` and `http://` URLs | > > > [!NOTE] > > > > `StorageConfig` and `GPUConfig` are not applicable to the Python SDK. Storage configuration is managed by the CyborgDB service. > > ### Example Usage > > ```python theme={null} > from cyborgdb.integrations.langchain import CyborgVectorStore > > store = CyborgVectorStore( > index_name="my_documents", > index_key=key, > api_key="your-api-key", > embedding="all-MiniLM-L6-v2", > base_url="http://localhost:8000" > ) > ``` > > *** > > ## Embeddings > > The Python SDK supports the same embedding types as the Embedded library: > > | Type | Description | Example | > | - | - | - | > | `str` | Model name string for SentenceTransformers | `"sentence-transformers/all-MiniLM-L6-v2"` | > | `SentenceTransformer` | SentenceTransformer model instance | `SentenceTransformer("all-MiniLM-L6-v2")` | > | `Embeddings` | Any LangChain Embeddings implementation | `OpenAIEmbeddings()`, `HuggingFaceEmbeddings()` | > > *** > > ## DistanceMetric > > Same as Embedded: > > * `"cosine"`: Cosine similarity (recommended for normalized embeddings) > * `"euclidean"`: Euclidean distance > * `"squared_euclidean"`: Squared Euclidean distance > > | Metric | Range | Best Match | Use Case | > | - | - | - | - | > | `cosine` | \[0, 2] | 0 | Text embeddings, normalized vectors | > | `euclidean` | \[0, ∞) | 0 | Raw feature vectors | > | `squared_euclidean` | \[0, ∞) | 0 | When avoiding sqrt computation | > > *** > > ## Document > > LangChain Document object used for storing text with metadata. > > | Attribute | Type | Description | > | - | - | - | > | `page_content` | `str` | The text content of the document | > | `metadata` | `dict` | Optional metadata associated with the document | > > ```python theme={null} > from langchain_core.documents import Document > > doc = Document( > page_content="This is the content of my document", > metadata={"source": "manual", "author": "John Doe"} > ) > ``` > > *** > > ## Filter Format > > Same filter format as Embedded. Metadata filters use a dictionary format: > > ```python theme={null} > # Exact match > filter = {"category": "technology"} > > # Range queries > filter = {"price": {"$gte": 100, "$lte": 500}} > > # IN queries > filter = {"tags": {"$in": ["python", "machine-learning"]}} > ``` > > Supported operators: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin` > > *** > > ## Return Types > > Same as Embedded: > > ```python theme={null} > # similarity_search returns List[Document] > docs = store.similarity_search("query", k=5) > > # similarity_search_with_score returns List[Tuple[Document, float]] > results = store.similarity_search_with_score("query", k=5) > ``` > > *** > > ## Async Support > > Same async variants as Embedded, prefixed with `a`: > > | Sync Method | Async Method | > | - | - | > | `add_texts` | `aadd_texts` | > | `add_documents` | `aadd_documents` | > | `similarity_search` | `asimilarity_search` | > | `similarity_search_with_score` | `asimilarity_search_with_score` | > | `similarity_search_by_vector` | `asimilarity_search_by_vector` | > | `delete` | `adelete` | > [tab] JS/TS > > ## CyborgVectorStoreConfig > > Configuration interface for constructing a `CyborgVectorStore` in JavaScript/TypeScript. > > ```typescript theme={null} > interface CyborgVectorStoreConfig { > baseUrl: string; > apiKey: string; > indexName: string; > indexKey: Uint8Array; > dimension?: number; > metric?: "cosine" | "euclidean" | "squared_euclidean"; > verifySsl?: boolean; > } > ``` > > | Parameter | Type | Default | Description | > | - | - | - | - | > | `baseUrl` | `string` | - | Base URL of the CyborgDB microservice endpoint | > | `apiKey` | `string` | - | API key for authentication | > | `indexName` | `string` | - | Name of the index | > | `indexKey` | `Uint8Array` | - | 32-byte encryption key | > | `dimension` | `number` | - | *(Optional)* Embedding dimension (auto-inferred if not provided) | > | `metric` | `string` | `"cosine"` | *(Optional)* Distance metric | > | `verifySsl` | `boolean` | `true` | *(Optional)* SSL verification | > > > [!NOTE] > > > > All parameters use camelCase convention, consistent with JavaScript/TypeScript standards. > > *** > > ## EmbeddingsInterface > > The JS/TS SDK accepts any LangChain `EmbeddingsInterface` implementation: > > ```typescript theme={null} > import { OpenAIEmbeddings } from '@langchain/openai'; > import { HuggingFaceTransformersEmbeddings } from '@langchain/community/embeddings/hf_transformers'; > > // OpenAI embeddings > const embeddings = new OpenAIEmbeddings(); > > // HuggingFace embeddings > const embeddings = new HuggingFaceTransformersEmbeddings({ > model: "all-MiniLM-L6-v2" > }); > ``` > > > [!NOTE] > > > > Unlike the Python SDKs, the JS/TS SDK does not accept raw model name strings. You must pass a LangChain `EmbeddingsInterface` instance. > > *** > > ## DistanceMetric > > Same options as Python SDKs: > > * `"cosine"`: Cosine similarity (recommended for normalized embeddings) > * `"euclidean"`: Euclidean distance > * `"squared_euclidean"`: Squared Euclidean distance > > *** > > ## Document > > LangChain `Document` object: > > ```typescript theme={null} > import { Document } from '@langchain/core/documents'; > > const doc = new Document({ > pageContent: "This is the content of my document", > metadata: { source: "manual", author: "John Doe" } > }); > ``` > > | Attribute | Type | Description | > | - | - | - | > | `pageContent` | `string` | The text content of the document | > | `metadata` | `Record` | Optional metadata associated with the document | > > *** > > ## FilterType > > Metadata filters use an object format: > > ```typescript theme={null} > // Exact match > const filter = { category: "technology" }; > > // Multiple conditions (AND) > const filter = { > category: "technology", > year: 2024 > }; > ``` > > Supports the same operators as the Python SDKs: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`. > > *** > > ## Return Types > > ```typescript theme={null} > // similaritySearch returns Promise > const docs = await store.similaritySearch("query", 5); > > // similaritySearchWithScore returns Promise<[Document, number][]> > const results = await store.similaritySearchWithScore("query", 5); > ``` > > *** > > ## Async > > > [!NOTE] > > > > All JS/TS methods are natively async and return `Promise<...>`. There are no separate sync/async variants — every method uses `await`. # Client Source: https://docs.cyborg.co/versions/latest/service/go-sdk/client/client `Client` is the entry point of the CyborgDB Go SDK. It connects to a running CyborgDB service and creates, loads, and lists encrypted indexes. Operations on an index, such as upsert and query, are methods of the `*EncryptedIndex` it returns. Every method that calls the service takes a `context.Context` first. ## Constructor ```go theme={null} func NewClient(baseURL, apiKey string, verifySSL ...bool) (*Client, error) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `baseURL` | `string` | - | Base URL of the CyborgDB service, e.g. `"http://localhost:8000"`. Must use `http` or `https` and have a host. | | `apiKey` | `string` | - | Service authentication credential, sent as the `X-API-Key` header. Pass `""` when the service runs without authentication. | | `verifySSL` | `...bool` | auto-detect | *(Optional)* TLS certificate verification. Only the first value is used. See [TLS verification](#tls-verification). | > [!NOTE] > > `apiKey` is the service **authentication** credential: the root key or a per-user `cdbk_` token. It is required only when the service runs with `CYBORGDB_SERVICE_ROOT_KEY` set; against an unauthenticated service (the default), pass `""`. This is distinct from the service's `CYBORGDB_API_KEY` license key. See [Managing Keys](../../guides/advanced/managing-keys). `NewClient` returns a `*ValidationError` wrapping `ErrInvalidURL` if `baseURL` has no `http`/`https` scheme or no host, e.g. `"localhost:8000"`. A path in `baseURL` is kept as a prefix, so `https://example.com/cyborgdb` sends requests to `https://example.com/cyborgdb/v1/...`. ### Example Usage ```go theme={null} package main import ( "context" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } health, err := client.GetHealth(context.Background()) if err != nil { log.Fatal(err) } fmt.Println(health["status"]) // Output: healthy } ``` ## TLS verification `verifySSL` decides whether the SDK checks the service's TLS certificate: | `baseURL` | `verifySSL` omitted | `true` | `false` | | - | - | - | - | | `http://…` | No TLS | No TLS | No TLS | | `https://` with host `localhost`, `127.0.0.1`, or `::1` | Verification **off** | Verification on | Verification off | | Any other `https://` URL | Verification on | Verification on | Verification off | ## Errors and timeouts Failed requests return errors that wrap a typed error chosen by HTTP status, such as `*NotFoundError` for `404`; arguments the SDK rejects before sending return a `*ValidationError`. See [Errors](../errors). Bound each call with a context deadline: ```go theme={null} ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() indexes, err := client.ListIndexes(ctx) if err != nil { log.Fatal(err) } fmt.Println(indexes) ``` # Create Index Source: https://docs.cyborg.co/versions/latest/service/go-sdk/client/create-index Creates a new encrypted index on the service and returns an `*EncryptedIndex` bound to it. ```go theme={null} func (c *Client) CreateIndex(ctx context.Context, params *CreateIndexParams) (*EncryptedIndex, error) ``` > [!NOTE] > > There is one index type, configured with flat fields. The earlier `IndexIVFFlat`, `IndexIVFPQ`, and `IndexIVFSQ` helpers and the `IndexConfig` field no longer exist. ### Parameters | Parameter | Type | Description | | - | - | - | | `ctx` | `context.Context` | Context for cancellation and deadlines. | | `params` | `*CreateIndexParams` | Index settings. A `nil` pointer returns a `*ValidationError` wrapping `ErrNilParams`. | #### CreateIndexParams Optional scalar fields are pointers: leave them `nil` to use the service default, or set them with the `cyborgdb.Int32`, `cyborgdb.String`, `cyborgdb.Float64`, and `cyborgdb.Bool` helpers. | Field | Type | Default | Description | | - | - | - | - | | `IndexName` | `string` | - | Unique name for the index. | | `IndexKey` | `[]byte` | `nil` | 32-byte encryption key (SDK-supplied KEK). Set either `IndexKey` or `KmsName`, never both. | | `KmsName` | `*string` | `nil` | Name of a `kms.registry` entry in the service YAML. The service generates the KEK and wraps it with that provider; the SDK never sees the plaintext key. | | `Dimension` | `*int32` | `nil` | Vector dimensionality. When `nil`, the service detects it from the first upsert. | | `Metric` | `*string` | `nil` (service default: `"euclidean"`) | `"euclidean"`, `"squared_euclidean"`, or `"cosine"`. | | `EmbeddingModel` | `*string` | `nil` | Name of one of the service's built-in embedding models (listed by `GET /v1/embedding-models`), used for automatic embedding generation. When set, `Dimension` is taken from the model. | | `StoragePrecision` | `*string` | `nil` (service default: `"float32"`) | Storage format for the index's stored vector embeddings. See [Storage precision](#storage-precision). | | `MetadataSchema` | `map[string]MetadataFieldPolicy` | `nil` | Per-field metadata indexing policy. Fixed at creation and cannot be changed later. See [Metadata schema](#metadata-schema). | | `TextFields` | `[]string` | `nil` | Metadata fields to index for BM25 full-text search. Shorthand for `FullText: true` in `MetadataSchema`. Enables `Text` on [`Query`](../encrypted-index/query) and [`QueryMetadata`](../encrypted-index/query-metadata). | | `Bm25K1` | `*float64` | `nil` (service default: `1.2`) | BM25 term-frequency saturation, `>= 0`. Requires at least one full-text field. | | `Bm25B` | `*float64` | `nil` (service default: `0.75`) | BM25 length-normalization strength, in `[0, 1]`. Requires at least one full-text field. | ### Key management Set exactly one of `IndexKey` or `KmsName`. The service rejects both together with a `*ValidationError` (HTTP `400`), whatever the KMS provider. * **SDK-supplied KEK:** set `IndexKey`. Pass the same key again on every [`LoadIndex`](./load-index). * **KMS-backed:** set `KmsName`. The service generates the key, wraps it with the named provider, and stores the wrapped key. Later calls pass a `nil` key. ### Storage precision `StoragePrecision` sets the format used to store the index's vector embeddings. Every value works with every metric. | Constant | Value | Bits per dimension | | - | - | - | | `StoragePrecisionFloat32` | `"float32"` | 32 | | `StoragePrecisionFloat16` | `"float16"` | 16 | | `StoragePrecisionTQ12` | `"tq12"` | 12 | | `StoragePrecisionTQ8` | `"tq8"` | 8 | | `StoragePrecisionTQ6` | `"tq6"` | 6 | | `StoragePrecisionTQ4` | `"tq4"` | 4 | The `tq*` values are TurboQuant tiers; lower tiers use less storage in exchange for a small recall and latency cost. ### Metadata schema `MetadataSchema` sets how each metadata field is indexed. Metadata itself stays schemaless: this controls indexing, not what may be stored. Fields left out get the default policy (indexed and filterable). Nested fields use dot-paths such as `"loc.city"`. `MetadataFieldPolicy` has three `*bool` fields; `nil` means the default: | Field | Default | Effect | | - | - | - | | `Filterable` | `true` | Indexes the field, so filters on it resolve from the index. `false` still stores the field but doesn't index it; see [Filters the index cannot answer](#filters-the-index-cannot-answer). | | `Pattern` | `false` | Also builds a regex dictionary, so `$regex` and `$contains` resolve from the index. Requires `Filterable` `true`. | | `FullText` | `false` | Sends the field's text through the BM25 analyzer instead of exact-match indexing. Implies `Filterable` `false`, and can't be combined with `Pattern` `true`. | #### Filters the index cannot answer The index can answer a filter when the field is filterable and, for `$regex` or `$contains`, the field also has `pattern` set. Any other filter is handled differently depending on the call: | Call | Filter the index can't answer | | - | - | | [`Query`](../encrypted-index/query) without `text` | Still works, but slower: the filter is applied to the decrypted metadata after the search. | | [`Query`](../encrypted-index/query) with `text` | Rejected with a `*ValidationError`. | | [`QueryMetadata`](../encrypted-index/query-metadata) | Rejected with a `*ValidationError`. | With the schema from the [per-field example](#per-field-metadata-policy) below: ```go theme={null} map[string]interface{}{"title": map[string]interface{}{"$regex": "^Intro"}} // answerable: title is filterable and has Pattern map[string]interface{}{"internal_blob": "abc"} // not answerable: internal_blob isn't filterable map[string]interface{}{"author": map[string]interface{}{"$regex": "^Ann"}} // not answerable: author is filterable by default, but has no Pattern ``` The stored policy is returned by the [`MetadataSchema`](../getters#metadataschema) getter. ### Returns The `*EncryptedIndex` bound to the new index. For KMS-backed indexes it holds no plaintext key. ### Errors > [accordion] \*ValidationError > > * Wraps `ErrNilParams`, `ErrMissingKeyOrKMS`, or `ErrInvalidKeyLength`. `params` is `nil`, neither `IndexKey` nor `KmsName` is set, or `IndexKey` isn't 32 bytes. Returned before any request is sent. > * The service rejects the request (HTTP `400`/`422`): the index name already exists, both `IndexKey` and `KmsName` are set, the `KmsName` slot is unknown, `StoragePrecision` isn't one of the six values, or `MetadataSchema` combines settings that aren't allowed. > [accordion] \*AuthenticationError > > The client's `apiKey` is missing or invalid (HTTP `401`), or is a per-user key: creating an index requires the root key (HTTP `403`). > [accordion] \*ServiceError > > The service returns `5xx`, including KMS wrap failures (`502`). > [accordion] \*TransportError > > The service can't be reached. See [Errors](../errors). ### Example Usage #### SDK-supplied key ```go theme={null} package main import ( "context" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } key, err := cyborgdb.GenerateKey() if err != nil { log.Fatal(err) } // The dimension is detected from the first upsert index, err := client.CreateIndex(context.Background(), &cyborgdb.CreateIndexParams{ IndexName: "documents", IndexKey: key, }) if err != nil { log.Fatal(err) } fmt.Println(index.GetIndexName()) // Output: documents } ``` > [!NOTE] > > Store the key securely: it is needed to load the index again. See [Generate Key](./generate-key). #### Explicit dimension and metric ```go theme={null} dimension := int32(384) metric := "cosine" index, err := client.CreateIndex(ctx, &cyborgdb.CreateIndexParams{ IndexName: "documents-384", IndexKey: key, Dimension: &dimension, Metric: &metric, }) if err != nil { log.Fatal(err) } _ = index ``` #### KMS-backed index ```go theme={null} // The service generates the key and wraps it with the "prod-aws" registry slot. kmsName := "prod-aws" dimension := int32(384) index, err := client.CreateIndex(ctx, &cyborgdb.CreateIndexParams{ IndexName: "kms-documents", KmsName: &kmsName, Dimension: &dimension, }) if err != nil { log.Fatal(err) } _ = index // Later calls, including LoadIndex, pass a nil key. ``` #### Automatic embeddings ```go theme={null} // The dimension is taken from the embedding model model := "all-MiniLM-L6-v2" index, err := client.CreateIndex(ctx, &cyborgdb.CreateIndexParams{ IndexName: "semantic-docs", IndexKey: key, EmbeddingModel: &model, }) if err != nil { log.Fatal(err) } _ = index ``` See [Auto-Generate Embeddings](../../guides/data-operations/add-items#automatic-embedding-generation). #### Reduced storage with TurboQuant ```go theme={null} dimension := int32(768) precision := cyborgdb.StoragePrecisionTQ8 index, err := client.CreateIndex(ctx, &cyborgdb.CreateIndexParams{ IndexName: "compact-docs", IndexKey: key, Dimension: &dimension, StoragePrecision: &precision, }) if err != nil { log.Fatal(err) } _ = index ``` #### Per-field metadata policy ```go theme={null} index, err := client.CreateIndex(ctx, &cyborgdb.CreateIndexParams{ IndexName: "docs-index", IndexKey: key, Dimension: cyborgdb.Int32(4), MetadataSchema: map[string]cyborgdb.MetadataFieldPolicy{ "title": {Filterable: cyborgdb.Bool(true), Pattern: cyborgdb.Bool(true)}, "internal_blob": {Filterable: cyborgdb.Bool(false)}, }, }) if err != nil { log.Fatal(err) } err = index.Upsert(ctx, cyborgdb.VectorItems{ {Id: "doc1", Vector: []float32{0.1, 0.2, 0.3, 0.4}, Metadata: map[string]interface{}{"title": "intro to encryption"}}, {Id: "doc2", Vector: []float32{0.5, 0.6, 0.7, 0.8}, Metadata: map[string]interface{}{"title": "advanced setup"}}, }) if err != nil { log.Fatal(err) } // $regex resolves from the index because "title" has Pattern set res, err := index.QueryMetadata(ctx, cyborgdb.QueryMetadataParams{ Filters: map[string]interface{}{"title": map[string]interface{}{"$regex": "^intro"}}, }) if err != nil { log.Fatal(err) } fmt.Println(res.Ids) // Output: [doc1] ``` #### Full-text search fields ```go theme={null} dimension := int32(4) index, err := client.CreateIndex(ctx, &cyborgdb.CreateIndexParams{ IndexName: "articles", IndexKey: key, Dimension: &dimension, TextFields: []string{"body"}, }) if err != nil { log.Fatal(err) } bm25, err := index.BM25(ctx) if err != nil { log.Fatal(err) } fmt.Println(bm25.K1, bm25.B, bm25.GetAnalyzerVersion()) // Output: 1.2 0.75 en/1;sw=2de831ef7be676b6;snowball-english-utf8-3.0.1 ``` # Generate Key Source: https://docs.cyborg.co/versions/latest/service/go-sdk/client/generate-key Generates a random 32-byte (256-bit) key for creating an encrypted index with an SDK-supplied key. ```go theme={null} func GenerateKey() ([]byte, error) ``` `GenerateKey` is a package-level function, not a `Client` method. The package also exports the key length as `cyborgdb.KeySize` (`32`). ### Returns A 32-byte key read from Go's `crypto/rand`. The error, which wraps `ErrKeyGeneration`, is non-nil only if the operating system's random source fails. Unlike the Python SDK, there is no option to save the key to a file. > [!WARNING] > > An index created with an SDK-supplied key can only be opened with that exact key. If the key is lost, the index's data can't be decrypted. Store it in a secrets manager, or use a KMS-backed index. See [Managing Encryption Keys](../../guides/advanced/managing-keys). ### Example Usage ```go theme={null} package main import ( "context" "encoding/hex" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } key, err := cyborgdb.GenerateKey() if err != nil { log.Fatal(err) } fmt.Println(len(key)) // Output: 32 _, err = client.CreateIndex(context.Background(), &cyborgdb.CreateIndexParams{ IndexName: "my-secure-index", IndexKey: key, }) if err != nil { log.Fatal(err) } // Keep the key somewhere safe, e.g. as hex in a secrets manager keyHex := hex.EncodeToString(key) _ = keyHex } ``` # Get Health Source: https://docs.cyborg.co/versions/latest/service/go-sdk/client/get-health Returns the health status of the CyborgDB service, to check that it is reachable and running. ```go theme={null} func (c *Client) GetHealth(ctx context.Context) (map[string]string, error) ``` ### Returns A `map[string]string` with these keys: | Key | Description | | - | - | | `status` | Service health, `"healthy"` when the service is up. | | `api_version` | REST API version, e.g. `"v1"`. | | `version` | CyborgDB service version. | ### Errors > [accordion] \*TransportError > > The service can't be reached. > [accordion] \*ServiceError > > The service returns `5xx`. See [Errors](../errors). ### Example Usage ```go theme={null} package main import ( "context" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } health, err := client.GetHealth(context.Background()) if err != nil { log.Fatal(err) } fmt.Println(health) // Output: map[api_version:v1 status:healthy version:0.18.0] } ``` # List Indexes Source: https://docs.cyborg.co/versions/latest/service/go-sdk/client/list-indexes Returns the names of all indexes on the CyborgDB service. ```go theme={null} func (c *Client) ListIndexes(ctx context.Context) ([]string, error) ``` ### Returns A `[]string` of index names. Empty when the service has no indexes. ### Errors > [accordion] \*AuthenticationError > > The client's `apiKey` is missing or invalid (HTTP `401`), or is a per-user key: listing indexes requires the root key (HTTP `403`). > [accordion] \*ServiceError > > The service returns `5xx`. > [accordion] \*TransportError > > The service can't be reached. See [Errors](../errors). ### Example Usage ```go theme={null} package main import ( "context" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } indexes, err := client.ListIndexes(context.Background()) if err != nil { log.Fatal(err) } fmt.Println(indexes) // Output: [documents embeddings semantic-search] } ``` # Load Index Source: https://docs.cyborg.co/versions/latest/service/go-sdk/client/load-index Loads an existing encrypted index and returns an `*EncryptedIndex` bound to it. ```go theme={null} func (c *Client) LoadIndex(ctx context.Context, indexName string, indexKey []byte) (*EncryptedIndex, error) ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `ctx` | `context.Context` | Context for cancellation and deadlines. | | `indexName` | `string` | Name of an existing index. | | `indexKey` | `[]byte` | The 32-byte key the index was created with. Required for SDK-supplied-key indexes; pass `nil` for KMS-backed indexes (created with `KmsName`). | > [!WARNING] > > For SDK-supplied-key indexes, `indexKey` must be the exact key passed to `CreateIndex`. A KMS-backed index fails to load if its `KmsName` slot is missing from the service YAML or its provider is unreachable, with `*AuthenticationError` (HTTP `401`). ### Returns The `*EncryptedIndex` bound to the loaded index. ### Errors > [accordion] \*ValidationError > > Wraps `ErrInvalidKeyLength`. `indexKey` is non-empty but not 32 bytes. Returned before any request is sent. > [accordion] \*NotFoundError > > No index named `indexName` exists, or `indexKey` doesn't match (HTTP `404`, in most cases). > [accordion] \*AuthenticationError > > `indexKey` doesn't match an index that has vectors and is already in the service's cache, or the client's `apiKey` is missing or invalid; or, for a KMS-backed index, its KMS slot is missing or the provider call fails (HTTP `401`). > [accordion] \*ServiceError > > The service returns `5xx`. > [accordion] \*TransportError > > The service can't be reached. See [Errors](../errors). > [!NOTE] > > A wrong key returns `*AuthenticationError` (HTTP `401`) when the index has vectors and the service already has it cached, and `*NotFoundError` (HTTP `404`) otherwise, for example on an empty index or right after the service restarts. Catch both when checking for a bad key. ### Example Usage #### SDK-supplied-key index ```go theme={null} package main import ( "context" "encoding/hex" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } // The same 32 bytes that were passed to CreateIndex, e.g. stored as hex key, err := hex.DecodeString("your-64-character-hex-key") if err != nil { log.Fatal(err) } index, err := client.LoadIndex(context.Background(), "my-index", key) if err != nil { log.Fatal(err) } fmt.Println(index.GetIndexName()) // Output: my-index } ``` #### KMS-backed index ```go theme={null} // No key needed: the service unwraps it with the index's KMS provider. index, err := client.LoadIndex(ctx, "kms-index", nil) if err != nil { log.Fatal(err) } _ = index ``` # Delete Source: https://docs.cyborg.co/versions/latest/service/go-sdk/encrypted-index/delete Permanently removes items from the index by ID, along with their contents and metadata. ```go theme={null} func (e *EncryptedIndex) Delete(ctx context.Context, ids []string) error ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `ctx` | `context.Context` | Context for cancellation and deadlines. | | `ids` | `[]string` | IDs of the items to delete. An empty slice is a no-op. | ### Returns `error` only; `nil` on success. ### Errors > [accordion] \*AuthenticationError > > The `apiKey` is invalid, or a read-only user key is used (HTTP `401`/`403`). > [accordion] \*ServiceError / \*TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors). ### Example Usage ```go theme={null} if err := index.Delete(ctx, []string{"doc1", "doc2"}); err != nil { log.Fatal(err) } ids, err := index.ListIDs(ctx) if err != nil { log.Fatal(err) } fmt.Println(ids.Ids) // Output: [doc3] ``` # Delete Index Source: https://docs.cyborg.co/versions/latest/service/go-sdk/encrypted-index/delete-index > [!WARNING] > > Deleting an index is irreversible. Deletes the index and all of its data from the CyborgDB service. ```go theme={null} func (e *EncryptedIndex) DeleteIndex(ctx context.Context) error ``` ### Returns `error` only; `nil` on success. ### Errors > [accordion] \*NotFoundError > > The index doesn't exist, for example because it was already deleted (HTTP `404`). > [accordion] \*AuthenticationError > > The `apiKey` is invalid (HTTP `401`), or the client is using a per-user key: deleting an index requires the root key (HTTP `403`). > [accordion] \*ServiceError / \*TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors). ### Example Usage ```go theme={null} if err := index.DeleteIndex(ctx); err != nil { log.Fatal(err) } names, err := client.ListIndexes(ctx) if err != nil { log.Fatal(err) } fmt.Println(slices.Contains(names, index.GetIndexName())) // Output: false ``` # Get Source: https://docs.cyborg.co/versions/latest/service/go-sdk/encrypted-index/get Retrieves items from the index by ID, with the fields you choose. ```go theme={null} func (e *EncryptedIndex) Get(ctx context.Context, ids []string, include []string) (*GetResponse, error) ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `ctx` | `context.Context` | Context for cancellation and deadlines. | | `ids` | `[]string` | IDs of the items to retrieve. | | `include` | `[]string` | Fields to return besides the ID. `nil` uses the service default, `{"vector", "contents", "metadata"}`. | ### Returns `*GetResponse`, whose `Results` has one entry per ID found. IDs that don't exist are left out without an error, and an empty `ids` slice returns no results. When `include` doesn't contain `"vector"`, an existing item that has none of the requested fields is also left out. | Field / method | Description | | - | - | | `Id string` | Always set. | | `Vector []float32` | When `"vector"` is in `include`. | | `GetContents() string` | When `"contents"` is in `include`. `""` if the item has no contents. | | `Metadata map[string]interface{}` | When `"metadata"` is in `include`. Numbers decode as `float64`. | ### Errors > [accordion] \*AuthenticationError > > The `apiKey` is invalid (HTTP `401`). > [accordion] \*ServiceError / \*TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors). ### Example Usage ```go theme={null} res, err := index.Get(ctx, []string{"doc1", "doc2", "missing-id"}, []string{"contents", "metadata"}) if err != nil { log.Fatal(err) } for _, item := range res.Results { fmt.Printf("%s %q %v\n", item.Id, item.GetContents(), item.Metadata) } // Output: // doc1 "First document" map[] // doc2 "" map[category:news] ``` # List IDs Source: https://docs.cyborg.co/versions/latest/service/go-sdk/encrypted-index/list-ids Returns every item ID in the index. ```go theme={null} func (e *EncryptedIndex) ListIDs(ctx context.Context) (*ListIDsResponse, error) ``` ### Returns `*ListIDsResponse` with `Ids []string` (all IDs in the index) and `Count int32`. ### Errors > [accordion] \*AuthenticationError > > The `apiKey` is invalid (HTTP `401`). > [accordion] \*ServiceError / \*TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors). ### Example Usage ```go theme={null} res, err := index.ListIDs(ctx) if err != nil { log.Fatal(err) } fmt.Println(res.Count, slices.Contains(res.Ids, "doc1")) // Output: 3 true // Fetch items in batches of 100 for i := 0; i < len(res.Ids); i += 100 { batch, err := index.Get(ctx, res.Ids[i:min(i+100, len(res.Ids))], nil) if err != nil { log.Fatal(err) } _ = batch } ``` # Query Source: https://docs.cyborg.co/versions/latest/service/go-sdk/encrypted-index/query Finds the nearest neighbors of one or more query vectors. With `QueryContents`, the service embeds the text first (the index needs an `EmbeddingModel`). With `Text`, the query becomes **hybrid**: BM25 full-text ranking is fused with the vector ranking. ```go theme={null} func (e *EncryptedIndex) Query(ctx context.Context, input QueryInput) (*QueryResponse, error) ``` `input` is either `QueryParams` (sent as JSON) or `BinaryQueryParams` (vectors sent as binary, faster for large batches). ### Parameters #### QueryParams Optional scalar fields are pointers: leave them `nil` to use the service default. | Field | Type | Default | Description | | - | - | - | - | | `QueryVector` | `[]float32` | `nil` | One query vector. | | `BatchQueryVectors` | `[][]float32` | `nil` | A batch of query vectors. Takes precedence over `QueryVector`. | | `QueryContents` | `*string` | `nil` | Text for the service to embed and search with. Requires an index created with `EmbeddingModel`. | | `TopK` | `int32` | `0` (service default: `100`) | Results to return per query. `0` means the service default. | | `NProbes` | `*int32` | `nil` (service default: auto) | Clusters to probe. Higher values improve recall and add latency. | | `Filters` | `map[string]interface{}` | `nil` | Metadata filter. See [Metadata filtering](../types#metadata-filtering). | | `Include` | `[]string` | `nil` (service default: `[]`) | Extra fields per result: `"distance"` and `"metadata"`. `Id` is always returned. See [Result fields](#result-fields). | | `Greedy` | `*bool` | `nil` (service default: `false`) | Use greedy search. | | `RerankMult` | `*int32` | `nil` (service default: `50`) | Stage 1 returns `TopK * RerankMult` candidates before reranking narrows them to `TopK`. | | `Text` | `*string` | `nil` | Query text for a BM25 leg, which makes the query hybrid. Requires an index with at least one full-text field. A query vector is still required. | | `TextFields` | `[]string` | `nil` (all full-text fields) | Full-text fields the BM25 leg searches. | | `TextFieldWeights` | `[]float32` | `nil` (`1.0` each) | Weight per searched field, in the same order as `TextFields`. | | `RequireAllTerms` | `*bool` | `nil` (service default: `false`) | Match only items containing every query term (AND) instead of any term (OR). | | `Alpha` | `*float64` | `nil` (service default: `0.5`) | Blend of the two legs, in `[0, 1]`: `0` is pure BM25, `1` is pure vector. | | `RrfK` | `*float64` | `nil` (service default: `60`) | Reciprocal rank fusion smoothing constant. Must be `> 0`. | | `WindowMult` | `*int32` | `nil` (service default: `3`) | Candidates retrieved per leg, as a multiple of `TopK`. Must be `>= 1`. | #### BinaryQueryParams The same fields as `QueryParams`, except: * `QueryVectors [][]float32` replaces `QueryVector` and `BatchQueryVectors`. * There is no `QueryContents`. ### Returns `*QueryResponse`, whose `Results` holds exactly one of: * `Results.ArrayOfQueryResultItem` (`*[]QueryResultItem`): one query vector. * `Results.ArrayOfArrayOfQueryResultItem` (`*[][]QueryResultItem`): two or more query vectors. A query with exactly one vector always returns single results, even when it's sent as a batch or through the binary path. #### Result fields | Field / method | Description | | - | - | | `Id string` | Always set. | | `GetDistance()`, `HasDistance()` | Vector queries, when `"distance"` is in `Include`. Lower is closer. | | `GetScore()`, `HasScore()` | Hybrid queries only, instead of distance. Higher is more relevant. | | `Metadata map[string]interface{}` | When `"metadata"` is in `Include`. | `Query` never returns vectors or contents, even when they're listed in `Include`. To read them, pass the result IDs to [`Get`](./get). ### Errors > [accordion] \*ValidationError > > * Wraps `ErrEmptyQueryVectors`, `ErrInconsistentDimension`, or `ErrUnsupportedQueryType`. A `BinaryQueryParams` has no vectors or vectors of different lengths, or `input` is another type. Returned before any request is sent. > * The service rejects the query (HTTP `400`/`422`): no query input, wrong vector dimension, `Text` on an index without full-text fields, or an out-of-range `Alpha`, `RrfK`, or `WindowMult`. Other numeric parameters aren't range-checked. > [accordion] \*AuthenticationError > > The `apiKey` is invalid (HTTP `401`). > [accordion] \*ServiceError / \*TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors). ### Example Usage #### Single vector ```go theme={null} resp, err := index.Query(ctx, cyborgdb.QueryParams{ QueryVector: []float32{0.1, 0.2, 0.3, 0.4}, TopK: 2, Include: []string{"distance", "metadata"}, }) if err != nil { log.Fatal(err) } for _, r := range *resp.Results.ArrayOfQueryResultItem { fmt.Printf("%s %.4f %v\n", r.Id, r.GetDistance(), r.Metadata) } // Output: // doc1 0.0000 map[category:news] // doc2 0.8000 map[category:research] ``` #### Batch of vectors ```go theme={null} resp, err := index.Query(ctx, cyborgdb.QueryParams{ BatchQueryVectors: [][]float32{ {0.1, 0.2, 0.3, 0.4}, {0.5, 0.6, 0.7, 0.8}, }, TopK: 1, }) if err != nil { log.Fatal(err) } for i, results := range *resp.Results.ArrayOfArrayOfQueryResultItem { fmt.Println(i, results[0].Id) } // Output: // 0 doc1 // 1 doc2 ``` #### BinaryQueryParams ```go theme={null} resp, err := index.Query(ctx, cyborgdb.BinaryQueryParams{ QueryVectors: [][]float32{ {0.1, 0.2, 0.3, 0.4}, {0.5, 0.6, 0.7, 0.8}, }, TopK: 1, }) if err != nil { log.Fatal(err) } fmt.Println(len(*resp.Results.ArrayOfArrayOfQueryResultItem)) // Output: 2 ``` #### Text, embedded by the service ```go theme={null} // The index must have been created with EmbeddingModel text := "machine learning in healthcare" resp, err := index.Query(ctx, cyborgdb.QueryParams{QueryContents: &text, TopK: 3}) if err != nil { log.Fatal(err) } for _, r := range *resp.Results.ArrayOfQueryResultItem { fmt.Println(r.Id) } ``` #### Hybrid (BM25 + vector) The index needs at least one full-text field, set with `TextFields` or `FullText` in [`CreateIndex`](../client/create-index#metadata-schema). ```go theme={null} text := "encrypted search" alpha := 0.5 resp, err := index.Query(ctx, cyborgdb.QueryParams{ QueryVector: []float32{0.1, 0.2, 0.3, 0.4}, Text: &text, Alpha: &alpha, TopK: 2, Include: []string{"metadata"}, }) if err != nil { log.Fatal(err) } for _, r := range *resp.Results.ArrayOfQueryResultItem { fmt.Printf("%s %.4f\n", r.Id, r.GetScore()) } // Output: // doc1 0.0164 // doc2 0.0161 ``` #### Filters and search options ```go theme={null} nProbes := int32(5) rerankMult := int32(20) greedy := true resp, err := index.Query(ctx, cyborgdb.QueryParams{ QueryVector: []float32{0.1, 0.2, 0.3, 0.4}, TopK: 20, NProbes: &nProbes, RerankMult: &rerankMult, Greedy: &greedy, Filters: map[string]interface{}{"category": "news"}, Include: []string{"distance", "metadata"}, }) if err != nil { log.Fatal(err) } for _, r := range *resp.Results.ArrayOfQueryResultItem { fmt.Println(r.Id, r.Metadata["category"]) } // Output: doc1 news ``` # Query Metadata Source: https://docs.cyborg.co/versions/latest/service/go-sdk/encrypted-index/query-metadata Finds items by metadata alone, with no query vector. `QueryMetadata` resolves the filter against the encrypted metadata index and returns the matching IDs. With `Text`, it also ranks matches by BM25 relevance. It works on untrained indexes. ```go theme={null} func (e *EncryptedIndex) QueryMetadata(ctx context.Context, params QueryMetadataParams) (*QueryMetadataResponse, error) ``` ### Parameters #### QueryMetadataParams | Field | Type | Default | Description | | - | - | - | - | | `Filters` | `map[string]interface{}` | `nil` | Metadata filter; `nil` or empty matches everything. See [Filter constraints](#filter-constraints). | | `TopK` | `int32` | `0` | Maximum results; `0` returns every match. Applied after `OrderBy`. | | `OrderBy` | `string` | `""` | Sort by a metadata field. `""` leaves results unordered. Can't be combined with `Text`. | | `Ascending` | `*bool` | `nil` (service default: ascending) | Sort direction when `OrderBy` is set: `cyborgdb.Bool(false)` for descending. Ignored when `OrderBy` is empty. | | `Text` | `*string` | `nil` | Query text for BM25 full-text ranking. Requires an index with at least one full-text field. Results then carry a score, sorted by relevance, and `Filters` act as a pre-filter. | | `TextFields` | `[]string` | `nil` (all full-text fields) | Full-text fields to search. | | `TextFieldWeights` | `[]float32` | `nil` (`1.0` each) | Weight per searched field, in the same order as `TextFields`. | | `RequireAllTerms` | `*bool` | `nil` (service default: `false`) | Match only items containing every query term. | > [!NOTE] > > * Without `OrderBy` or `Text`, results come back in no particular order. > * Items missing the `OrderBy` field, or holding a non-scalar value in it, sort last. ### Filter constraints [`Query`](./query) falls back to a post-filter over decrypted metadata when the index can't answer a filter, for pure vector queries. `QueryMetadata` has no fallback, so every filter must be answerable from the index. The index's [`MetadataSchema`](../client/create-index#metadata-schema) is therefore enforced here: * `$regex` and `$contains` need a field created with `Pattern` `true`. * A field created with `Filterable` `false` can't be filtered on. * `$type` isn't supported. Any of these returns a `*ValidationError` (HTTP `400`) with the reason. Nested dot-paths such as `"loc.city"` are supported. ### Returns `*QueryMetadataResponse`: | Field | Type | Description | | - | - | - | | `Results` | `[]MetadataResult` | One entry per match, with `Id` and, when `Text` is set, a score (`GetScore()`, `HasScore()`). Higher scores are more relevant. | | `Ids` | `[]string` | The same IDs, in the same order. | | `Count` | `int32` | Number of matches returned. | ### Errors > [accordion] \*ValidationError > > The service rejects the query (HTTP `400`): see [Filter constraints](#filter-constraints). > [accordion] \*AuthenticationError > > The `apiKey` is invalid (HTTP `401`). > [accordion] \*ServiceError / \*TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors). ### Example Usage #### Filter only ```go theme={null} res, err := index.QueryMetadata(ctx, cyborgdb.QueryMetadataParams{ Filters: map[string]interface{}{"label": "dog"}, }) if err != nil { log.Fatal(err) } ids := res.Ids sort.Strings(ids) // unordered without OrderBy fmt.Println(res.Count, ids) // Output: 2 [101 102] ``` #### Operators and a result cap ```go theme={null} res, err := index.QueryMetadata(ctx, cyborgdb.QueryMetadataParams{ Filters: map[string]interface{}{ "$and": []interface{}{ map[string]interface{}{"label": "cat"}, map[string]interface{}{"confidence": map[string]interface{}{"$gte": 0.9}}, }, }, TopK: 10, }) if err != nil { log.Fatal(err) } fmt.Println(res.Ids) // Output: [201] ``` #### Sorted by a field ```go theme={null} // Ascending by "views" (the default) asc, err := index.QueryMetadata(ctx, cyborgdb.QueryMetadataParams{ Filters: map[string]interface{}{"label": "dog"}, OrderBy: "views", }) if err != nil { log.Fatal(err) } // Descending by "views"; TopK applies after the sort desc, err := index.QueryMetadata(ctx, cyborgdb.QueryMetadataParams{ Filters: map[string]interface{}{"label": "dog"}, OrderBy: "views", Ascending: cyborgdb.Bool(false), TopK: 5, }) if err != nil { log.Fatal(err) } fmt.Println(asc.Ids, desc.Ids) // Output: [101 102] [102 101] ``` #### Regex match ```go theme={null} // "title" must have been created with Pattern set res, err := index.QueryMetadata(ctx, cyborgdb.QueryMetadataParams{ Filters: map[string]interface{}{"title": map[string]interface{}{"$regex": "^intro"}}, }) if err != nil { log.Fatal(err) } fmt.Println(res.Ids) // Output: [101] ``` #### Full-text search ```go theme={null} // The index needs a full-text field, e.g. CreateIndexParams{TextFields: []string{"body"}} text := "encrypted search" res, err := index.QueryMetadata(ctx, cyborgdb.QueryMetadataParams{Text: &text, TopK: 5}) if err != nil { log.Fatal(err) } for _, r := range res.Results { fmt.Printf("%s %.4f\n", r.Id, r.GetScore()) } ``` For filter syntax and operators, see [Metadata filtering](../types#metadata-filtering). # Train Source: https://docs.cyborg.co/versions/latest/service/go-sdk/encrypted-index/train Clusters the index's vectors into IVF lists so queries only scan the closest lists. `Train` waits until training finishes before returning. ```go theme={null} func (e *EncryptedIndex) Train(ctx context.Context, params TrainParams) error ``` > [!TIP] > > The service also trains indexes automatically. An untrained index is trained once it holds more than `AUTO_TRAIN_MIN_VECTORS` vectors (default `65536`), and a trained index is retrained when its size calls for more lists than it has. Set `AUTO_TRAIN_DISABLED=true` on the service to turn this off. Call `Train` yourself to train a smaller index, or to make sure training is finished before running queries or benchmarks. ### Parameters #### TrainParams All fields are pointers; `nil` uses the service default. Pass `cyborgdb.TrainParams{}` for all defaults. | Field | Type | Default | Description | | - | - | - | - | | `NLists` | `*int32` | `nil` (auto) | Number of IVF lists. When `nil`, the square root of the vector count, rounded to a power of two. | | `BatchSize` | `*int32` | `nil` (ignored) | Vectors processed per training batch. | | `MaxIters` | `*int32` | `nil` (ignored) | Maximum clustering iterations. | | `Tolerance` | `*float64` | `nil` (ignored) | Convergence tolerance. | | `MaxMemory` | `*int32` | `nil` (ignored) | Memory cap for training, in MB. | > [!WARNING] > > Only `NLists` affects training today. The service accepts `BatchSize`, `MaxIters`, `Tolerance`, and `MaxMemory` but doesn't pass them to training, so they have no effect. Parameter values aren't range-checked: an out-of-range value such as a negative list count is accepted, and training is skipped as described in [Requirements](#requirements). ### Requirements Training only runs when all three hold: * The index has at least **10,000 vectors**. * It has at least twice as many vectors as `NLists`. * The vector dimension is a **multiple of 32**, such as 384, 768, or 1536. > [!WARNING] > > `Train` doesn't report a skipped or failed training run. If a requirement isn't met, or training fails on the service, `Train` still returns `nil` and the index stays untrained. Check [`IsTrained`](../getters#istrained) after `Train` returns: an untrained index has `NLists` of `1`. Queries on an untrained index still work. ### Returns `error` only. If the index is already training, `Train` waits for that run to finish, then trains again. ### Errors > [accordion] \*AuthenticationError > > The client isn't using the root key (HTTP `401`/`403`). Training requires the root key. > [accordion] \*NotFoundError > > The index doesn't exist (HTTP `404`). A wrong key gives `*NotFoundError` or `*AuthenticationError`, as described in [Load Index](../client/load-index#errors). > [accordion] \*ServiceError / \*TransportError > > The service returns `5xx` or can't be reached. A failed training run doesn't return an error; see [Requirements](#requirements). See [Errors](../errors). ### Example Usage #### Default settings ```go theme={null} if err := index.Train(ctx, cyborgdb.TrainParams{}); err != nil { log.Fatal(err) } // Train doesn't return an error if training is skipped, so check the result trained, err := index.IsTrained(ctx) if err != nil { log.Fatal(err) } nLists, err := index.NLists(ctx) if err != nil { log.Fatal(err) } fmt.Println(trained, nLists) // Output: true 128 ``` #### Custom settings ```go theme={null} nLists := int32(128) batchSize := int32(4096) maxIters := int32(200) tolerance := 1e-7 err := index.Train(ctx, cyborgdb.TrainParams{ NLists: &nLists, BatchSize: &batchSize, MaxIters: &maxIters, Tolerance: &tolerance, }) if err != nil { log.Fatal(err) } ``` # Upsert Source: https://docs.cyborg.co/versions/latest/service/go-sdk/encrypted-index/upsert Adds vectors to the index, or replaces existing vectors with the same ID. `Upsert` takes either `VectorItems` (sent as JSON) or `BinaryUpsertParams` (sent as binary); `UpsertVectors` is a shortcut for the binary form. ```go theme={null} func (e *EncryptedIndex) Upsert(ctx context.Context, input UpsertInput) error func (e *EncryptedIndex) UpsertVectors(ctx context.Context, ids []string, vectors [][]float32, metadata []map[string]interface{}) error ``` ### Parameters #### VectorItems `VectorItems` is a `[]VectorItem`: | Field | Type | Description | | - | - | - | | `Id` | `string` | Unique identifier. Required. | | `Vector` | `[]float32` | Vector data. May be empty if the index has an embedding model and the item has contents. | | `Metadata` | `map[string]interface{}` | *(Optional)* Key-value pairs for filtering. | | `Contents` | `NullableContents` | *(Optional)* Text to store with the item, and to embed on an index with an embedding model. Set it with `item.SetContentsString(s)`; see [Set contents on a VectorItem](#set-contents-on-a-vectoritem). | #### BinaryUpsertParams Vectors are sent as base64-encoded little-endian `float32`, which is faster for large batches. | Field | Type | Description | | - | - | - | | `IDs` | `[]string` | Unique identifier for each vector. | | `Vectors` | `[][]float32` | Vector data, one slice per ID. All vectors must have the same length. | | `Metadata` | `[]map[string]interface{}` | *(Optional)* Metadata per vector, same length as `IDs`. | | `Contents` | `[]string` | *(Optional)* Contents per vector, same length as `IDs`. An empty string means no contents. | `UpsertVectors(ctx, ids, vectors, metadata)` is the same as `Upsert` with a `BinaryUpsertParams` that has no contents. > [!TIP] > > Store dates in `Metadata` as epoch milliseconds (`t.UnixMilli()`) so range filters work on them. See [Dates](../types#dates). > [!WARNING] > > Don't upsert vectors containing `NaN` or infinite values. The service stores them, and later `get` or `query` calls on that index that return vectors or distances fail with a `5xx` error. The SDK doesn't check for them. ### Returns `error` only; `nil` on success. ### Errors > [accordion] \*ValidationError > > * Wraps a sentinel. A `BinaryUpsertParams` field is empty, slices differ in length (`ErrIDsVectorsLengthMismatch`, `ErrMetadataLengthMismatch`, `ErrContentsLengthMismatch`), or vectors differ in length (`ErrInconsistentDimension`). Returned before any request is sent. `VectorItems` aren't checked in the SDK. > * The service rejects the items (HTTP `400`), for example a vector with the wrong dimension. > [accordion] \*AuthenticationError > > The `apiKey` is invalid, or a read-only user key is used (HTTP `401`/`403`). > [accordion] \*ServiceError / \*TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors). ### Example Usage #### VectorItems ```go theme={null} err := index.Upsert(ctx, cyborgdb.VectorItems{ {Id: "doc1", Vector: []float32{0.1, 0.2, 0.3, 0.4}}, {Id: "doc2", Vector: []float32{0.5, 0.6, 0.7, 0.8}, Metadata: map[string]interface{}{"category": "news"}}, }) if err != nil { log.Fatal(err) } ``` #### BinaryUpsertParams with metadata and contents ```go theme={null} err := index.Upsert(ctx, cyborgdb.BinaryUpsertParams{ IDs: []string{"vec1", "vec2", "vec3"}, Vectors: [][]float32{ {0.1, 0.2, 0.3, 0.4}, {0.5, 0.6, 0.7, 0.8}, {0.9, 1.0, 1.1, 1.2}, }, Metadata: []map[string]interface{}{{"category": "news"}, {"category": "research"}, nil}, Contents: []string{"First body", "Second body", ""}, }) if err != nil { log.Fatal(err) } ``` #### Set contents on a VectorItem ```go theme={null} item := cyborgdb.VectorItem{Id: "doc3", Vector: []float32{0.1, 0.2, 0.3, 0.4}} item.SetContentsString("Third document") if err := index.Upsert(ctx, cyborgdb.VectorItems{item}); err != nil { log.Fatal(err) } res, err := index.Get(ctx, []string{"doc3"}, []string{"contents"}) if err != nil { log.Fatal(err) } fmt.Println(res.Results[0].GetContents()) // Output: Third document ``` On an index with an embedding model, leave `Vector` empty and the service embeds the contents. #### UpsertVectors ```go theme={null} ids := []string{"vec4", "vec5"} vectors := [][]float32{ {0.1, 0.2, 0.3, 0.4}, {0.5, 0.6, 0.7, 0.8}, } if err := index.UpsertVectors(ctx, ids, vectors, nil); err != nil { log.Fatal(err) } ``` #### Replace an existing item ```go theme={null} items := cyborgdb.VectorItems{{Id: "doc1", Vector: []float32{0.1, 0.2, 0.3, 0.4}, Metadata: map[string]interface{}{"version": 1}}} if err := index.Upsert(ctx, items); err != nil { log.Fatal(err) } // Same ID: replaces the vector and metadata items = cyborgdb.VectorItems{{Id: "doc1", Vector: []float32{0.2, 0.3, 0.4, 0.5}, Metadata: map[string]interface{}{"version": 2}}} if err := index.Upsert(ctx, items); err != nil { log.Fatal(err) } res, err := index.Get(ctx, []string{"doc1"}, []string{"metadata"}) if err != nil { log.Fatal(err) } fmt.Println(res.Results[0].Metadata) // Output: map[version:2] ``` # User Management (RBAC) Source: https://docs.cyborg.co/versions/latest/service/go-sdk/encrypted-index/users When the service runs with `CYBORGDB_SERVICE_ROOT_KEY` set, `*EncryptedIndex` can create, list, and revoke per-index users. These methods require a client created with the root key. They work on both KMS-backed indexes and indexes created with an `IndexKey`. > [!NOTE] > > See [Multi-Tenancy & RBAC](../../guides/advanced/multi-tenancy) for the operator-side playbook (modes, key kinds, SDK-supplied indexes). ## CreateUser Creates a user scoped to this index and returns their API key. ```go theme={null} func (e *EncryptedIndex) CreateUser(ctx context.Context, permissions []string) (*CreatedUser, error) ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `ctx` | `context.Context` | Context for cancellation and deadlines. | | `permissions` | `[]string` | Non-empty subset of `{"read", "write"}`. | ### Returns `*CreatedUser`: | Field | Type | Description | | - | - | - | | `UserID` | `string` | Hex identifier for the new user. | | `APIKey` | `string` | The user's API key, starting with `cdbk_`. | > [!WARNING] > > The service returns `APIKey` only in this response and never stores it. Give it to the user over a secure channel and don't log it. If it's lost, delete the user and create a new one. ### Example ```go theme={null} package main import ( "context" "encoding/hex" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { ctx := context.Background() rootKey := "your-service-root-key" key, err := hex.DecodeString("your-64-character-hex-key") if err != nil { log.Fatal(err) } admin, err := cyborgdb.NewClient("http://localhost:8000", rootKey) if err != nil { log.Fatal(err) } index, err := admin.LoadIndex(ctx, "documents", key) if err != nil { log.Fatal(err) } user, err := index.CreateUser(ctx, []string{"read", "write"}) if err != nil { log.Fatal(err) } fmt.Println(len(user.UserID), user.APIKey[:5]) // Output: 32 cdbk_ // The user connects with their own key userClient, err := cyborgdb.NewClient("http://localhost:8000", user.APIKey) if err != nil { log.Fatal(err) } _ = userClient } ``` *** ## ListUsers Lists the users created for this index. ```go theme={null} func (e *EncryptedIndex) ListUsers(ctx context.Context) ([]UserInfo, error) ``` ### Returns A `[]UserInfo`, each with `UserID string` and `Permissions []string` (a subset of `{"read", "write"}`). ### Example ```go theme={null} if _, err := index.CreateUser(ctx, []string{"read"}); err != nil { log.Fatal(err) } users, err := index.ListUsers(ctx) if err != nil { log.Fatal(err) } for _, u := range users { fmt.Println(u.Permissions) } // Output: [read] ``` > [!NOTE] > > Deleting an index doesn't delete its user records. If you create a new index with the same name, `ListUsers` on it still returns the old users. They can't read the new index, because their keys don't unwrap its data key; delete them with `DeleteUser`. *** ## DeleteUser Revokes a user. Their access keys for this index are erased, so their `cdbk_` key stops working on the next request. ```go theme={null} func (e *EncryptedIndex) DeleteUser(ctx context.Context, userID string) error ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `ctx` | `context.Context` | Context for cancellation and deadlines. | | `userID` | `string` | `UserID` from `CreateUser` or `ListUsers`. Deleting an ID that doesn't exist succeeds without an error. | ### Example ```go theme={null} user, err := index.CreateUser(ctx, []string{"read"}) if err != nil { log.Fatal(err) } if err := index.DeleteUser(ctx, user.UserID); err != nil { log.Fatal(err) } users, err := index.ListUsers(ctx) if err != nil { log.Fatal(err) } fmt.Println(len(users)) // Output: 0 ``` *** ## Errors > [accordion] \*AuthenticationError > > The client isn't using the root key (HTTP `403`), or its `apiKey` is invalid (HTTP `401`). > [accordion] \*ValidationError > > `permissions` is empty or contains a value other than `"read"` or `"write"`, or `userID` isn't hex (HTTP `400`). > [accordion] \*NotFoundError > > The index doesn't exist (HTTP `404`). > [accordion] \*ServiceError / \*TransportError > > The service returns `5xx` or can't be reached. See [Errors](../errors). # Errors Source: https://docs.cyborg.co/versions/latest/service/go-sdk/errors Failed requests to the service return an error that wraps one of the typed errors below, chosen from the HTTP status code. Match them with `errors.As`, or match the shared `cyborgdb.Error` interface. ```go theme={null} package main import ( "context" "errors" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } key, err := cyborgdb.GenerateKey() if err != nil { log.Fatal(err) } _, err = client.LoadIndex(context.Background(), "missing-index", key) var notFound *cyborgdb.NotFoundError if errors.As(err, ¬Found) { fmt.Println(notFound.StatusCode(), notFound.Detail()) } // Output: 404 No KMS envelope for index 'missing-index' } ``` ## Error types | Type | Returned for | `Retryable()` | | - | - | - | | `*ValidationError` | HTTP `400` or `422`, and every argument check the SDK runs before sending (see [below](#errors-returned-before-a-request-is-sent)). | `false` | | `*AuthenticationError` | HTTP `401` or `403`: a missing or invalid `apiKey`, a non-root key used for a root-only operation, or an `indexKey` that doesn't match an index that has vectors and is already in the service's cache. | `false` | | `*NotFoundError` | HTTP `404`: the index or resource does not exist, or (in most cases) the `indexKey` doesn't match. | `false` | | `*ConflictError` | HTTP `409`: the request conflicts with the current state on the server. | `false` | | `*RateLimitError` | HTTP `429`. The service does not rate-limit requests yet. | `true` | | `*ServiceError` | Any HTTP `5xx` response. | `true` | | `*TransportError` | No response arrived: DNS failure, refused connection, TLS failure, or timeout. | `true` | | `*APIError` | Any other status of `300` or above, such as `405` or `413`. | `false` | All eight implement `cyborgdb.Error`. A `2xx` response whose body can't be decoded returns the decoding error unchanged, not a typed error. Methods such as `CreateIndex` add context to the message (for example `failed to create index: ...`), so always match with `errors.As` or `errors.Is`, never by comparing the error directly. ## The Error interface | Method | Returns | | - | - | | `StatusCode() int` | HTTP status code. `0` for a `*TransportError` or an argument check. | | `Detail() string` | The service's error message, from the response body's `detail` field. | | `RequestID() string` | Value of the `X-Request-Id` response header, when the service sends one. Include it when reporting a problem. | | `RetryAfter() float64` | Seconds from a numeric `Retry-After` header, or `0`. | | `Retryable() bool` | Fixed per type; see the table above. | | `Unwrap() error` | The underlying error. | `Unwrap` makes standard checks work through the chain, for example `errors.Is(err, context.DeadlineExceeded)` on a `*TransportError` caused by a context deadline. ```go theme={null} _, err := index.QueryMetadata(ctx, cyborgdb.QueryMetadataParams{ Filters: map[string]interface{}{"category": map[string]interface{}{"$regex": "^re"}}, }) var ve *cyborgdb.ValidationError if errors.As(err, &ve) { fmt.Println(ve.StatusCode()) fmt.Println(ve.Detail()) } // Output: // 400 // Failed to query metadata: Invalid input: $regex on 'category' requires a regex-indexed (pattern) field ``` ## Retries The SDK does not retry requests, and its HTTP client has no timeout: set deadlines on `ctx`. `Retryable()` marks the errors that are safe to retry; the retry loop is up to the caller: ```go theme={null} var resp *cyborgdb.QueryResponse var err error for attempt := 0; attempt < 3; attempt++ { resp, err = index.Query(ctx, cyborgdb.QueryParams{QueryVector: []float32{0.1, 0.2, 0.3, 0.4}, TopK: 5}) var ce cyborgdb.Error if err == nil || !errors.As(err, &ce) || !ce.Retryable() { break } wait := time.Duration(ce.RetryAfter() * float64(time.Second)) if wait == 0 { wait = time.Duration(1< [!NOTE] > > The package also declares `ErrQueryVectorsInvalidType`, `ErrMissingQueryInput`, and `ErrUnexpectedTrainingStatus`, but no function returns them. A query with no input is rejected by the service instead, as a `*ValidationError` with status `400`. # Getters Source: https://docs.cyborg.co/versions/latest/service/go-sdk/getters `*EncryptedIndex` exposes index settings and training status as methods. Every getter except `GetIndexName` takes a `context.Context` and calls the service's describe or training-status endpoint. Nothing is cached, so each call returns the current value. ## GetIndexName ```go theme={null} func (e *EncryptedIndex) GetIndexName() string ``` The index's name. Read locally, with no network call. ```go theme={null} fmt.Println(index.GetIndexName()) // Output: my-vectors ``` *** ## Dimension ```go theme={null} func (e *EncryptedIndex) Dimension(ctx context.Context) (int32, error) ``` Vector dimensionality. Returns `0` if the index was created without a `Dimension` and nothing has been upserted yet. ```go theme={null} dim, err := index.Dimension(ctx) if err != nil { log.Fatal(err) } fmt.Println(dim) // Output: 384 ``` *** ## Metric ```go theme={null} func (e *EncryptedIndex) Metric(ctx context.Context) (string, error) ``` Distance metric: `"euclidean"`, `"squared_euclidean"`, or `"cosine"`. ```go theme={null} metric, err := index.Metric(ctx) if err != nil { log.Fatal(err) } fmt.Println(metric) // Output: euclidean ``` *** ## NLists ```go theme={null} func (e *EncryptedIndex) NLists(ctx context.Context) (int32, error) ``` Number of IVF lists. `1` for an untrained index; the trained list count after [`Train`](./encrypted-index/train). ```go theme={null} nLists, err := index.NLists(ctx) if err != nil { log.Fatal(err) } fmt.Println(nLists) // Output: 1 ``` *** ## MetadataSchema ```go theme={null} func (e *EncryptedIndex) MetadataSchema(ctx context.Context) (map[string]MetadataFieldPolicy, error) ``` The per-field indexing policy set with `MetadataSchema` or `TextFields` in [`CreateIndex`](./client/create-index#metadata-schema). Never `nil`: an empty map when the index uses the default policy. The `MetadataFieldPolicy` fields are `*bool`; read them with `GetFilterable()`, `GetPattern()`, and `GetFullText()`. ```go theme={null} schema, err := index.MetadataSchema(ctx) if err != nil { log.Fatal(err) } for field, p := range schema { fmt.Println(field, p.GetFilterable(), p.GetPattern(), p.GetFullText()) } // Output: body false false true ``` *** ## BM25 ```go theme={null} func (e *EncryptedIndex) BM25(ctx context.Context) (*BM25Config, error) ``` The index's BM25 settings, or `nil` (with a `nil` error) when it has no full-text fields. | Field / method | Type | Description | | - | - | - | | `K1` | `float32` | Term-frequency saturation. | | `B` | `float32` | Length normalization. | | `GetAnalyzerVersion()` | `string` | Text analyzer the index was built with. | ```go theme={null} bm25, err := index.BM25(ctx) if err != nil { log.Fatal(err) } fmt.Println(bm25.K1, bm25.B, bm25.GetAnalyzerVersion()) // Output: 1.2 0.75 en/1;sw=2de831ef7be676b6;snowball-english-utf8-3.0.1 ``` *** ## IsTrained ```go theme={null} func (e *EncryptedIndex) IsTrained(ctx context.Context) (bool, error) ``` `true` if the index has been trained. ```go theme={null} trained, err := index.IsTrained(ctx) if err != nil { log.Fatal(err) } if !trained { if err := index.Train(ctx, cyborgdb.TrainParams{}); err != nil { log.Fatal(err) } } ``` *** ## IsTraining ```go theme={null} func (e *EncryptedIndex) IsTraining(ctx context.Context) (bool, error) ``` `true` while the service is training this index or has it queued for training. Requires the root key: with a per-user key the service returns HTTP `403` and the SDK returns `*AuthenticationError`. ```go theme={null} for { training, err := index.IsTraining(ctx) if err != nil { log.Fatal(err) } if !training { break } time.Sleep(5 * time.Second) } ``` # CyborgDB - Go SDK Reference Source: https://docs.cyborg.co/versions/latest/service/go-sdk/introduction `v0.18.x` The **CyborgDB** Go SDK is a client for the CyborgDB service. It creates encrypted indexes, upserts and retrieves vectors, runs vector, hybrid (BM25 + vector), and metadata-only queries, and manages per-index users. Every call that reaches the service takes a `context.Context`, and failures return [typed errors](./errors). The source code is on [GitHub](https://github.com/cyborginc/cyborgdb-go). ## Installation ```bash theme={null} go get github.com/cyborginc/cyborgdb-go ``` The package name is `cyborgdb`: ```go theme={null} import "github.com/cyborginc/cyborgdb-go" ``` ## Prerequisites The SDK needs a running CyborgDB service: ```bash theme={null} # Install and start the service pip install cyborgdb-service cyborgdb-service # Or run the Docker image docker run -p 8000:8000 cyborginc/cyborgdb-service ``` See the quickstart guides for [Docker](../guides/intro/quickstart-docker) and [Python](../guides/intro/quickstart-python). # Load Sample Dataset Source: https://docs.cyborg.co/versions/latest/service/go-sdk/load-sample-dataset Loads a hosted sample dataset, ready to upsert and query, for quickstarts, demos, and tests without generating your own vectors. The dataset is downloaded from a public S3 bucket on first use and cached on disk for later calls. ```go theme={null} // Load a dataset by name; "" loads the default ("quickstart-75k") func LoadSampleDataset(name string) (*SampleDataset, error) // The same, with explicit cache control func LoadSampleDatasetWithOptions(name string, opts LoadSampleDatasetOptions) (*SampleDataset, error) ``` ### Parameters | Parameter | Type | Default | Description | | - | - | - | - | | `name` | `string` | `""` (`"quickstart-75k"`) | Dataset to load. `"quickstart-75k"` is currently the only one. | | `opts.CacheDir` | `string` | `""` (`os.UserCacheDir()/cyborgdb`) | Directory for the cached dataset. | | `opts.ForceDownload` | `bool` | `false` | Download again even if a cached copy exists. | The functions take no `context.Context`. The download has a fixed 120-second timeout, and the decompressed dataset is capped at 512 MiB. Each dataset's SHA-256 digest is pinned in the SDK and checked after download and on every cache read, so a tampered file is rejected and downloaded again. ### Returns `*SampleDataset`: | Field | Type | Description | | - | - | - | | `Name` | `string` | Dataset identifier, e.g. `"quickstart-75k"`. | | `Version` | `int` | Dataset schema version. | | `Description` | `string` | Human-readable description. | | `Dimension` | `int` | Vector dimensionality. | | `Metric` | `string` | Distance metric the vectors were generated for. | | `Count` | `int` | Number of items. | | `Items` | `VectorItems` | Items with `Id`, `Vector`, and `Metadata`, ready for [`Upsert`](./encrypted-index/upsert). | | `SampleQueries` | `[][]float32` | The first 10 query vectors. | | `ExampleFilters` | `[]SampleFilter` | Metadata filters guaranteed to match, each with `Name`, `Filter`, and `Demonstrates`. | | `Ids` / `Vectors` / `Metadata` | parallel slices | Raw data, aligned by position. | | `Queries`, `MetadataQueries`, `MetadataQueryNames`, `UntrainedNeighbors`, `TrainedNeighbors`, `UntrainedMetadataMatches`, `TrainedMetadataMatches`, `UntrainedMetadataNeighbors`, `TrainedMetadataNeighbors`, `UntrainedRecall`, `TrainedRecall`, `NumUntrainedVectors`, `NumTrainedVectors` | ground truth | Fixture data for checking recall. | ### Errors > [accordion] ErrUnknownSampleDataset > > The dataset name is unknown. > [accordion] ErrSampleDatasetDownload > > The download returns a non-`200` status. A network failure or timeout returns the underlying error (for example a `*url.Error`) instead, without this sentinel. > [accordion] ErrSampleDatasetIntegrity > > The file fails its SHA-256 check. > [accordion] ErrSampleDatasetTooLarge > > The decompressed dataset exceeds 512 MiB. These are wrapped with extra context; match them with `errors.Is`. ### Example Usage ```go theme={null} package main import ( "context" "fmt" "log" "github.com/cyborginc/cyborgdb-go" ) func main() { ctx := context.Background() client, err := cyborgdb.NewClient("http://localhost:8000", "your-api-key") if err != nil { log.Fatal(err) } key, err := cyborgdb.GenerateKey() if err != nil { log.Fatal(err) } // Downloads on first use; cached afterwards dataset, err := cyborgdb.LoadSampleDataset("") if err != nil { log.Fatal(err) } fmt.Println(dataset.Name, dataset.Count, dataset.Dimension, dataset.Metric) // Output: quickstart-75k 75000 128 euclidean dim := int32(dataset.Dimension) index, err := client.CreateIndex(ctx, &cyborgdb.CreateIndexParams{ IndexName: "demo", IndexKey: key, Dimension: &dim, Metric: &dataset.Metric, }) if err != nil { log.Fatal(err) } if err := index.Upsert(ctx, dataset.Items); err != nil { log.Fatal(err) } // Similarity search with a bundled query vector resp, err := index.Query(ctx, cyborgdb.QueryParams{QueryVector: dataset.SampleQueries[0], TopK: 5}) if err != nil { log.Fatal(err) } fmt.Println(len(*resp.Results.ArrayOfQueryResultItem)) // Output: 5 // A curated metadata filter example := dataset.ExampleFilters[0] fmt.Println(example.Name, example.Filter) // Output: Equality filter (string field) map[string:string_0] if _, err := index.Query(ctx, cyborgdb.QueryParams{QueryVector: dataset.SampleQueries[0], Filters: example.Filter}); err != nil { log.Fatal(err) } } ``` # Types Source: https://docs.cyborg.co/versions/latest/service/go-sdk/types ## Index configuration These fields of [`CreateIndexParams`](./client/create-index#createindexparams) configure the index. There is no `IndexConfig` field and no `IndexIVFFlat` / `IndexIVFPQ` / `IndexIVFSQ` helpers. | Field | Type | Default | Description | | - | - | - | - | | `Dimension` | `*int32` | auto-detect | Vector dimensionality. Taken from the first upsert, or from `EmbeddingModel`, when `nil`. | | `Metric` | `*string` | `"euclidean"` | `"euclidean"`, `"squared_euclidean"`, or `"cosine"`. | | `EmbeddingModel` | `*string` | `nil` | Name of one of the service's built-in embedding models (listed by `GET /v1/embedding-models`), used for automatic embedding generation. | | `StoragePrecision` | `*string` | `"float32"` | One of the `StoragePrecision*` constants: `Float32`, `Float16`, or TurboQuant `TQ12`, `TQ8`, `TQ6`, `TQ4`. See [Storage precision](./client/create-index#storage-precision). | | `MetadataSchema` | `map[string]MetadataFieldPolicy` | `nil` | Per-field indexing policy. See [Metadata schema](./client/create-index#metadata-schema). | | `TextFields` | `[]string` | `nil` | Fields to index for BM25 full-text search. | | `Bm25K1` | `*float64` | `1.2` | BM25 term-frequency saturation. | | `Bm25B` | `*float64` | `0.75` | BM25 length normalization. | ### MetadataFieldPolicy ```go theme={null} type MetadataFieldPolicy struct { Filterable *bool // nil = true Pattern *bool // nil = false FullText *bool // nil = false } ``` ## Key management | Field | Type | Notes | | - | - | - | | `IndexKey` | `[]byte` | 32-byte key (`KeySize`) for the SDK-supplied-key path. Pass it again on every `LoadIndex`. The SDK sends it to the service as hex. | | `KmsName` | `*string` | Name of a `kms.registry` entry in the service YAML. The service generates and wraps the key; later calls pass a `nil` key. | Set exactly one of the two in `CreateIndexParams`; setting both returns a `*ValidationError`. ## VectorItem The element type of `VectorItems`, the JSON form of [`Upsert`](./encrypted-index/upsert): ```go theme={null} item := cyborgdb.VectorItem{ Id: "unique_identifier", Vector: []float32{0.1, 0.2, 0.3, 0.4}, Metadata: map[string]interface{}{ "category": "research", "author": "Dr. Smith", "tags": []string{"ai", "ml"}, "published_ms": int64(1768435200000), // a date, as epoch milliseconds }, } _ = item ``` Set `VectorItem.Contents` with `item.SetContentsString(s)`, as shown in [Upsert](./encrypted-index/upsert#set-contents-on-a-vectoritem). The contents type is exported as `cyborgdb.Contents`. ## Query result [`Query`](./encrypted-index/query) returns a `*QueryResponse`. Its `Results` field is a union with exactly one side set: | Field | Type | Set for | | - | - | - | | `ArrayOfQueryResultItem` | `*[]QueryResultItem` | One query vector, in any form | | `ArrayOfArrayOfQueryResultItem` | `*[][]QueryResultItem` | Two or more query vectors | `QueryResultItem` has `Id string` and `Metadata map[string]interface{}`, plus `GetDistance()` / `HasDistance()` (vector queries; lower is closer) and `GetScore()` / `HasScore()` (hybrid queries, instead of distance; higher is more relevant). ## QueryMetadataResponse and MetadataResult [`QueryMetadata`](./encrypted-index/query-metadata) returns: ```go theme={null} type QueryMetadataResponse struct { Results []MetadataResult // Id, plus a score when Text is set Ids []string Count int32 } type MetadataResult struct { Id string Score *float32 // read with GetScore() / HasScore() } ``` ## BM25Config Returned by the [`BM25`](./getters#bm25) getter: ```go theme={null} type BM25Config struct { K1 float32 B float32 AnalyzerVersion NullableString // read with GetAnalyzerVersion() } ``` ## Field selection `Include` picks the fields returned besides the ID: | Field | `Get` | `Query` | | - | - | - | | `vector` | Yes (default) | Not returned | | `contents` | Yes (default) | Not returned | | `metadata` | Yes (default) | Yes | | `distance` | - | Yes | `Get` with a `nil` include returns `vector`, `contents`, and `metadata`; `Query` with a `nil` `Include` returns only the ID. ## Metadata filtering `Filters` on [`Query`](./encrypted-index/query) and [`QueryMetadata`](./encrypted-index/query-metadata) is a `map[string]interface{}` of MongoDB-style operators. Nested fields use dot-paths such as `"loc.city"`. ### Operators | Operator | Meaning | Example | | - | - | - | | `$eq` | Equal (also the meaning of a bare value) | `{"category": "research"}` | | `$ne` | Not equal | `{"status": {"$ne": "draft"}}` | | `$gt`, `$gte` | Greater than, or equal | `{"year": {"$gte": 2020}}` | | `$lt`, `$lte` | Less than, or equal | `{"price": {"$lt": 100}}` | | `$in` | Value is in the list | `{"tag": {"$in": ["ai", "ml"]}}` | | `$nin` | Value is not in the list | `{"category": {"$nin": ["spam", "deleted"]}}` | | `$exists` | Field is present (`true`) or absent (`false`) | `{"reviewer": {"$exists": true}}` | | `$regex` | String matches a regular expression | `{"title": {"$regex": "^intro"}}` | | `$contains` | String contains a substring | `{"title": {"$contains": "guide"}}` | | `$and` | All sub-filters match | `{"$and": [{"a": 1}, {"b": 2}]}` | | `$or` | Any sub-filter matches | `{"$or": [{"x": 1}, {"y": 2}]}` | | `$nor` | No sub-filter matches | `{"$nor": [{"status": "draft"}, {"status": "deleted"}]}` | | `$not` | The sub-filter doesn't match. Takes one filter object, at the top level. | `{"$not": {"price": {"$gt": 100}}}` | The examples are shown as JSON; in Go, each object is a `map[string]interface{}` and each array a `[]interface{}`. `$gt`, `$gte`, `$lt`, and `$lte` require a number; any other value returns a `*ValidationError`. `$not` can't be nested inside a field. `$regex` and `$contains` resolve from the index only on fields created with `Pattern` `true`: `Query` falls back to a slower post-filter otherwise, and `QueryMetadata` rejects the filter. ### Example ```go theme={null} filter := map[string]interface{}{ "$and": []interface{}{ map[string]interface{}{"category": "research"}, map[string]interface{}{"confidence": map[string]interface{}{"$gte": 0.9}}, map[string]interface{}{"$or": []interface{}{ map[string]interface{}{"language": "en"}, map[string]interface{}{"translated": true}, }}, }, } _ = filter ``` ### Dates CyborgDB has no date type. Store dates in metadata as integer milliseconds since the Unix epoch (UTC), so range operators work on them. Don't store `time.Time` values: the SDK sends them as RFC 3339 strings, which only support equality filters. ```go theme={null} published := time.Date(2026, 1, 15, 0, 0, 0, 0, time.UTC) err := index.Upsert(ctx, cyborgdb.VectorItems{ {Id: "doc1", Vector: []float32{0.1, 0.2, 0.3, 0.4}, Metadata: map[string]interface{}{"published_ms": published.UnixMilli()}}, }) if err != nil { log.Fatal(err) } // Everything published on or after 2026-01-01 start := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC).UnixMilli() res, err := index.QueryMetadata(ctx, cyborgdb.QueryMetadataParams{ Filters: map[string]interface{}{"published_ms": map[string]interface{}{"$gte": start}}, }) if err != nil { log.Fatal(err) } fmt.Println(res.Ids) // Output: [doc1] ``` Values come back as `float64` after JSON decoding. Convert one back to a `time.Time` with: ```go theme={null} res, err := index.Get(ctx, []string{"doc1"}, []string{"metadata"}) if err != nil { log.Fatal(err) } ms := int64(res.Results[0].Metadata["published_ms"].(float64)) fmt.Println(time.UnixMilli(ms).UTC()) // Output: 2026-01-15 00:00:00 +0000 UTC ``` ## Distance metrics | Metric | Description | | - | - | | `cosine` | Cosine distance. Suited to normalized embeddings. | | `euclidean` | Euclidean (L2) distance. | | `squared_euclidean` | Squared Euclidean distance. Same ranking as `euclidean`, without the square root. | ## Other types | Type | Fields | Used by | | - | - | - | | `UpsertInput` | Interface implemented by `VectorItems` and `BinaryUpsertParams` | [`Upsert`](./encrypted-index/upsert) | | `QueryInput` | Interface implemented by `QueryParams` and `BinaryQueryParams` | [`Query`](./encrypted-index/query) | | `QueryMetadataParams` | `Filters`, `TopK`, `OrderBy`, `Ascending *bool`, and the text-search fields | [`QueryMetadata`](./encrypted-index/query-metadata) | | `TrainParams` | `NLists`, `BatchSize`, `MaxIters`, `MaxMemory` (`*int32`), `Tolerance` (`*float64`) | [`Train`](./encrypted-index/train) | | `GetResponse` | `Results []GetResultItemModel`: `Id`, `Vector`, `Metadata`, `GetContents()` | [`Get`](./encrypted-index/get) | | `ListIDsResponse` | `Ids []string`, `Count int32` | [`ListIDs`](./encrypted-index/list-ids) | | `CreatedUser` | `UserID`, `APIKey` (`string`) | [`CreateUser`](./encrypted-index/users) | | `UserInfo` | `UserID string`, `Permissions []string` | [`ListUsers`](./encrypted-index/users) | | `SampleDataset`, `SampleFilter`, `LoadSampleDatasetOptions` | See [Load Sample Dataset](./load-sample-dataset) | `LoadSampleDataset` | ## Constants | Constant | Value | | - | - | | `KeySize` | `32` | | `StoragePrecisionFloat32`, `StoragePrecisionFloat16`, `StoragePrecisionTQ12`, `StoragePrecisionTQ8`, `StoragePrecisionTQ6`, `StoragePrecisionTQ4` | `"float32"`, `"float16"`, `"tq12"`, `"tq8"`, `"tq6"`, `"tq4"` | | `DefaultSampleDataset` | `"quickstart-75k"` | | `SampleDatasetsBaseURL` | `"https://cyborgdb-sample-datasets.s3.amazonaws.com"` | Pointer fields can be set with the helpers `cyborgdb.Bool`, `cyborgdb.Int32`, `cyborgdb.String`, and `cyborgdb.Float64`, e.g. `Dimension: cyborgdb.Int32(384)`. Error types and sentinel errors are listed in [Errors](./errors). # CyborgDB Release Notes Source: https://docs.cyborg.co/changelog CyborgDB follows a bi-monthly release cadence, with new features, enhancements, and bug fixes released every even month (Feb, Apr, etc). This changelog provides a summary of the changes in each release. **v0.18.0** 2026-10-01 ## CyborgDB v0.18.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * **BM25 full-text and hybrid search** * Mark metadata fields as `full_text` in `metadata_schema` to make them keyword-searchable; tune scoring per index with `bm25_k1` / `bm25_b` * `query(text=...)` runs a keyword search, optionally limited to specific `text_fields`; combine it with a query vector for hybrid search, blended with `alpha`, `rrf_k`, and `window_mult` * Available in the embedded libraries, the REST API, and the Python, JavaScript/TypeScript, and Go SDKs * **Metadata schema.** `create_index` accepts a `metadata_schema` that sets, per field, whether it is `filterable`, indexed for fast `$regex` / `$contains` matching (`pattern`), or `full_text` * **`query_metadata`** returns the items matching a metadata filter without a query vector, in the embedded libraries, all client SDKs, and the REST API (`POST /v1/vectors/query_metadata`) * **TurboQuant storage precision.** `storage_precision` adds the `tq12`, `tq8`, `tq6`, and `tq4` tiers for much smaller stored vectors at a small recall cost (`tq4` is the most compact) * `GET /v1/embedding-models` lists the built-in embedding models the service supports * `load_sample_dataset` (`loadSampleDataset` / `LoadSampleDataset`) in the client SDKs loads a sample dataset for quick evaluation * `StorageConfig.disk(...)` adds a `cache_metadata_index` option ### Improvements * Built-in embedding models no longer require PyTorch; installing the `[embeddings]` extra is no longer needed * `$regex` filters are now evaluated with RE2, giving linear-time matching and protection against pathological patterns * `$contains` filter operator for substring matching * The client SDKs now raise standardized error types (for example `AuthenticationError`, `NotFoundError`, `ValidationError`) * Telemetry is not sent when no API key is set * Index dimension is now validated at `create_index` ### Breaking Changes * **Memory backend removed.** `StorageConfig.memory()` and `CYBORGDB_DB_TYPE=memory` are gone; use `disk` (or `s3`) instead * **One process per storage target.** A disk path or S3 bucket/prefix must be used by a single CyborgDB process at a time. Running multiple embedded processes or service replicas against the same storage target is not supported * `GET /v1/indexes/list` and `GET /v1/indexes/training-status` now require the root (admin) key ### Bug Fixes * JavaScript/TypeScript SDK: fixed decoding of `contents` returned by `get()`, and `verifySsl: false` is now honored **v0.17.0** 2026-06-25 ## CyborgDB v0.17.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * **Access control (RBAC)** on encrypted indexes, in both the embedded libraries and the service * The holder of the root index KEK can mint per-user keys scoped to `read` and/or `write` — the keys a user holds determine their permissions, enforced cryptographically on every request * Embedded: `create_user_keys` (Python) / `CreateUserKeys` (C++), plus `index_key=` / `user_id=` per-operation overrides for stateless deployments * Service: `POST`/`GET`/`DELETE` on `/v1/indexes/{name}/users`, surfaced as `users` in the Python, JavaScript/TypeScript, and Go SDKs * **Per-index KMS & BYOK.** Each index can be wrapped by its own operator-managed key, optionally living in a customer's own AWS account * Providers: `aws-kms` (AWS KMS `Encrypt`/`Decrypt`), `aws` (Secrets Manager), and `none` * Pass `kms_name` to `create_index` instead of `index_key`; the service resolves the key server-side from the index's stored key envelope, so the SDK never holds a long-term key * Cross-account BYOK via `role_arn` + `external_id`; KMS credentials are kept separate from `CYBORGDB_S3_*` storage credentials * **Free tier.** `CYBORGDB_API_KEY` is now optional — without it, CyborgDB runs free-tier with a 1,000,000-item-per-index cap. Demo keys are available via `get_demo_api_key()` / `getDemoApiKey()` / `GetDemoAPIKey()` * **YAML configuration.** The service can be configured entirely by `cyborgdb.yaml` (resolved from `CYBORGDB_CONFIG_FILE`, the working directory, or `/etc/cyborgdb/`), with `${VAR}` / `${VAR:-default}` env-var substitution. Environment variables override the file * `storage_precision` lets you store rerank vectors as `float16` instead of `float32`, halving the on-disk footprint at a small recall cost * `rerank_mult` on `query` tunes stage 1 retrieval depth (`top_k * rerank_mult` candidates before reranking), and `include=["vector"]` returns the stored rerank vector ### Improvements * `n_lists` is now selected automatically by the core engine ### Breaking Changes * **Single index type.** CyborgDB now ships a single IVF index type. The polymorphic `index_config` object is gone, along with the IVFFlat / IVFPQ / IVFSQ distinction * Configuration parameters (`dimension`, `metric`, `embedding_model`, `storage_precision`) are now top-level fields on `create_index` * `dimension` is optional — the server auto-detects it from the first upsert, or infers it from `embedding_model` * In the embedded SDKs, all parameters after `index_key` are keyword-only * **Storage refactor.** The backing store surface is now just `memory`, `disk`, or `s3` * The `standalone`, `postgres`, and `redis` backends have been removed * `CYBORGDB_CONNECTION_STRING` is replaced by `CYBORGDB_DISK_PATH` and the `CYBORGDB_S3_*` variables — switch `standalone` → `disk` when upgrading * In the embedded SDKs, a single `StorageConfig` (`StorageConfig.memory()` / `.disk(path)` / `.s3(bucket)`) replaces the `index_location` / `config_location` / `items_location` trio of `DBConfig` objects * **Authentication overhaul.** `CYBORGDB_API_KEY` is now a *license* key only and no longer gates access to the REST API * Request authentication is controlled by `CYBORGDB_SERVICE_ROOT_KEY`. Leave it unset and authentication is disabled; set it and routes accept only the root key or a per-user `cdbk_…` token in the `X-API-Key` header * The legacy `cyborgdb-api-key` header and the `REQUIRE_API_KEY` flag have been removed * A wrong `index_key` now returns `401` instead of `500` **v0.16.1** 2026-04-13 ## CyborgDB v0.16.1 ### Behavior Changes * `query()` now returns only `id` fields by default when `include` is not specified * Previously defaulted to `["distance", "metadata"]`; new default is `[]` * Pass `include=["distance", "metadata"]` explicitly to retain the prior behavior * Applies to both the embedded library and the REST service (`QueryRequest`, `BatchQueryRequest`, and `BinaryQueryRequest` all default `include` to `[]`) * **Breaking change for REST API clients**: requests without an explicit `include` field will no longer receive `distance` or `metadata` in the response ### Bug Fixes * Fixed an S3 backing store bug to properly support S3 versioned objects * Fixed a distance computation bug affecting query result ordering * Fixed an arm64 Linux issue where `cyborgdb-core` could fail to load runtime dependencies * query() now returns vector IDs by default ### Improvements * CUDA wheels now statically link CUDA runtime dependencies for improved portability **v0.16.0** 2026-04-02 ## CyborgDB v0.16.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * CyborgDB now supports **Amazon S3** as a backing store for encrypted indexes * Configure via `CYBORGDB_DB_TYPE=s3` with an S3 connection string * Compatible with AWS S3, MinIO, and any S3-compatible object storage * **CyborgDB Migrate**: New tool for migrating vector embeddings from other databases into CyborgDB * Supports Pinecone, Qdrant, Weaviate, ChromaDB, and Milvus as sources * Interactive TUI wizard or headless TOML-based config for CI/CD pipelines * Install via `pip install cyborgdb-migrate` * IVFSQ default scalar quantization bits increased from 8 to 16 for improved recall accuracy ### Improvements & Bug Fixes * Stability improvements and bug fixes across all components * Ingest errors now properly propagate to callers instead of being silently swallowed * Improved serialization support for all backing store types * New API contract test suite for guaranteed interface stability * Expanded E2E test coverage across all SDK languages and backing stores **v0.15.0** 2026-02-24 ## CyborgDB v0.15.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Significant performance optimizations for all index types * Added new `IVFSQ` index type and replace `IVFFlat` as the default * Deprecated IVF index type * Added standalone support for on-device encrypted indexes without external database dependencies * Added support for binary upsert and query vectors for faster data transfer and reduced memory usage * New `/training-status` endpoint in REST API for monitoring index training progress and status * Improved error handling and logging across all components **v0.14.0** 2025-11-25 ## CyborgDB v0.14.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Significant performance optimizations for `cyborgdb-core`: * Reduced single-query (unbatched) latency by 75% * Introduced `standalone` database mode for quick evaluation and testing: * Automatically enabled when no external database is configured * Useful for rapid prototyping and development without infrastructure overhead * Not recommended for production use - use PostgreSQL or Redis for production deployments * Improved type definitions for TypeScript SDK **v0.13.1** 2025-10-31 ## CyborgDB v0.13.1 ### Bug Fixes * Fixed an issue where `cyborgdb-core` would fail to find runtime dependencies on certain Linux arm64 systems * Exposed demo API key creation on Go and TypeScript SDKs **v0.13.0** 2025-10-27 ## CyborgDB v0.13.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Merged `cyborgdb-lite` functionality into `cyborgdb-core`: * `cyborgdb-lite` package has been deprecated and removed * All features previously available in `cyborgdb-lite` are now included in `cyborgdb-core` * Simplified package structure with a single unified library for embedded use * CyborgDB Service now supports CUDA with `pip install "cyborgdb-service[cuda]"`: * Enables existing `cyborgdb-core` CUDA optimizations in the REST API microservice * Deprecated support for Python 3.9 due to EOL for: * `cyborgdb-core` * `cyborgdb-service` * `cyborgdb-py` **v0.12.0** 2025-08-28 ## CyborgDB v0.12.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Go Client SDK now available: * [`go get github.com/cyborginc/cyborgdb-go`](https://pkg.go.dev/github.com/cyborginc/cyborgdb-go) * Automatic index management enabled by default in CyborgDB Service: * Simplifies setup and reduces manual configuration * `IndexConfig` classes now optional - CyborgDB can auto-configure indexes on the fly based on data & usage characteristics * Training & retraining now handled automatically, optimizing index performance without manual intervention * Queries can now automatically determine the optimal number of clusters to search * LangChain integration now available for Python Client SDK **v0.11.0** 2025-06-26 ## CyborgDB v0.11.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript & TypeScript) ### New Features * CyborgDB is now available as a **REST API** microservice * Available as a Python package ([`cyborgdb-service`](https://pypi.org/project/cyborgdb-service/)) * Available as a Docker image ([`cyborginc/cyborgdb-service`](https://hub.docker.com/r/cyborginc/cyborgdb-service)) * CyborgDB Client SDKs now available for REST API microservice * Python ([`cyborgdb`](https://pypi.org/project/cyborgdb/)) * JavaScript ([`cyborgdb`](https://www.npmjs.com/package/cyborgdb)) * TypeScript ([`cyborgdb`](https://www.npmjs.com/package/cyborgdb)) * Introduced API key management and a new Admin Dashboard for enhanced operational control * Optimized concurrency handling using opportunistic mutexes to improve performance under load * Improved Docker container reliability and stability across deployment environments **v0.10.0** 2025-04-30 ## CyborgDB v0.10.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker - *early access*) * Client SDK (Python, JavaScript & TypeScript - *early access*) ### New Features * CyborgDB REST API service in **early access** * CyborgDB Client SDKs in **early access** * Python * JavaScript * TypeScript * [LangChain integration for CyborgDB](/versions/latest/integrations/langchain/introduction) now available * Install via `pip install "cyborgdb-core[langchain]"` * Use via `from cyborgdb_core.integrations.langchain import CyborgVectorStore` * Supports both `cyborgdb-core` and `cyborgdb-lite` * Added configurable logging utility for embedded library in C++ and [Python](/versions/latest/embedded/python/client/logger) **v0.9.2** 2025-04-14 ## CyborgDB v0.9.2 ### New Features * `cyborgdb_lite` is now available for **evaluation** and **non-commercial use** on [PyPI](https://pypi.org/project/cyborgdb-lite/) **v0.9.1** 2025-03-28 ## CyborgDB v0.9.1 ### Bug Fixes * Fixed a bug where [automatic embedding generation](/versions/latest/embedded/guides/encrypted-indexes/create-index#automatic-embedding-generation) would not load the model correctly when using [`load_index()`](/versions/latest/embedded/guides/encrypted-indexes/load-index) * Fixed a bug which caused intermittent [`query()`](/versions/latest/embedded/guides/data-operations/query) recall issues on Linux * Fixed incorrect type returns for [`get()`](/versions/latest/embedded/guides/data-operations/get-items) in C++ and Python APIs ### Improvements * Enabled pre-filtering on [metadata queries](/versions/latest/embedded/guides/data-operations/metadata-filtering) to improve performance * Added annotations and IDE auto-completion for the Python API * Expanded support to Python 3.9 - 3.13 **v0.9.0** 2025-02-28 ## CyborgDB v0.9.0 > [!NOTE] > > This release renamed Cyborg Vector Search to **CyborgDB**. **Deployment Model**: Embedded Library (Python & C++) ### New Features * Added support for **metadata fields & query filtering** * Metadata fields can be added to items during [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items#adding-items-with-metadata) calls * [`query()`](/versions/latest/embedded/guides/data-operations/metadata-filtering) calls can filter results based on metadata fields * Added support for **item deletion** * [`delete()`](/versions/latest/embedded/guides/data-operations/delete-items) calls can remove items from the encrypted index * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items) conflicts are now resolved by overwriting existing items * Added support for **automatic embedding generation** * An embedding model can be specified during [index creation](/versions/latest/embedded/guides/encrypted-indexes/create-index#automatic-embedding-generation) * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items#automatic-embedding-generation) calls can generate embeddings directly from index contents * [`query()`](/versions/latest/embedded/guides/data-operations/query#automatic-embedding-generation) calls can use the model to generate embeddings for query vectors ### Breaking Changes * IDs are now `string`-type (instead of `int`) * This impacts `upsert()`, `get()` and `query()` function signatures * `get_item()` and `get_items()` have been replaced by [`get()`](/versions/latest/embedded/guides/data-operations/get-items) **v0.8.0** 2024-12-19 ## Cyborg Vector Search v0.8.0 **Deployment Model**: Embedded Library (Python & C++) ### New Features * Added support for **encrypted item storage & retrieval** * Encrypted indexes can now handle item content storage * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items) calls can take item content as bytes, encrypt and store them in the index * [`get_item()`](/versions/latest/embedded/guides/data-operations/get-items) calls can retrieve encrypted item content and decrypt them * Client-side caching now available for encrypted indexes (via [`max_cache_size`](/versions/latest/embedded/guides/encrypted-indexes/create-index) parameter) * Client can now handle more than one index via multiple `EncryptedIndex` objects * Optimizations: * Full-pipeline GPU acceleration for encrypted indexes * Optimized quantization and ranking logic * Backing store batch operations for improved performance ### Breaking Changes * Python & C++ APIs now split into two classes: * [`Client`](/versions/latest/embedded/guides/encrypted-indexes/create-client) class now handles DB backend connection, index creation and loading * [`EncryptedIndex`](/versions/latest/embedded/guides/encrypted-indexes/create-index) class now handles data operations (e.g., `upsert()`, `query()`, etc.) **v0.7.0** 2024-10-31 ## Cyborg Vector Search v0.7.0 **Deployment Model**: Embedded Library (Python & C++) ### New Features * First *public* release of Cyborg Vector Search * Python API available through PyBind11 * GPU acceleration with CUDA support # CyborgDB Docs Source: https://docs.cyborg.co/index ![CyborgDB](https://mintcdn.com/cyborg/o5z3-JbkwPXf99Si/images/cyborgdb-white.svg?fit=max\&auto=format\&n=o5z3-JbkwPXf99Si\&q=85\&s=7ad60fe8f70762276000d401bece8503) The vector database that keeps\ your data encrypted at rest, in transit, and in use.Similarity search directly on encrypted embeddings — self-hosted in your VPC or on-prem. AES-256-GCM with your KMS key, per-operation key derivation, keys zeroized after use. **CyborgDB** is an encrypted vector database — similarity search directly on encrypted embeddings, with per-operation key derivation via your KMS and keys zeroized after use. Only the final candidates are decrypted. It runs self-hosted and standalone — persisting to local disk (default) or S3 — exposes a familiar API that slots into existing AI pipelines, and can be [GPU-accelerated with NVIDIA cuVS](https://developer.nvidia.com/blog/bringing-confidentiality-to-vector-search-with-cyborg-and-nvidia-cuvs/). \<5msp95 encrypted query latency 100M+vectors per index Zerodata leaves your boundary ### Choose Your Path > [card] [Learn the Fundamentals](versions/latest/intro/about) > > Understand the architecture and principles behind encrypted vector search > [card] [Start Building](versions/latest/intro/quickstart) > > Get hands-on with CyborgDB in minutes using our quickstart guide > [card] [Explore Deployment Options](versions/latest/intro/deployment-models) > > Discover embedded libraries, managed service, and custom deployment options ### Documentation Structure > [card] [Introduction](versions/latest/intro/about) > > Core concepts, deployment models, and getting started guides > [card] [CyborgDB Service](versions/latest/service/guides/intro/about) > > CyborgDB self-hosted with REST API and client SDKs > [card] [CyborgDB Embedded](versions/latest/embedded/guides/intro/about) > > Self-hosted, embedded deployments with Python and C++ bindings > [card] [Integrations](versions/latest/integrations/about) > > LangChain and other framework integrations for seamless adoption > [card] [How to Use These Docs](versions/latest/intro/using-docs) > > Navigation tips and conventions used throughout these docs # CyborgDB Release Notes Source: https://docs.cyborg.co/changelog CyborgDB follows a bi-monthly release cadence, with new features, enhancements, and bug fixes released every even month (Feb, Apr, etc). This changelog provides a summary of the changes in each release. **v0.18.0** 2026-10-01 ## CyborgDB v0.18.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * **BM25 full-text and hybrid search** * Mark metadata fields as `full_text` in `metadata_schema` to make them keyword-searchable; tune scoring per index with `bm25_k1` / `bm25_b` * `query(text=...)` runs a keyword search, optionally limited to specific `text_fields`; combine it with a query vector for hybrid search, blended with `alpha`, `rrf_k`, and `window_mult` * Available in the embedded libraries, the REST API, and the Python, JavaScript/TypeScript, and Go SDKs * **Metadata schema.** `create_index` accepts a `metadata_schema` that sets, per field, whether it is `filterable`, indexed for fast `$regex` / `$contains` matching (`pattern`), or `full_text` * **`query_metadata`** returns the items matching a metadata filter without a query vector, in the embedded libraries, all client SDKs, and the REST API (`POST /v1/vectors/query_metadata`) * **TurboQuant storage precision.** `storage_precision` adds the `tq12`, `tq8`, `tq6`, and `tq4` tiers for much smaller stored vectors at a small recall cost (`tq4` is the most compact) * `GET /v1/embedding-models` lists the built-in embedding models the service supports * `load_sample_dataset` (`loadSampleDataset` / `LoadSampleDataset`) in the client SDKs loads a sample dataset for quick evaluation * `StorageConfig.disk(...)` adds a `cache_metadata_index` option ### Improvements * Built-in embedding models no longer require PyTorch; installing the `[embeddings]` extra is no longer needed * `$regex` filters are now evaluated with RE2, giving linear-time matching and protection against pathological patterns * `$contains` filter operator for substring matching * The client SDKs now raise standardized error types (for example `AuthenticationError`, `NotFoundError`, `ValidationError`) * Telemetry is not sent when no API key is set * Index dimension is now validated at `create_index` ### Breaking Changes * **Memory backend removed.** `StorageConfig.memory()` and `CYBORGDB_DB_TYPE=memory` are gone; use `disk` (or `s3`) instead * **One process per storage target.** A disk path or S3 bucket/prefix must be used by a single CyborgDB process at a time. Running multiple embedded processes or service replicas against the same storage target is not supported * `GET /v1/indexes/list` and `GET /v1/indexes/training-status` now require the root (admin) key ### Bug Fixes * JavaScript/TypeScript SDK: fixed decoding of `contents` returned by `get()`, and `verifySsl: false` is now honored **v0.17.0** 2026-06-25 ## CyborgDB v0.17.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * **Access control (RBAC)** on encrypted indexes, in both the embedded libraries and the service * The holder of the root index KEK can mint per-user keys scoped to `read` and/or `write` — the keys a user holds determine their permissions, enforced cryptographically on every request * Embedded: `create_user_keys` (Python) / `CreateUserKeys` (C++), plus `index_key=` / `user_id=` per-operation overrides for stateless deployments * Service: `POST`/`GET`/`DELETE` on `/v1/indexes/{name}/users`, surfaced as `users` in the Python, JavaScript/TypeScript, and Go SDKs * **Per-index KMS & BYOK.** Each index can be wrapped by its own operator-managed key, optionally living in a customer's own AWS account * Providers: `aws-kms` (AWS KMS `Encrypt`/`Decrypt`), `aws` (Secrets Manager), and `none` * Pass `kms_name` to `create_index` instead of `index_key`; the service resolves the key server-side from the index's stored key envelope, so the SDK never holds a long-term key * Cross-account BYOK via `role_arn` + `external_id`; KMS credentials are kept separate from `CYBORGDB_S3_*` storage credentials * **Free tier.** `CYBORGDB_API_KEY` is now optional — without it, CyborgDB runs free-tier with a 1,000,000-item-per-index cap. Demo keys are available via `get_demo_api_key()` / `getDemoApiKey()` / `GetDemoAPIKey()` * **YAML configuration.** The service can be configured entirely by `cyborgdb.yaml` (resolved from `CYBORGDB_CONFIG_FILE`, the working directory, or `/etc/cyborgdb/`), with `${VAR}` / `${VAR:-default}` env-var substitution. Environment variables override the file * `storage_precision` lets you store rerank vectors as `float16` instead of `float32`, halving the on-disk footprint at a small recall cost * `rerank_mult` on `query` tunes stage 1 retrieval depth (`top_k * rerank_mult` candidates before reranking), and `include=["vector"]` returns the stored rerank vector ### Improvements * `n_lists` is now selected automatically by the core engine ### Breaking Changes * **Single index type.** CyborgDB now ships a single IVF index type. The polymorphic `index_config` object is gone, along with the IVFFlat / IVFPQ / IVFSQ distinction * Configuration parameters (`dimension`, `metric`, `embedding_model`, `storage_precision`) are now top-level fields on `create_index` * `dimension` is optional — the server auto-detects it from the first upsert, or infers it from `embedding_model` * In the embedded SDKs, all parameters after `index_key` are keyword-only * **Storage refactor.** The backing store surface is now just `memory`, `disk`, or `s3` * The `standalone`, `postgres`, and `redis` backends have been removed * `CYBORGDB_CONNECTION_STRING` is replaced by `CYBORGDB_DISK_PATH` and the `CYBORGDB_S3_*` variables — switch `standalone` → `disk` when upgrading * In the embedded SDKs, a single `StorageConfig` (`StorageConfig.memory()` / `.disk(path)` / `.s3(bucket)`) replaces the `index_location` / `config_location` / `items_location` trio of `DBConfig` objects * **Authentication overhaul.** `CYBORGDB_API_KEY` is now a *license* key only and no longer gates access to the REST API * Request authentication is controlled by `CYBORGDB_SERVICE_ROOT_KEY`. Leave it unset and authentication is disabled; set it and routes accept only the root key or a per-user `cdbk_…` token in the `X-API-Key` header * The legacy `cyborgdb-api-key` header and the `REQUIRE_API_KEY` flag have been removed * A wrong `index_key` now returns `401` instead of `500` **v0.16.1** 2026-04-13 ## CyborgDB v0.16.1 ### Behavior Changes * `query()` now returns only `id` fields by default when `include` is not specified * Previously defaulted to `["distance", "metadata"]`; new default is `[]` * Pass `include=["distance", "metadata"]` explicitly to retain the prior behavior * Applies to both the embedded library and the REST service (`QueryRequest`, `BatchQueryRequest`, and `BinaryQueryRequest` all default `include` to `[]`) * **Breaking change for REST API clients**: requests without an explicit `include` field will no longer receive `distance` or `metadata` in the response ### Bug Fixes * Fixed an S3 backing store bug to properly support S3 versioned objects * Fixed a distance computation bug affecting query result ordering * Fixed an arm64 Linux issue where `cyborgdb-core` could fail to load runtime dependencies * query() now returns vector IDs by default ### Improvements * CUDA wheels now statically link CUDA runtime dependencies for improved portability **v0.16.0** 2026-04-02 ## CyborgDB v0.16.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * CyborgDB now supports **Amazon S3** as a backing store for encrypted indexes * Configure via `CYBORGDB_DB_TYPE=s3` with an S3 connection string * Compatible with AWS S3, MinIO, and any S3-compatible object storage * **CyborgDB Migrate**: New tool for migrating vector embeddings from other databases into CyborgDB * Supports Pinecone, Qdrant, Weaviate, ChromaDB, and Milvus as sources * Interactive TUI wizard or headless TOML-based config for CI/CD pipelines * Install via `pip install cyborgdb-migrate` * IVFSQ default scalar quantization bits increased from 8 to 16 for improved recall accuracy ### Improvements & Bug Fixes * Stability improvements and bug fixes across all components * Ingest errors now properly propagate to callers instead of being silently swallowed * Improved serialization support for all backing store types * New API contract test suite for guaranteed interface stability * Expanded E2E test coverage across all SDK languages and backing stores **v0.15.0** 2026-02-24 ## CyborgDB v0.15.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Significant performance optimizations for all index types * Added new `IVFSQ` index type and replace `IVFFlat` as the default * Deprecated IVF index type * Added standalone support for on-device encrypted indexes without external database dependencies * Added support for binary upsert and query vectors for faster data transfer and reduced memory usage * New `/training-status` endpoint in REST API for monitoring index training progress and status * Improved error handling and logging across all components **v0.14.0** 2025-11-25 ## CyborgDB v0.14.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Significant performance optimizations for `cyborgdb-core`: * Reduced single-query (unbatched) latency by 75% * Introduced `standalone` database mode for quick evaluation and testing: * Automatically enabled when no external database is configured * Useful for rapid prototyping and development without infrastructure overhead * Not recommended for production use - use PostgreSQL or Redis for production deployments * Improved type definitions for TypeScript SDK **v0.13.1** 2025-10-31 ## CyborgDB v0.13.1 ### Bug Fixes * Fixed an issue where `cyborgdb-core` would fail to find runtime dependencies on certain Linux arm64 systems * Exposed demo API key creation on Go and TypeScript SDKs **v0.13.0** 2025-10-27 ## CyborgDB v0.13.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Merged `cyborgdb-lite` functionality into `cyborgdb-core`: * `cyborgdb-lite` package has been deprecated and removed * All features previously available in `cyborgdb-lite` are now included in `cyborgdb-core` * Simplified package structure with a single unified library for embedded use * CyborgDB Service now supports CUDA with `pip install "cyborgdb-service[cuda]"`: * Enables existing `cyborgdb-core` CUDA optimizations in the REST API microservice * Deprecated support for Python 3.9 due to EOL for: * `cyborgdb-core` * `cyborgdb-service` * `cyborgdb-py` **v0.12.0** 2025-08-28 ## CyborgDB v0.12.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript, TypeScript & Go) ### New Features * Go Client SDK now available: * [`go get github.com/cyborginc/cyborgdb-go`](https://pkg.go.dev/github.com/cyborginc/cyborgdb-go) * Automatic index management enabled by default in CyborgDB Service: * Simplifies setup and reduces manual configuration * `IndexConfig` classes now optional - CyborgDB can auto-configure indexes on the fly based on data & usage characteristics * Training & retraining now handled automatically, optimizing index performance without manual intervention * Queries can now automatically determine the optimal number of clusters to search * LangChain integration now available for Python Client SDK **v0.11.0** 2025-06-26 ## CyborgDB v0.11.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker) * Client SDK (Python, JavaScript & TypeScript) ### New Features * CyborgDB is now available as a **REST API** microservice * Available as a Python package ([`cyborgdb-service`](https://pypi.org/project/cyborgdb-service/)) * Available as a Docker image ([`cyborginc/cyborgdb-service`](https://hub.docker.com/r/cyborginc/cyborgdb-service)) * CyborgDB Client SDKs now available for REST API microservice * Python ([`cyborgdb`](https://pypi.org/project/cyborgdb/)) * JavaScript ([`cyborgdb`](https://www.npmjs.com/package/cyborgdb)) * TypeScript ([`cyborgdb`](https://www.npmjs.com/package/cyborgdb)) * Introduced API key management and a new Admin Dashboard for enhanced operational control * Optimized concurrency handling using opportunistic mutexes to improve performance under load * Improved Docker container reliability and stability across deployment environments **v0.10.0** 2025-04-30 ## CyborgDB v0.10.0 ### Deployment Model * Embedded Library (Python & C++) * REST API (Microservice via Python or Docker - *early access*) * Client SDK (Python, JavaScript & TypeScript - *early access*) ### New Features * CyborgDB REST API service in **early access** * CyborgDB Client SDKs in **early access** * Python * JavaScript * TypeScript * [LangChain integration for CyborgDB](/versions/latest/integrations/langchain/introduction) now available * Install via `pip install "cyborgdb-core[langchain]"` * Use via `from cyborgdb_core.integrations.langchain import CyborgVectorStore` * Supports both `cyborgdb-core` and `cyborgdb-lite` * Added configurable logging utility for embedded library in C++ and [Python](/versions/latest/embedded/python/client/logger) **v0.9.2** 2025-04-14 ## CyborgDB v0.9.2 ### New Features * `cyborgdb_lite` is now available for **evaluation** and **non-commercial use** on [PyPI](https://pypi.org/project/cyborgdb-lite/) **v0.9.1** 2025-03-28 ## CyborgDB v0.9.1 ### Bug Fixes * Fixed a bug where [automatic embedding generation](/versions/latest/embedded/guides/encrypted-indexes/create-index#automatic-embedding-generation) would not load the model correctly when using [`load_index()`](/versions/latest/embedded/guides/encrypted-indexes/load-index) * Fixed a bug which caused intermittent [`query()`](/versions/latest/embedded/guides/data-operations/query) recall issues on Linux * Fixed incorrect type returns for [`get()`](/versions/latest/embedded/guides/data-operations/get-items) in C++ and Python APIs ### Improvements * Enabled pre-filtering on [metadata queries](/versions/latest/embedded/guides/data-operations/metadata-filtering) to improve performance * Added annotations and IDE auto-completion for the Python API * Expanded support to Python 3.9 - 3.13 **v0.9.0** 2025-02-28 ## CyborgDB v0.9.0 > [!NOTE] > > This release renamed Cyborg Vector Search to **CyborgDB**. **Deployment Model**: Embedded Library (Python & C++) ### New Features * Added support for **metadata fields & query filtering** * Metadata fields can be added to items during [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items#adding-items-with-metadata) calls * [`query()`](/versions/latest/embedded/guides/data-operations/metadata-filtering) calls can filter results based on metadata fields * Added support for **item deletion** * [`delete()`](/versions/latest/embedded/guides/data-operations/delete-items) calls can remove items from the encrypted index * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items) conflicts are now resolved by overwriting existing items * Added support for **automatic embedding generation** * An embedding model can be specified during [index creation](/versions/latest/embedded/guides/encrypted-indexes/create-index#automatic-embedding-generation) * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items#automatic-embedding-generation) calls can generate embeddings directly from index contents * [`query()`](/versions/latest/embedded/guides/data-operations/query#automatic-embedding-generation) calls can use the model to generate embeddings for query vectors ### Breaking Changes * IDs are now `string`-type (instead of `int`) * This impacts `upsert()`, `get()` and `query()` function signatures * `get_item()` and `get_items()` have been replaced by [`get()`](/versions/latest/embedded/guides/data-operations/get-items) **v0.8.0** 2024-12-19 ## Cyborg Vector Search v0.8.0 **Deployment Model**: Embedded Library (Python & C++) ### New Features * Added support for **encrypted item storage & retrieval** * Encrypted indexes can now handle item content storage * [`upsert()`](/versions/latest/embedded/guides/data-operations/add-items) calls can take item content as bytes, encrypt and store them in the index * [`get_item()`](/versions/latest/embedded/guides/data-operations/get-items) calls can retrieve encrypted item content and decrypt them * Client-side caching now available for encrypted indexes (via [`max_cache_size`](/versions/latest/embedded/guides/encrypted-indexes/create-index) parameter) * Client can now handle more than one index via multiple `EncryptedIndex` objects * Optimizations: * Full-pipeline GPU acceleration for encrypted indexes * Optimized quantization and ranking logic * Backing store batch operations for improved performance ### Breaking Changes * Python & C++ APIs now split into two classes: * [`Client`](/versions/latest/embedded/guides/encrypted-indexes/create-client) class now handles DB backend connection, index creation and loading * [`EncryptedIndex`](/versions/latest/embedded/guides/encrypted-indexes/create-index) class now handles data operations (e.g., `upsert()`, `query()`, etc.) **v0.7.0** 2024-10-31 ## Cyborg Vector Search v0.7.0 **Deployment Model**: Embedded Library (Python & C++) ### New Features * First *public* release of Cyborg Vector Search * Python API available through PyBind11 * GPU acceleration with CUDA support # CyborgDB Docs Source: https://docs.cyborg.co/index ![CyborgDB](https://mintcdn.com/cyborg/o5z3-JbkwPXf99Si/images/cyborgdb-white.svg?fit=max\&auto=format\&n=o5z3-JbkwPXf99Si\&q=85\&s=7ad60fe8f70762276000d401bece8503) The vector database that keeps\ your data encrypted at rest, in transit, and in use.Similarity search directly on encrypted embeddings — self-hosted in your VPC or on-prem. AES-256-GCM with your KMS key, per-operation key derivation, keys zeroized after use. **CyborgDB** is an encrypted vector database — similarity search directly on encrypted embeddings, with per-operation key derivation via your KMS and keys zeroized after use. Only the final candidates are decrypted. It runs self-hosted and standalone — persisting to local disk (default) or S3 — exposes a familiar API that slots into existing AI pipelines, and can be [GPU-accelerated with NVIDIA cuVS](https://developer.nvidia.com/blog/bringing-confidentiality-to-vector-search-with-cyborg-and-nvidia-cuvs/). \<5msp95 encrypted query latency 100M+vectors per index Zerodata leaves your boundary ### Choose Your Path > [card] [Learn the Fundamentals](versions/latest/intro/about) > > Understand the architecture and principles behind encrypted vector search > [card] [Start Building](versions/latest/intro/quickstart) > > Get hands-on with CyborgDB in minutes using our quickstart guide > [card] [Explore Deployment Options](versions/latest/intro/deployment-models) > > Discover embedded libraries, managed service, and custom deployment options ### Documentation Structure > [card] [Introduction](versions/latest/intro/about) > > Core concepts, deployment models, and getting started guides > [card] [CyborgDB Service](versions/latest/service/guides/intro/about) > > CyborgDB self-hosted with REST API and client SDKs > [card] [CyborgDB Embedded](versions/latest/embedded/guides/intro/about) > > Self-hosted, embedded deployments with Python and C++ bindings > [card] [Integrations](versions/latest/integrations/about) > > LangChain and other framework integrations for seamless adoption > [card] [How to Use These Docs](versions/latest/intro/using-docs) > > Navigation tips and conventions used throughout these docs