# @zilliz/milvus2-sdk-node > Official Node.js/TypeScript SDK for Milvus and Zilliz Cloud vector databases. Use it for semantic search, RAG retrieval, recommendation, hybrid dense+sparse retrieval, metadata filtering, and collection/index/user/resource management. SDK `3.0.10` is tested with Milvus `3.0.6`. It requires Node.js 18+ and is licensed under Apache-2.0. ## Install ```bash npm install @zilliz/milvus2-sdk-node # or yarn add @zilliz/milvus2-sdk-node ``` ## Client Choice - Use `MilvusClient` for the full gRPC API and best performance in normal Node.js runtimes. - Use `HttpClient` for HTTP/REST compatibility and environments where gRPC/raw TCP is unavailable or undesirable, such as Cloudflare Workers, Vercel Edge, and many serverless deployments. - Zilliz Cloud commonly uses `token`; local Milvus can use no auth or `username`/`password`. ```typescript import { MilvusClient, HttpClient } from '@zilliz/milvus2-sdk-node'; const grpcClient = new MilvusClient({ address: 'localhost:19530' }); await grpcClient.connectPromise; const cloudClient = new MilvusClient({ address: 'https://your-instance.zillizcloud.com', token: 'your-api-key', }); await cloudClient.connectPromise; const httpClient = new HttpClient({ endpoint: 'http://localhost:19530', token: 'optional-token', }); ``` ## Key Constraints and Pitfalls - Call `loadCollection` after `createCollection` and before `search`/`query`. - Dense vector dimensions must match the collection schema at insert and search time. - `DataType.VarChar` requires `max_length`. - `DataType.Array` requires `element_type` and `max_capacity`; VarChar array elements also need `max_length`. - `DataType.SparseFloatVector` does not require `dim`. - Int64 values beyond `Number.MAX_SAFE_INTEGER` (`2^53`) should be passed as strings. - `search` performs vector ANN search and returns results ordered by score/distance; `query` performs scalar filtering without a vector. - Use `filter` for scalar expressions. Some older APIs may also accept `expr`, but prefer `filter`. - `autoID: true` means primary keys are generated by Milvus; do not provide that primary key in inserted rows. ## Compatibility | Milvus version | Recommended SDK | | -------------- | ------------------------------------------------------------- | | v3.0.0+ | `@zilliz/milvus2-sdk-node@3` (3.0.10 tested with Milvus 3.0.6) | | v2.6.0+ | `@zilliz/milvus2-sdk-node@2.6` for a matching 2.x release | | v2.5.0+ | `@zilliz/milvus2-sdk-node@2.5.12` | | v2.4.0+ | `@zilliz/milvus2-sdk-node@2.4.9` | | v2.3.0+ | `@zilliz/milvus2-sdk-node@2.3.5` | SDK 3.x provides core operations on compatible Milvus 2.x deployments and Zilliz Cloud. Check your deployment’s feature availability before using 3.0-only methods or options. ## Task: Basic Vector Search / RAG Retrieval ```typescript import { MilvusClient, DataType, MetricType } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530' }); await client.connectPromise; await client.createCollection({ collection_name: 'documents', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 1536 }, { name: 'text', data_type: DataType.VarChar, max_length: 4000 }, { name: 'source', data_type: DataType.VarChar, max_length: 256 }, ], index_params: [ { field_name: 'vector', index_type: 'HNSW', metric_type: MetricType.COSINE, params: { M: 16, efConstruction: 256 }, }, ], }); await client.loadCollection({ collection_name: 'documents' }); await client.insert({ collection_name: 'documents', data: [ { vector: embedding1, text: 'document content...', source: 'file1.pdf' }, { vector: embedding2, text: 'another document...', source: 'file2.pdf' }, ], }); const res = await client.search({ collection_name: 'documents', data: [queryEmbedding], limit: 5, output_fields: ['text', 'source'], }); console.log(res.results); // [{ id, score, text, source }, ...] ``` ## Task: Vector Search with Metadata Filter ```typescript const res = await client.search({ collection_name: 'products', data: [queryVector], limit: 20, filter: 'category == "electronics" AND price < 500 AND brand IN ["Apple", "Samsung"]', output_fields: ['name', 'price', 'category', 'brand'], }); ``` Filter expression syntax: ```text age > 18 status == "active" price <= 99.9 category IN ["books", "music"] title LIKE "hello%" ARRAY_CONTAINS(tags, "ai") ARRAY_LENGTH(tags) > 3 metadata["key"] == "value" metadata["nested"]["field"] > 10 NOT (status == "deleted") ``` Bind filter placeholders in `MilvusClient` with `exprValues`. For REST `HttpClient` calls, `exprParams` is the only supported field name for filter parameters. The server binding does not recognize `filterParams`. ```typescript await client.query({ collection_name: 'documents', filter: 'year >= {min_year}', exprValues: { min_year: 2024 }, output_fields: ['text'], }); ``` ## Task: Query, Get, Count, Delete ```typescript const rows = await client.query({ collection_name: 'documents', filter: 'source == "file1.pdf"', output_fields: ['text', 'source'], limit: 100, }); const byIds = await client.get({ collection_name: 'documents', ids: [1, 2, 3], output_fields: ['text'], }); const count = await client.count({ collection_name: 'documents', filter: 'source != ""', }); await client.delete({ collection_name: 'documents', ids: [1, 2, 3] }); await client.delete({ collection_name: 'documents', filter: 'source == "old.pdf"', }); ``` ## Task: Upsert and Partial Array Update Use `upsert` to insert or replace rows by primary key. For array fields, `field_ops` can do partial updates. ```typescript import { DataType, FieldPartialUpdateOpType } from '@zilliz/milvus2-sdk-node'; await client.createCollection({ collection_name: 'articles', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true }, { name: 'vector', data_type: DataType.FloatVector, dim: 128 }, { name: 'tags', data_type: DataType.Array, element_type: DataType.VarChar, max_length: 64, max_capacity: 20, }, ], }); await client.upsert({ collection_name: 'articles', data: [{ id: 1, tags: ['featured'] }], field_ops: [ { field_name: 'tags', op: FieldPartialUpdateOpType.ARRAY_APPEND }, ], }); ``` Valid partial array ops: `REPLACE`, `ARRAY_APPEND`, `ARRAY_REMOVE`. ## Task: Rich Schema (JSON, Array, Dynamic Fields) ```typescript await client.createCollection({ collection_name: 'articles', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'title', data_type: DataType.VarChar, max_length: 512 }, { name: 'embedding', data_type: DataType.FloatVector, dim: 768 }, { name: 'tags', data_type: DataType.Array, element_type: DataType.VarChar, max_length: 64, max_capacity: 20, }, { name: 'metadata', data_type: DataType.JSON }, ], enable_dynamic_field: true, index_params: [ { field_name: 'embedding', index_type: 'HNSW', metric_type: MetricType.COSINE, params: { M: 16, efConstruction: 256 }, }, ], }); await client.loadCollection({ collection_name: 'articles' }); await client.insert({ collection_name: 'articles', data: [ { title: 'Milvus guide', embedding: Array(768).fill(0.1), tags: ['vector-db', 'rag'], metadata: { author: 'zilliz', year: 2026 }, dynamic_extra_field: 'stored in dynamic field', }, ], }); ``` ## Task: Multi-Tenant Partition Key Partition keys automatically route rows and filtered searches by tenant without manual partition management. ```typescript await client.createCollection({ collection_name: 'tenant_data', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'tenant_id', data_type: DataType.VarChar, max_length: 64, is_partition_key: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128 }, { name: 'content', data_type: DataType.VarChar, max_length: 2000 }, ], num_partitions: 16, }); await client.loadCollection({ collection_name: 'tenant_data' }); await client.insert({ collection_name: 'tenant_data', data: [ { tenant_id: 'user_123', vector: Array(128).fill(0.1), content: 'hello' }, ], }); const res = await client.search({ collection_name: 'tenant_data', data: [queryVector], filter: 'tenant_id == "user_123"', limit: 10, output_fields: ['content'], }); ``` ## Task: Sparse Vector Search Sparse vectors are objects mapping dimension index to weight. ```typescript await client.createCollection({ collection_name: 'sparse_docs', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'sparse_vector', data_type: DataType.SparseFloatVector }, { name: 'text', data_type: DataType.VarChar, max_length: 5000 }, ], index_params: [ { field_name: 'sparse_vector', index_type: 'SPARSE_INVERTED_INDEX', metric_type: MetricType.IP, }, ], }); await client.loadCollection({ collection_name: 'sparse_docs' }); await client.insert({ collection_name: 'sparse_docs', data: [ { sparse_vector: { 0: 0.5, 10: 0.3, 200: 0.8 }, text: 'machine learning' }, { sparse_vector: { 1: 0.1, 50: 0.9 }, text: 'database systems' }, ], }); const res = await client.search({ collection_name: 'sparse_docs', data: [{ 0: 0.5, 10: 0.3 }], anns_field: 'sparse_vector', limit: 10, output_fields: ['text'], }); ``` ## Task: Full-Text Search / BM25 Functions Milvus can generate sparse BM25 representations from text fields with functions. Define analyzer-enabled input text and a sparse output field. ```typescript import { DataType, FunctionType, MetricType } from '@zilliz/milvus2-sdk-node'; await client.createCollection({ collection_name: 'text_search', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'text', data_type: DataType.VarChar, max_length: 5000, enable_analyzer: true, }, { name: 'sparse', data_type: DataType.SparseFloatVector }, ], functions: [ { name: 'bm25_fn', type: FunctionType.BM25, input_field_names: ['text'], output_field_names: ['sparse'], params: {}, }, ], index_params: [ { field_name: 'sparse', index_type: 'SPARSE_INVERTED_INDEX', metric_type: MetricType.BM25, }, ], }); ``` ## Task: Hybrid Search (Multiple Vector Requests + Rerank) `hybridSearch` combines multiple ANN requests, commonly dense vectors plus sparse/BM25 vectors, then reranks with `WeightedRanker` or `RRFRanker`. ```typescript import { WeightedRanker, RRFRanker } from '@zilliz/milvus2-sdk-node'; const res = await client.hybridSearch({ collection_name: 'hybrid_docs', data: [ { anns_field: 'dense_vector', data: [denseQueryVector], params: { ef: 64 }, }, { anns_field: 'sparse_vector', data: [sparseQueryVector], }, ], rerank: WeightedRanker([0.7, 0.3]), // or RRFRanker(60) limit: 10, output_fields: ['text', 'source'], }); ``` ## Task: Iterators for Large Result Sets ```typescript const queryIter = await client.queryIterator({ collection_name: 'documents', filter: 'status == "active"', batchSize: 1000, limit: 100000, output_fields: ['text', 'source'], }); for await (const batch of queryIter) { processBatch(batch); } const searchIter = await client.searchIterator({ collection_name: 'documents', data: queryVector, batchSize: 100, limit: 5000, output_fields: ['text'], }); for await (const batch of searchIter) { processBatch(batch); } ``` ## Task: Bulk Data Import Use `BulkWriter` to generate Milvus-compatible JSON or Parquet files locally, then import files server-side from storage accessible by Milvus. ```typescript import { BulkWriter, DataType } from '@zilliz/milvus2-sdk-node'; const writer = new BulkWriter({ schema: { fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true }, { name: 'vector', data_type: DataType.FloatVector, dim: 128 }, ], }, format: 'parquet', // or 'json' localPath: './bulk_data', }); for (const row of largeDataset) { await writer.append(row); } const batchFiles = await writer.close(); // Upload the files in batchFiles to storage accessible to Milvus. // Use their uploaded paths in the import request. const importRes = await client.bulkInsert({ collection_name: 'my_collection', files: ['imports/data.parquet'], }); const state = await client.getImportState({ task: importRes.tasks[0] }); ``` ## Task: External Collections (gRPC) External collections can map Milvus fields to external data and refresh external data sources. Use only when your Milvus deployment supports this feature. ```typescript await client.createCollection({ collection_name: 'external_docs', external_source: 's3://bucket/path/', external_spec: JSON.stringify({ format: 'parquet' }), fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, external_field: 'doc_id', }, { name: 'vector', data_type: DataType.FloatVector, dim: 768, external_field: 'embedding', }, { name: 'text', data_type: DataType.VarChar, max_length: 4000, external_field: 'body', }, ], }); const refresh = await client.refreshExternalCollection({ collection_name: 'external_docs', }); await client.getRefreshExternalCollectionProgress({ job_id: refresh.job_id }); await client.listRefreshExternalCollectionJobs({ collection_name: 'external_docs', }); ``` ## Task: Snapshot APIs (gRPC) Snapshot APIs are available for deployments that support Milvus snapshot management. ```typescript await client.createSnapshot({ collection_name: 'documents', snapshot_name: 'snap_001', }); await client.listSnapshots({ collection_name: 'documents' }); await client.describeSnapshot({ collection_name: 'documents', snapshot_name: 'snap_001', }); const restore = await client.restoreSnapshot({ source_collection_name: 'documents', target_collection_name: 'documents_restored', snapshot_name: 'snap_001', }); await client.getRestoreSnapshotState({ job_id: restore.job_id }); await client.listRestoreSnapshotJobs(); await client.dropSnapshot({ collection_name: 'documents', snapshot_name: 'snap_001', }); ``` Related methods include `pinSnapshotData` and `unpinSnapshotData`. ## Task: Collection and Index Management ```typescript await client.hasCollection({ collection_name }); await client.describeCollection({ collection_name }); await client.batchDescribeCollections({ collection_names: [collection_name] }); await client.showCollections(); await client.loadCollection({ collection_name }); await client.releaseCollection({ collection_name }); await client.refreshLoad({ collection_name }); await client.renameCollection({ collection_name, new_collection_name }); await client.truncateCollection({ collection_name }); await client.dropCollection({ collection_name }); await client.alterCollectionProperties({ collection_name, properties: { 'collection.ttl.seconds': 3600 }, }); await client.dropCollectionProperties({ collection_name, properties: ['collection.ttl.seconds'], }); await client.alterCollectionFieldProperties({ collection_name, field_name: 'vector', properties: { 'mmap.enabled': true }, }); await client.createIndex({ collection_name, field_name: 'vector', index_type: 'HNSW', metric_type: 'COSINE', }); await client.describeIndex({ collection_name, field_name: 'vector' }); await client.listIndexes({ collection_name }); await client.getIndexState({ collection_name, field_name: 'vector' }); await client.dropIndex({ collection_name, field_name: 'vector' }); ``` ## Task: Database, Partition, Alias, RBAC, Resource Groups ```typescript await client.createDatabase({ db_name: 'tenant_db' }); await client.listDatabases(); await client.describeDatabase({ db_name: 'tenant_db' }); await client.dropDatabase({ db_name: 'tenant_db' }); await client.createPartition({ collection_name, partition_name: 'p1' }); await client.listPartitions({ collection_name }); await client.loadPartitions({ collection_name, partition_names: ['p1'] }); await client.dropPartition({ collection_name, partition_name: 'p1' }); await client.createAlias({ collection_name, alias: 'current_docs' }); await client.describeAlias({ collection_name, alias: 'current_docs' }); await client.dropAlias({ alias: 'current_docs' }); await client.createUser({ username: 'alice', password: 'secret' }); await client.createRole({ roleName: 'reader' }); await client.addUserToRole({ username: 'alice', roleName: 'reader', }); await client.createResourceGroup({ resource_group: 'rg1' }); await client.listResourceGroups(); await client.dropResourceGroup({ resource_group: 'rg1' }); ``` ## HTTP Client Notes `HttpClient` uses the Milvus REST v2 API with camelCase request fields. Set `endpoint` to your cluster origin; the SDK appends `/v2`. If you specify `baseURL`, include `/v2` in the value. ```typescript import { HttpClient } from '@zilliz/milvus2-sdk-node'; const client = new HttpClient({ endpoint: 'http://localhost:19530', database: 'default', timeout: 60_000, }); const created = await client.createCollection({ collectionName: 'docs', dimension: 128, metricType: 'COSINE', primaryFieldName: 'id', vectorFieldName: 'vector', }); if (created.code !== 0) throw new Error(created.message); const vector = Array(128).fill(0.1); await client.insert({ collectionName: 'docs', data: [{ id: 1, vector }] }); await client.search({ collectionName: 'docs', data: [vector], limit: 10, outputFields: ['id'] }); await client.query({ collectionName: 'docs', filter: 'id > 0', limit: 100, outputFields: ['id'] }); ``` - [HttpClient guide](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/) - [HttpClient method reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/) - [Milvus REST v2 operations](https://milvus-io.github.io/milvus-sdk-node/rest-api/) ## Quick Reference: Data Types | Use case | DataType | Notes | | ----------------------------- | ------------------------------------------------------------- | ----------------------------------- | | Primary key | `DataType.Int64`, `DataType.VarChar` | Set `is_primary_key: true` | | Dense embedding | `DataType.FloatVector` | Set `dim` | | Binary embedding | `DataType.BinaryVector` | Set `dim`; binary metrics apply | | Half precision | `DataType.Float16Vector`, `DataType.BFloat16Vector` | Set `dim` | | Quantized dense | `DataType.Int8Vector` | Set `dim` | | Sparse embedding | `DataType.SparseFloatVector` | No `dim` | | Text | `DataType.VarChar` | Set `max_length` | | Metadata | `DataType.JSON` | Filter with `metadata["key"]` | | Lists | `DataType.Array` | Set `element_type` + `max_capacity` | | Numeric | `DataType.Int8`, `Int16`, `Int32`, `Int64`, `Float`, `Double` | Use string for unsafe Int64 | | Boolean | `DataType.Bool` | | | Geo/time | `DataType.Geometry`, `DataType.Timestamptz` | Deployment/version dependent | | Advanced nested/vector arrays | `DataType.Struct`, `DataType.ArrayOfVector` | Deployment/version dependent | ## Quick Reference: Metric Types | Metric | Best for | Score meaning | | -------------------------------------------------------------------- | ------------------------------------- | ---------------------------- | | `MetricType.COSINE` | Normalized embeddings | Higher = more similar | | `MetricType.L2` | Euclidean distance | Lower = more similar | | `MetricType.IP` | Inner product / normalized vectors | Higher = more similar | | `MetricType.BM25` | Sparse full-text relevance | Higher = more relevant | | `MetricType.HAMMING`, `MetricType.JACCARD` | Binary vectors | Lower/metric-specific | | `MetricType.TANIMOTO`, `SUBSTRUCTURE`, `SUPERSTRUCTURE`, `MHJACCARD` | Specialized similarity | Deployment/version dependent | | `MetricType.MAX_SIM*`, `DTW_*` | Advanced multi-vector/sequence search | Deployment/version dependent | ## Quick Reference: Index Types Common values: `AUTOINDEX`, `HNSW`, `FLAT`, `IVF_FLAT`, `IVF_SQ8`, `IVF_PQ`, `DISKANN`, `BIN_FLAT`, `BIN_IVF_FLAT`, `SPARSE_INVERTED_INDEX`, `SPARSE_WAND`. ## Error Handling `MilvusClient` DDL methods such as `createCollection` return `ResStatus` directly with `error_code` and `reason`. Data methods such as `insert`, `search`, and `query` return their payload alongside `status.error_code` and `status.reason`. Transport and SDK errors can reject the promise. With `HttpClient`, catch `HttpError` for non-2xx responses and check the Milvus `code` when the response has a status envelope. ```typescript import { ErrorCode } from '@zilliz/milvus2-sdk-node'; try { const { status } = await client.describeCollection({ collection_name: 'documents', }); if (status.error_code !== ErrorCode.SUCCESS) { throw new Error(status.reason); } } catch (err) { console.error('Milvus transport or SDK error:', err); } ``` ## Full API Reference See the [SDK API reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/) for current method signatures and examples. The source lives under `milvus/`. ## SDK 3.0.10 - `count()` preserves the server error status with `data: 0` when a query fails. Check `status.error_code` before using the count. - `flushSync()` supports streaming flush checkpoints and preserves server errors, database selection, and polling timeouts. - `HttpClient` binds the built-in `fetch` to the global receiver for edge runtimes. ## SDK 3.0.6–3.0.9 - Search and query accept gRPC `function_chains`; REST search and hybrid search accept `functionChains`. Search aggregation is available as gRPC `search_aggregation` or REST `searchAggregation`. - StructArray schemas support nested Array sub-fields. Partial upserts can replace a specific path using `field_ops` (gRPC) or `fieldOps` (REST) and the path-replacement operation. - Use `exportSnapshot`, `getExportSnapshotState`, and `restoreExternalSnapshot` for portable snapshot export and restore. - `MilvusClient` exposes `updateReplicateConfiguration`, `getReplicateConfiguration`, `getReplicateInfo`, `createReplicateStream`, and `dumpMessages` for replication and WAL streams. - `MilvusClient` exposes `computePhraseMatchSlop`, `batchUpdateManifest`, proxy RPCs (`allocTimestamp`, `getComponentStates`, `registerLink`, `dummy`), and telemetry RPCs (`getClientTelemetry`, `pushClientCommand`, `deleteClientCommand`). - `HttpClient` covers Milvus 3.0.6 REST v2 workflows including collection schema changes, external refresh, snapshot jobs, manual import commit/abort, resource and privilege groups, analyzer files, and diagnostics. The REST reference also covers compatibility aliases and the two legacy standalone function routes. Use `addFunctionField` and `dropFunctionField` for the SDK's atomic function-field operations. ## SDK 3.0.4–3.0.5 - `buildBloomFilter(members, fpr = 0.005)` returns Uint8Array for `filter: 'membership_match(field, {blob}, type=bloom)', exprValues: { blob }`. Members must all be integers (`number`/`bigint`) or strings; decimal strings are UTF-8, not integer IDs. False positives are possible; this is not an authorization filter. FPR range: 0.0001–0.05. - `buildRoaringBitmap(members)` returns Uint8Array for `membership_match(field, {blob}, type=roaring)` with the same exprValues shape. Exact integer membership accepts safe numbers, bigint or decimal int64 strings. Reuse blobs; do not JSON/base64 encode them. Server expression support is required. Incremental builders: `BloomFilterBuilder`, `RoaringBitmapBuilder`. - `ClientConfig.telemetry` defaults to `{ enabled: true, heartbeatIntervalMs: 10000, samplingRate: 1, errorMaxCount: 100 }`. Set `enabled: false` at construction to prevent startup. `client.getTelemetry().getConfig()` inspects effective settings; `closeConnection()` stops heartbeats. Telemetry is separate from `trace` and sends metrics/client metadata to the connected server. - `DataType.Text = 25` requires StorageV3, has no `max_length`, and cannot be a primary/partition key or array element. Values are JavaScript strings. - `addFunctionField` backfills existing sealed segments asynchronously. Check `getCollectionStatistics().data.schema_version_consistent_segments` against `schema_version_total_segments`, then bound index readiness. Success of the schema RPC does not mean completion. `do_physical_backfill` is not a function-field option. - New index constants: `HNSW_SQ`, `HNSW_PQ`, `HNSW_PRQ`, `AISAQ`, `NGRAM`, `FMINDEX`; server availability varies. - Release details: https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/ --- # Milvus Node.js SDK Connect a Node.js application to Milvus or Zilliz Cloud and list collections. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/ ## Section links - [Install](https://milvus-io.github.io/milvus-sdk-node/#install) - [Connect and list collections](https://milvus-io.github.io/milvus-sdk-node/#connect-and-list-collections) - [Start building](https://milvus-io.github.io/milvus-sdk-node/#start-building) - [Compatibility](https://milvus-io.github.io/milvus-sdk-node/#compatibility) `@zilliz/milvus2-sdk-node` v3.x is the official Node.js SDK for compatible Milvus 2.x and 3.0+ deployments and Zilliz Cloud, with `MilvusClient` for gRPC and `HttpClient` for REST v2. ## Install ```sh npm install @zilliz/milvus2-sdk-node ``` ## Connect and list collections ```js import { MilvusClient } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: process.env.MILVUS_ADDRESS ?? 'localhost:19530', token: process.env.MILVUS_TOKEN, }); try { const { status, data } = await client.listCollections(); if (status.error_code !== 'Success') throw new Error(status.reason); console.log(data.map((collection) => collection.name)); } finally { await client.closeConnection(); } ``` Run `node list-collections.mjs` against local Milvus, or set `MILVUS_ADDRESS` and `MILVUS_TOKEN` for your cluster. ## Start building - [Create a collection](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#your-first-collection) - [Insert data](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/) - [Search vectors](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/) - [Explore the REST API](https://milvus-io.github.io/milvus-sdk-node/rest-api/) ## Compatibility SDK 3.0.11 · Node.js 18+ Tested with Milvus 3.0.7 --- # Get Started with Milvus Install the Milvus Node.js SDK, connect to Milvus or Zilliz Cloud, create your first collection, and search vectors. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/ ## Section links - [Installation](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#installation) - [Basic Connection](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#basic-connection) - [Connection with Authentication](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#connection-with-authentication) - [Connection with Token (Zilliz Cloud)](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#connection-with-token-zilliz-cloud) - [Your First Collection](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#your-first-collection) - [Connection Lifecycle](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#connection-lifecycle) - [Connecting](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#connecting) - [Disconnecting](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#disconnecting) - [Error Handling](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#error-handling) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/#next-steps) This guide will help you get started with the Milvus Node.js SDK. You’ll learn how to install the SDK, connect to Milvus, and perform basic operations. ## Installation Install the SDK using npm or yarn: ```bash npm install @zilliz/milvus2-sdk-node # or yarn add @zilliz/milvus2-sdk-node ``` ## Basic Connection Create a new client instance and connect to your Milvus server: ```javascript import { MilvusClient } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530', }); // Wait for connection to be established await client.connectPromise; console.log('Connected to Milvus!'); ``` ## Connection with Authentication If your Milvus instance requires authentication: ```javascript const client = new MilvusClient({ address: 'localhost:19530', username: 'root', password: 'Milvus', }); await client.connectPromise; ``` ## Connection with Token (Zilliz Cloud) For Zilliz Cloud, you can use a token: ```javascript const client = new MilvusClient({ address: 'https://your-endpoint.zillizcloud.com:443', token: 'your-api-key', }); await client.connectPromise; ``` ## Your First Collection Let’s create a collection, insert some data, and perform a search: ```javascript import { MilvusClient, DataType } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530', }); await client.connectPromise; // Define collection schema const collectionName = 'hello_milvus'; const schema = [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, }, { name: 'text', data_type: DataType.VarChar, max_length: 256, }, ]; // Create collection await client.createCollection({ collection_name: collectionName, fields: schema, consistency_level: 'Strong', }); console.log('Collection created!'); // Insert data const data = [ { vector: Array.from({ length: 128 }, () => Math.random()), text: 'Hello Milvus', }, { vector: Array.from({ length: 128 }, () => Math.random()), text: 'Vector database', }, ]; await client.insert({ collection_name: collectionName, data, }); console.log('Data inserted!'); // Create index await client.createIndex({ collection_name: collectionName, field_name: 'vector', index_type: 'HNSW', metric_type: 'L2', }); // Load collection await client.loadCollectionSync({ collection_name: collectionName, }); // Search const searchResults = await client.search({ collection_name: collectionName, data: [Array.from({ length: 128 }, () => Math.random())], limit: 5, output_fields: ['text'], }); console.log('Search results:', searchResults); await client.dropCollection({ collection_name: collectionName }); await client.closeConnection(); ``` ## Connection Lifecycle ### Connecting The SDK automatically connects when you create a new `MilvusClient` instance. You can wait for the connection using: ```javascript await client.connectPromise; ``` ### Disconnecting To properly close the connection: ```javascript await client.closeConnection(); ``` ## Error Handling Always wrap your operations in try-catch blocks: ```javascript try { await client.createCollection({ collection_name: 'my_collection', fields: schema, }); } catch (error) { console.error('Error creating collection:', error); } ``` ## Next Steps - Learn about [Client Configuration](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/) - Understand [Data Types & Schemas](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/) - Explore [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/) - Check out [Examples & Tutorials](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/) --- # Deploy Applications with the Milvus SDK Choose gRPC or HTTP for Milvus Node.js deployments on servers, containers, serverless functions, and edge platforms. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/ ## Section links - [Choosing the Right Client](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#choosing-the-right-client) - [Serverless Platforms](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#serverless-platforms) - [Vercel](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#vercel) - [Cloudflare Workers](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#cloudflare-workers) - [AWS Lambda](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#aws-lambda) - [Traditional Server Deployment](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#traditional-server-deployment) - [Node.js/Express](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#nodejsexpress) - [Docker](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#docker) - [Environment Variables](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#environment-variables) - [Platform Comparison](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#platform-comparison) - [Common Patterns](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#common-patterns) - [Client Reuse](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#client-reuse) - [Error Handling](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#error-handling) - [Timeout Configuration](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#timeout-configuration) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/getting-started/deployment/#next-steps) Use `MilvusClient` on Node.js servers with gRPC support. Choose `HttpClient` for HTTP-only environments such as Cloudflare Workers and Vercel Edge, or when a proxy requires REST. ## Choosing the Right Client | Decision | MilvusClient (gRPC) | HttpClient (REST) | | --- | --- | --- | | Protocol | gRPC over HTTP/2 | Milvus REST v2 over HTTP with JSON | | Request field casing | snake_case, such as `collection_name` | camelCase, such as `collectionName` | | Serverless and edge support | Use in Node.js runtimes that support gRPC connections | Use in Fetch-capable runtimes, including HTTP-only serverless and edge environments | | Streaming and gRPC-only admin RPCs | Supports replication and WAL streams, plus proxy and telemetry administration | Supports REST management operations and returns JSON responses | | Response and error handling | Inspect `error_code` on a status or `status.error_code` on a result. Transport failures can reject. | Inspect `code` where the REST response provides it. Non-2xx responses throw `HttpError`. | Set the REST client’s `endpoint` to your cluster origin. The SDK appends `/v2`. For a custom `baseURL`, include the full versioned URL ending in `/v2`. ## Serverless Platforms ### Vercel Deploy to Vercel serverless functions with minimal configuration. **Quick Start:** ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node'; let client; function getClient() { if (!client) { client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 10000, }); } return client; } export default async function handler(req, res) { const milvusClient = getClient(); const results = await milvusClient.search({ collectionName: 'my_collection', data: req.body.vectors, limit: 10, outputFields: [], }); res.status(200).json({ results }); } ``` **Learn more:** [Vercel Deployment Guide](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/) ### Cloudflare Workers Deploy to Cloudflare Workers for edge computing. **Quick Start:** ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node/dist/milvus/HttpClient.js'; export default { async fetch(request, env) { const { vector } = await request.json(); const client = new HttpClient({ endpoint: env.MILVUS_ENDPOINT, token: env.MILVUS_TOKEN, timeout: 25000, }); const results = await client.search({ collectionName: 'my_collection', data: [vector], limit: 10, outputFields: [], }); return new Response(JSON.stringify({ results }), { headers: { 'Content-Type': 'application/json' }, }); }, }; ``` **Learn more:** [Cloudflare Workers Deployment Guide](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/) ### AWS Lambda Deploy to AWS Lambda for scalable serverless functions. **Quick Start:** ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node'; let client; function getClient() { if (!client) { client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 25000, }); } return client; } export const handler = async (event) => { const milvusClient = getClient(); const results = await milvusClient.search({ collectionName: 'my_collection', data: JSON.parse(event.body).vectors, limit: 10, outputFields: [], }); return { statusCode: 200, body: JSON.stringify({ results }), }; }; ``` **Learn more:** [AWS Lambda Deployment Guide](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/) ## Traditional Server Deployment ### Node.js/Express For traditional Node.js servers, you can use either client: ```javascript // Using gRPC Client (Recommended) import { MilvusClient } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530', token: 'your-token', }); await client.connectPromise; // Using HTTP Client import { HttpClient } from '@zilliz/milvus2-sdk-node'; const client = new HttpClient({ endpoint: 'http://localhost:19530', token: 'your-token', }); ``` ### Docker Deploy in Docker containers: ```dockerfile FROM node:20-alpine WORKDIR /app COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 CMD ["node", "index.js"] ``` ## Environment Variables Always use environment variables for sensitive configuration: ```bash MILVUS_ENDPOINT=https://your-instance.zillizcloud.com MILVUS_TOKEN=your-api-token ``` ```javascript const client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, }); ``` ## Platform Comparison | Platform | Client Type | Timeout Limit | Best For | | --- | --- | --- | --- | | Vercel | HTTP | 10s (Hobby), 60s (Pro) | Next.js apps, static sites | | Cloudflare Workers | HTTP | 30s (free), 15min (paid) | Edge computing, global distribution | | AWS Lambda | HTTP | Up to 15 minutes | Enterprise serverless | | Traditional Server | gRPC or HTTP | No limit | Long-lived applications | ## Common Patterns ### Client Reuse Reuse client instances to improve performance: ```javascript let client; function getClient() { if (!client) { client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, }); } return client; } ``` ### Error Handling Reuse the HTTP client from the previous example. Inspect the Milvus response code and catch errors from the HTTP request: ```javascript async function searchCollection(queryVector) { try { const results = await getClient().search({ collectionName: 'my_collection', data: [queryVector], limit: 10, outputFields: [], }); if (results.code !== 0) { return { success: false, error: results.message, status: 502 }; } return { success: true, results }; } catch (error) { console.error('Milvus error:', error); return { success: false, error: error.message, status: error.status || 500, }; } } ``` ### Timeout Configuration Set timeouts based on platform limits: ```javascript const client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 10000, // Adjust based on platform }); ``` ## Next Steps - **Vercel**: [Detailed Vercel Deployment Guide](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/) - **Cloudflare**: [Cloudflare Workers Guide](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/) - **AWS Lambda**: [AWS Lambda Guide](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/) - **HTTP Client**: [HTTP Client Documentation](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/) - **Best Practices**: [Best Practices Guide](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) --- # Milvus Code Examples and Tutorials Follow Node.js examples for Milvus CRUD, similarity search, dynamic schemas, and integrations with Next.js and LangChain. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/ ## Section links - [Basic CRUD Operations](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#basic-crud-operations) - [Complete Example](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#complete-example) - [Vector Similarity Search](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#vector-similarity-search) - [Image Search Example](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#image-search-example) - [Hybrid Search](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#hybrid-search) - [Multi-Vector Search](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#multi-vector-search) - [Dynamic Schema Usage](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#dynamic-schema-usage) - [Flexible Schema Example](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#flexible-schema-example) - [Partition Key Usage](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#partition-key-usage) - [Time-Based Partitioning](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#time-based-partitioning) - [Multi-Database Setup](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#multi-database-setup) - [Database Management Example](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#database-management-example) - [Authentication Examples](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#authentication-examples) - [Basic Authentication](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#basic-authentication) - [Token Authentication (Zilliz Cloud)](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#token-authentication-zilliz-cloud) - [Next.js Integration](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#nextjs-integration) - [API Route Example](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#api-route-example) - [LangChain Integration](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#langchain-integration) - [LangChain.js Example](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#langchainjs-example) - [Cloud Deployment](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#cloud-deployment) - [Zilliz Cloud Example](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#zilliz-cloud-example) - [Error Handling Pattern](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#error-handling-pattern) - [Comprehensive Error Handling](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#comprehensive-error-handling) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/#next-steps) This guide provides comprehensive examples and tutorials for common use cases. ## Basic CRUD Operations ### Complete Example ```javascript import { MilvusClient, DataType } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530', }); await client.connectPromise; // Create collection const schema = [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, }, { name: 'text', data_type: DataType.VarChar, max_length: 256, }, ]; await client.createCollection({ collection_name: 'my_collection', fields: schema, }); // Insert data const insertResult = await client.insert({ collection_name: 'my_collection', data: [ { vector: Array.from({ length: 128 }, () => Math.random()), text: 'Hello Milvus', }, { vector: Array.from({ length: 128 }, () => Math.random()), text: 'Vector database', }, ], }); if (insertResult.status.error_code !== 'Success') { throw new Error(insertResult.status.reason); } if (!('int_id' in insertResult.IDs)) { throw new Error('Expected Int64 primary keys'); } const ids = insertResult.IDs.int_id.data.map(String); console.log('Inserted IDs:', ids); // Create index await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'HNSW', metric_type: 'L2', }); // Load collection await client.loadCollectionSync({ collection_name: 'my_collection', }); // Search const searchResults = await client.search({ collection_name: 'my_collection', data: [Array.from({ length: 128 }, () => Math.random())], limit: 5, output_fields: ['text'], }); console.log('Search results:', searchResults.results); // Query const queryResults = await client.query({ collection_name: 'my_collection', expr: 'text == "Hello Milvus"', output_fields: ['id', 'text'], }); console.log('Query results:', queryResults.data); // Delete const deleteResult = await client.delete({ collection_name: 'my_collection', ids: [ids[0]], }); console.log('Deleted rows:', deleteResult.delete_cnt); // Drop collection await client.dropCollection({ collection_name: 'my_collection', }); await client.closeConnection(); ``` ## Vector Similarity Search ### Image Search Example ```javascript import { MilvusClient, DataType } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530', }); await client.connectPromise; // Create collection for image embeddings await client.createCollection({ collection_name: 'image_collection', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'image_embedding', data_type: DataType.FloatVector, dim: 512, }, { name: 'image_url', data_type: DataType.VarChar, max_length: 512, }, ], }); // Insert image embeddings await client.insert({ collection_name: 'image_collection', data: [ { image_embedding: Array.from({ length: 512 }, () => Math.random()), image_url: 'https://example.com/image1.jpg', }, // ... more images ], }); // Create index await client.createIndex({ collection_name: 'image_collection', field_name: 'image_embedding', index_type: 'HNSW', metric_type: 'COSINE', }); // Load and search await client.loadCollectionSync({ collection_name: 'image_collection', }); const queryEmbedding = Array.from({ length: 512 }, () => Math.random()); const results = await client.search({ collection_name: 'image_collection', data: [queryEmbedding], limit: 10, output_fields: ['image_url'], }); console.log('Similar images:', results.results); await client.dropCollection({ collection_name: 'image_collection' }); await client.closeConnection(); ``` ## Hybrid Search ### Multi-Vector Search ```javascript import { ConsistencyLevelEnum, DataType, MilvusClient, } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530' }); const textVector = Array.from({ length: 768 }, () => Math.random()); const imageVector = Array.from({ length: 512 }, () => Math.random()); // Create collection with multiple vector fields await client.createCollection({ collection_name: 'hybrid_collection', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'text_vector', data_type: DataType.FloatVector, dim: 768, }, { name: 'image_vector', data_type: DataType.FloatVector, dim: 512, }, ], }); await client.insert({ collection_name: 'hybrid_collection', data: [{ text_vector: textVector, image_vector: imageVector }], }); await client.flushSync({ collection_names: ['hybrid_collection'] }); // Create indexes for both vectors await client.createIndex({ collection_name: 'hybrid_collection', field_name: 'text_vector', index_type: 'HNSW', metric_type: 'L2', }); await client.createIndex({ collection_name: 'hybrid_collection', field_name: 'image_vector', index_type: 'HNSW', metric_type: 'L2', }); // Load collection await client.loadCollectionSync({ collection_name: 'hybrid_collection', }); // Hybrid search const results = await client.hybridSearch({ collection_name: 'hybrid_collection', data: [ { data: textVector, anns_field: 'text_vector', }, { data: imageVector, anns_field: 'image_vector', }, ], rerank: { strategy: 'rrf', params: { k: 60 } }, consistency_level: ConsistencyLevelEnum.Strong, limit: 10, }); console.log('Hybrid search results:', results.results); await client.dropCollection({ collection_name: 'hybrid_collection' }); await client.closeConnection(); ``` ## Dynamic Schema Usage ### Flexible Schema Example ```javascript // Create collection with dynamic fields enabled await client.createCollection({ collection_name: 'dynamic_collection', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, }, ], enable_dynamic_field: true, }); // Insert data with dynamic fields await client.insert({ collection_name: 'dynamic_collection', data: [ { vector: Array.from({ length: 128 }, () => Math.random()), category: 'tech', // Dynamic field tags: ['ai', 'ml'], // Dynamic field metadata: { // Dynamic field author: 'John Doe', date: '2024-01-01', }, }, ], }); ``` ## Partition Key Usage ### Time-Based Partitioning ```javascript // Create collection with partition key await client.createCollection({ collection_name: 'time_partitioned', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, }, { name: 'timestamp', data_type: DataType.Int64, is_partition_key: true, // Partition key }, ], }); // Insert data (automatically partitioned by timestamp) await client.insert({ collection_name: 'time_partitioned', data: [ { vector: Array.from({ length: 128 }, () => Math.random()), timestamp: Date.now(), }, ], }); ``` ## Multi-Database Setup ### Database Management Example ```javascript // Create database await client.createDatabase({ db_name: 'production_db', }); // Create client for specific database const prodClient = new MilvusClient({ address: 'localhost:19530', database: 'production_db', }); // Create collection in production database await prodClient.createCollection({ collection_name: 'prod_collection', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true }, { name: 'vector', data_type: DataType.FloatVector, dim: 4 }, ], }); // List databases const databases = await client.listDatabases(); console.log('Databases:', databases.db_names); await prodClient.dropCollection({ collection_name: 'prod_collection' }); await prodClient.closeConnection(); await client.dropDatabase({ db_name: 'production_db' }); ``` ## Authentication Examples ### Basic Authentication ```javascript const client = new MilvusClient({ address: 'localhost:19530', username: 'root', password: 'Milvus', }); await client.connectPromise; ``` ### Token Authentication (Zilliz Cloud) ```javascript const client = new MilvusClient({ address: 'your-endpoint.zillizcloud.com:443', token: 'your-api-key', ssl: true, }); await client.connectPromise; ``` ## Next.js Integration ### API Route Example ```javascript import { MilvusClient } from '@zilliz/milvus2-sdk-node'; import { NextResponse } from 'next/server'; const client = new MilvusClient({ address: process.env.MILVUS_ADDRESS, token: process.env.MILVUS_TOKEN, }); export async function POST(request) { const { vector } = await request.json(); const results = await client.search({ collection_name: 'my_collection', data: [vector], limit: 10, }); if (results.status.error_code !== 'Success') { return NextResponse.json({ error: results.status.reason }, { status: 502 }); } return NextResponse.json({ results: results.results }); } ``` ## LangChain Integration ### LangChain.js Example Install `@langchain/community`, `@langchain/core`, and the Milvus SDK. This example uses deterministic vectors so you can test the integration locally without an embedding service. Use your embedding model for real documents. ```javascript import { Milvus } from '@langchain/community/vectorstores/milvus'; const embed = (text) => (text.includes('vector') ? [1, 0] : [0, 1]); const embeddings = { embedDocuments: async (texts) => texts.map(embed), embedQuery: async (text) => embed(text), }; const vectorStore = await Milvus.fromTexts( [ 'Milvus stores vector embeddings', 'LangChain connects application components', ], [{ topic: 'milvus' }, { topic: 'langchain' }], embeddings, { url: process.env.MILVUS_ADDRESS ?? 'localhost:19530', clientConfig: { token: process.env.MILVUS_TOKEN }, collectionName: 'langchain_collection', } ); const results = await vectorStore.similaritySearch('vector search', 1); console.log(results.map((document) => document.pageContent)); ``` ## Cloud Deployment ### Zilliz Cloud Example ```javascript const client = new MilvusClient({ address: 'your-endpoint.zillizcloud.com:443', token: 'your-api-key', ssl: true, timeout: 60000, maxRetries: 5, }); await client.connectPromise; const { data, status } = await client.listCollections(); if (status.error_code !== 'Success') throw new Error(status.reason); console.log(data.map((collection) => collection.name)); await client.closeConnection(); ``` ## Error Handling Pattern ### Comprehensive Error Handling ```javascript async function safeOperation(operation) { try { return await operation(); } catch (error) { if (error.error_code === 'CollectionNotExists') { console.error('Collection does not exist'); } else if (error.error_code === 'IllegalArgument') { console.error('Invalid argument:', error.reason); } else { console.error('Unexpected error:', error); } throw error; } } // Usage await safeOperation(() => client.createCollection({ collection_name: 'my_collection', fields: schema, }) ); ``` ## Next Steps - Explore [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) - Check out [API Reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - Read [Troubleshooting](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/) --- # Configure the Milvus Client Configure the Milvus Node.js client with an address, credentials, TLS, timeouts, retries, and connection pooling. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/ ## Section links - [Basic Configuration](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#basic-configuration) - [Configuration Options](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#configuration-options) - [Address and Endpoints](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#address-and-endpoints) - [Authentication](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#authentication) - [Username and Password](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#username-and-password) - [Token (for Zilliz Cloud)](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#token-for-zilliz-cloud) - [SSL/TLS Configuration](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#ssltls-configuration) - [gRPC message compression](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#grpc-message-compression) - [Timeout Settings](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#timeout-settings) - [Retry Configuration](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#retry-configuration) - [Database Selection](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#database-selection) - [Logging Configuration](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#logging-configuration) - [Connection Pooling](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#connection-pooling) - [gRPC Channel Options](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#grpc-channel-options) - [Connect Reserved Options](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#connect-reserved-options) - [Environment-Specific Configuration](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#environment-specific-configuration) - [Development](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#development) - [Production](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#production) - [Zilliz Cloud Configuration](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#zilliz-cloud-configuration) - [Complete Configuration Example](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#complete-configuration-example) - [Configuration Interface](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#configuration-interface) - [Request Tracing](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#request-tracing) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#next-steps) - [Client telemetry (SDK 3.0.5)](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/#client-telemetry-sdk-305) Create a gRPC `MilvusClient` with your cluster’s `address` and credentials if authentication is enabled. Use a [REST endpoint](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#constructor) when configuring `HttpClient`. | Option | What it controls | | --- | --- | | `address` | Required Milvus gRPC address, for example `localhost:19530` or your Zilliz Cloud endpoint. | | `token` | Zilliz Cloud API key or a `username:password` token. | | `username` / `password` | Separate credentials for an authenticated deployment. | | `database` | Database to use after connecting. Defaults to `default`. | | `ssl` / `tls` | Enable TLS and configure certificates or server identity. | | `timeout` | Request timeout in milliseconds. | | `pool` | gRPC connection pool settings, such as minimum and maximum sizes. | | `maxRetries` | Maximum retry count for retryable gRPC failures. Defaults to 3. | | `telemetry` | Client metrics, heartbeats, and server commands. Enabled by default. | ## Basic Configuration The simplest configuration requires only the Milvus server address: ```javascript const client = new MilvusClient({ address: 'localhost:19530', }); ``` ## Configuration Options ### Address and Endpoints ```javascript const client = new MilvusClient({ address: 'localhost:19530', // Required: Milvus server address }); ``` ### Authentication #### Username and Password ```javascript const client = new MilvusClient({ address: 'localhost:19530', username: 'root', password: 'Milvus', }); ``` #### Token (for Zilliz Cloud) ```javascript const client = new MilvusClient({ address: 'https://your-endpoint.zillizcloud.com:443', token: 'your-api-key', // Can be 'username:password' or API key }); ``` ### SSL/TLS Configuration Enable SSL/TLS encryption: ```javascript const client = new MilvusClient({ address: 'localhost:19530', ssl: true, tls: { rootCertPath: '/path/to/ca.pem', serverName: 'milvus.example.com', }, }); ``` Full TLS options: ```javascript const client = new MilvusClient({ address: 'localhost:19530', ssl: true, tls: { // Certificate Authority PEM file path rootCertPath: '/path/to/ca.pem', // Or certificate buffer rootCert: Buffer.from('...'), // Private key path (for client authentication) privateKeyPath: '/path/to/key.pem', // Or private key buffer privateKey: Buffer.from('...'), // Certificate chain path certChainPath: '/path/to/cert.pem', // Or certificate buffer certChain: Buffer.from('...'), // Server name for SNI serverName: 'milvus.example.com', // Skip certificate verification (not recommended for production) skipCertCheck: false, // Additional verify options verifyOptions: {}, }, }); ``` ### gRPC message compression Set `grpcCompression` when creating the client to compress requests and accept compressed responses. ```javascript const client = new MilvusClient({ address: 'localhost:19530', grpcCompression: 'zstd', }); ``` The default is `'identity'`. Use `'gzip'` or `'zstd'` with an endpoint that supports the selected encoding. Zstd uses Node’s built-in codec on Node 22.15+, 23.8+, and 24+. Each client configures its own channels. Small messages can grow after compression. ### Timeout Settings Configure request timeouts: ```javascript const client = new MilvusClient({ address: 'localhost:19530', timeout: 30000, // 30 seconds in milliseconds }); ``` ### Retry Configuration Configure retry behavior: ```javascript const client = new MilvusClient({ address: 'localhost:19530', maxRetries: 3, // Maximum number of retries retryDelay: 1000, // Delay between retries in milliseconds }); ``` ### Database Selection Specify which database to use: ```javascript const client = new MilvusClient({ address: 'localhost:19530', database: 'my_database', }); ``` ### Logging Configuration Configure logging levels: ```javascript const client = new MilvusClient({ address: 'localhost:19530', logLevel: 'debug', // 'error', 'warn', 'info', 'debug' logPrefix: 'milvus-client', // Prefix for log messages }); ``` ### Connection Pooling Configure connection pool options: ```javascript const client = new MilvusClient({ address: 'localhost:19530', pool: { min: 2, // Minimum pool size max: 10, // Maximum pool size idleTimeoutMillis: 30000, // Idle timeout }, }); ``` ### gRPC Channel Options Advanced gRPC channel configuration: ```javascript const client = new MilvusClient({ address: 'localhost:19530', channelOptions: { 'grpc.keepalive_time_ms': 30000, 'grpc.keepalive_timeout_ms': 5000, 'grpc.keepalive_permit_without_calls': 1, 'grpc.http2.max_pings_without_data': 0, 'grpc.http2.min_time_between_pings_ms': 10000, 'grpc.http2.min_ping_interval_without_data_ms': 300000, }, }); ``` ### Connect Reserved Options Use `option` to pass reserved key-value metadata in the initial Milvus `Connect` request. These values are sent as `client_info.reserved` and are useful for deployment-specific routing, attribution, or internal integrations. ```javascript const client = new MilvusClient({ address: 'localhost:19530', option: { app: 'recommendation-service', environment: 'production', }, }); ``` `option` values must be strings. ## Environment-Specific Configuration ### Development ```javascript const client = new MilvusClient({ address: process.env.MILVUS_ADDRESS || 'localhost:19530', logLevel: 'debug', }); ``` ### Production ```javascript const client = new MilvusClient({ address: process.env.MILVUS_ADDRESS, username: process.env.MILVUS_USERNAME, password: process.env.MILVUS_PASSWORD, ssl: true, tls: { rootCertPath: process.env.MILVUS_CA_CERT, }, timeout: 60000, maxRetries: 5, logLevel: 'warn', }); ``` ## Zilliz Cloud Configuration For Zilliz Cloud, use the endpoint and API key: ```javascript const client = new MilvusClient({ address: 'https://your-endpoint.zillizcloud.com:443', token: 'your-api-key', ssl: true, }); ``` ## Complete Configuration Example ```javascript const client = new MilvusClient({ // Required address: 'localhost:19530', // Authentication (choose one) username: 'root', password: 'Milvus', // OR token: 'api-key', // SSL/TLS ssl: true, tls: { rootCertPath: '/path/to/ca.pem', serverName: 'milvus.example.com', }, // Timeouts and retries timeout: 30000, maxRetries: 3, retryDelay: 1000, // Database database: 'default', // Logging logLevel: 'info', logPrefix: 'milvus', // Connection pooling pool: { min: 2, max: 10, }, }); ``` ## Configuration Interface The `ClientConfig` interface includes: ```typescript interface ClientConfig { address: string; // Required token?: string; ssl?: boolean; username?: string; password?: string; channelOptions?: ChannelOptions; option?: Record; timeout?: number | string; maxRetries?: number; retryDelay?: number; database?: string; logLevel?: string; logPrefix?: string; tls?: { rootCertPath?: string; rootCert?: Buffer; privateKeyPath?: string; privateKey?: Buffer; certChainPath?: string; certChain?: Buffer; verifyOptions?: Record; serverName?: string; skipCertCheck?: boolean; }; pool?: Options; loaderOptions?: LoaderOption; telemetry?: TelemetryConfig; trace?: boolean; } ``` ## Request Tracing All API requests support optional trace IDs for tracking and debugging: ```javascript // Add trace ID to any request await client.listCollections({ client_request_id: 'trace-id-123', // Optional trace ID }); // Alternative format (compatible with pymilvus) await client.listCollections({ 'client-request-id': 'trace-id-123', }); ``` **Features:** - Automatic timestamp: Every request includes `client-request-unixmsec` - Trace ID support: Add `client_request_id` or `client-request-id` to track requests - Global support: All API methods automatically support trace IDs - Priority: `client_request_id` takes priority over `client-request-id` (JavaScript convention) For more details, see [Request Tracing](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#request-tracing-traceid) in Advanced Features. ## Next Steps - Learn about [Data Types & Schemas](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/) - Explore [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/) - Check out [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) for production configurations ## Client telemetry (SDK 3.0.5) `telemetry` configures heartbeat reporting and is enabled by default. See [Client Telemetry](https://milvus-io.github.io/milvus-sdk-node/advanced/client-telemetry/) for defaults, collected information, disabling, and `getTelemetry()` inspection. `TelemetryConfig` is exported from the package root. --- # Data Types and Collection Schemas Design Milvus collection schemas in Node.js using scalar and vector data types, a primary key, and optional dynamic fields. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/ ## Section links - [Supported Data Types](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#supported-data-types) - [Scalar Types](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#scalar-types) - [Integer Types](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#integer-types) - [Floating Point Types](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#floating-point-types) - [Boolean Type](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#boolean-type) - [String Types](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#string-types) - [JSON Type](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#json-type) - [Geometry](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#geometry) - [Timestamptz](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#timestamptz) - [Vector Types](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#vector-types) - [FloatVector](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#floatvector) - [BinaryVector](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#binaryvector) - [SparseFloatVector](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#sparsefloatvector) - [Float16Vector](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#float16vector) - [BFloat16Vector](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#bfloat16vector) - [Int8Vector](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#int8vector) - [Nullable Vector Fields](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#nullable-vector-fields) - [Complex Types](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#complex-types) - [Array](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#array) - [ArrayOfVector](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#arrayofvector) - [StructArray](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#structarray) - [Field Schema Definition](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#field-schema-definition) - [Primary Key Fields](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#primary-key-fields) - [Collection Schema Creation](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#collection-schema-creation) - [Basic Schema](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#basic-schema) - [Schema with Multiple Vector Fields](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#schema-with-multiple-vector-fields) - [Schema with Consistency Level](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#schema-with-consistency-level) - [Dynamic Schema](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#dynamic-schema) - [Schema Validation](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#schema-validation) - [Schema Best Practices](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#schema-best-practices) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#next-steps) - [Text](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#text) Milvus supports various data types for storing different kinds of data. Understanding these types is essential for designing effective schemas. ## Supported Data Types ### Scalar Types #### Integer Types - **Int8**: 8-bit signed integer (-128 to 127) - **Int16**: 16-bit signed integer (-32,768 to 32,767) - **Int32**: 32-bit signed integer - **Int64**: 64-bit signed integer ```javascript import { DataType } from '@zilliz/milvus2-sdk-node'; const ageField = { name: 'age', data_type: DataType.Int64, }; ``` #### Floating Point Types - **Float**: 32-bit floating point number - **Double**: 64-bit floating point number ```javascript { name: 'score', data_type: DataType.Float, } ``` #### Boolean Type - **Bool**: Boolean value (true/false) ```javascript { name: 'is_active', data_type: DataType.Bool, } ``` #### String Types - **VarChar**: Variable-length string (requires `max_length`) ```javascript { name: 'title', data_type: DataType.VarChar, max_length: 256, } ``` #### JSON Type - **JSON**: JSON object ```javascript { name: 'metadata', data_type: DataType.JSON, } ``` #### Geometry Geospatial data stored in WKT (Well-Known Text) format. ```javascript const locationField = { name: 'location', data_type: DataType.Geometry, }; // Insert as WKT string const row = { location: 'POINT(121.47 31.23)' }; ``` #### Timestamptz Timestamp with timezone information. ```javascript { name: 'created_at', data_type: DataType.Timestamptz, } ``` ### Vector Types #### FloatVector Dense float vector (most common): ```javascript { name: 'embedding', data_type: DataType.FloatVector, dim: 128, // Required: dimension of the vector } ``` #### BinaryVector Binary vector (for binary embeddings): ```javascript { name: 'binary_embedding', data_type: DataType.BinaryVector, dim: 128, // Must be multiple of 8 } ``` #### SparseFloatVector Sparse vectors store only non-zero values with their indices. Commonly used for BM25 full-text search and keyword-based retrieval. ```javascript { name: 'sparse_vector', data_type: DataType.SparseFloatVector, } ``` The SDK accepts sparse vectors as dictionaries, dense arrays with missing positions, CSR objects, or COO arrays of objects. For example: **Dictionary format** (recommended): ```javascript // Keys are indices, values are float weights const sparseVector = { 10: 0.5, 100: 0.3, 500: 0.8, 1200: 0.1 }; ``` **COO format:** ```javascript const sparseVector = [ { index: 10, value: 0.5 }, { index: 100, value: 0.3 }, { index: 500, value: 0.8 }, { index: 1200, value: 0.1 }, ]; ``` Note: Dimension is determined automatically from the maximum index across all vectors. #### Float16Vector 16-bit float vector: ```javascript { name: 'f16_embedding', data_type: DataType.Float16Vector, dim: 128, } ``` #### BFloat16Vector BFloat16 vector: ```javascript { name: 'bf16_embedding', data_type: DataType.BFloat16Vector, dim: 128, } ``` #### Int8Vector 8-bit integer vector: ```javascript { name: 'int8_embedding', data_type: DataType.Int8Vector, dim: 128, } ``` #### Nullable Vector Fields Vector fields can be marked as nullable. Insert or upsert `null` for rows that do not have an embedding yet; query and search results return `null` for those fields. ```javascript const optionalEmbedding = { name: 'optional_embedding', data_type: DataType.FloatVector, dim: 128, nullable: true, }; await client.insert({ collection_name: 'my_collection', data: [ { id: 1, optional_embedding: Array(128).fill(0.1) }, { id: 2, optional_embedding: null }, ], }); ``` Nullable vector payloads are supported for `FloatVector`, `BinaryVector`, `Float16Vector`, `BFloat16Vector`, `SparseFloatVector`, and `Int8Vector`. ### Complex Types #### Array Array of scalar values: ```javascript { name: 'tags', data_type: DataType.Array, element_type: DataType.VarChar, max_capacity: 100, max_length: 128, } ``` #### ArrayOfVector Use a vector child field in a StructArray to store multiple vectors per entity. The SDK encodes that child as `ArrayOfVector` when sending the schema to Milvus. Declare each child with its vector type and dimension, as shown below. #### StructArray Milvus 3.0 A StructArray is an `Array` whose elements share a nested struct schema. Define the child fields with `fields` and set `element_type` to `DataType.Struct`. ```javascript { name: 'features', data_type: DataType.Array, element_type: DataType.Struct, max_capacity: 16, nullable: true, fields: [ { name: 'label', data_type: DataType.VarChar, max_length: 64 }, { name: 'score', data_type: DataType.Int32 }, { name: 'active', data_type: DataType.Bool }, { name: 'embedding', data_type: DataType.FloatVector, dim: 128 }, ], } ``` Insert arrays of objects that match the child schema: ```javascript await client.insert({ collection_name: 'documents', data: [ { id: 1, features: [ { label: 'title', score: 95, active: true, embedding: Array(128).fill(0.1), }, ], }, ], }); ``` Use bracketed paths for child fields and `element_filter` when predicates must match values from the same array element: ```javascript const rows = await client.query({ collection_name: 'documents', filter: 'element_filter(features, $[score] >= 90 AND $[active] == true)', output_fields: ['id', 'features[label]', 'features[score]'], }); ``` Vector and scalar child fields can be indexed with paths such as `features[embedding]`, `features[score]`, or `features[label]`. Element-level query and search results include an `offset` for the matching StructArray element. Separate StructArray fields may reuse the same child names. To add a StructArray to an existing collection with `addCollectionField()`, set `nullable: true` so existing rows remain valid. On Milvus 3.0.6+, add a child to an existing StructArray with a `parent[child]` field name and `nullable: true`. The parent can be nullable or non-nullable; the server inherits its row nullability and capacity. Existing struct elements and new elements that omit the child receive a null child value. ```typescript await client.addCollectionField({ collection_name: 'my_collection', field: { name: 'items[score]', data_type: DataType.Int64, nullable: true }, }); await client.addCollectionField({ collection_name: 'my_collection', field: { name: 'items[tags]', data_type: DataType.Array, element_type: DataType.VarChar, max_capacity: 8, max_length: 64, nullable: true, }, }); await client.query({ collection_name: 'my_collection', filter: 'MATCH_ANY(items, ARRAY_CONTAINS($[tags], "red"))', output_fields: ['id', 'items'], }); await client.dropCollectionField({ collection_name: 'my_collection', field_name: 'items[tags]', }); ``` This example assumes an existing `items` StructArray and an `id` primary key. For an Array child, `max_capacity` limits that child’s Array and `max_length` limits each VarChar element. `nullable: true` allows the child itself to be missing or null; `element_nullable` describes null elements *inside* that child’s Array and does not replace `nullable: true` when adding a child. Array children are supported on Milvus 3.0.6+. Nullable vector children are also supported on Milvus 3.0.6+ for FloatVector, BinaryVector, Float16Vector, BFloat16Vector, and Int8Vector. Missing or null children retain their positions within each struct element. Create the child vector index before loading a collection that declares the child at creation. Milvus 3.0.6 rejects JSON children inside a StructArray. ## Field Schema Definition Each field in a collection schema must include: ```javascript { name: 'field_name', // Required: field name data_type: DataType.Int64, // Required: data type description: 'Field description', // Optional is_primary_key: false, // Optional: primary key flag autoID: false, // Optional: auto-generate IDs max_length: 256, // Required for VarChar dim: 128, // Required for vector types nullable: false, // Optional: allow null values default_value: undefined, // Optional scalar default value external_field: undefined, // Optional: source field name for external collections } ``` ### Primary Key Fields Every collection must have exactly one primary key field: ```javascript { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, // Let Milvus generate IDs automatically } ``` Or with manual IDs: ```javascript { name: 'user_id', data_type: DataType.Int64, is_primary_key: true, autoID: false, // You provide IDs } ``` ## Collection Schema Creation ### Basic Schema ```javascript import { MilvusClient, DataType } from '@zilliz/milvus2-sdk-node'; const schema = [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, }, { name: 'text', data_type: DataType.VarChar, max_length: 256, }, ]; await client.createCollection({ collection_name: 'my_collection', fields: schema, }); ``` ### Schema with Multiple Vector Fields ```javascript const schema = [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'text_vector', data_type: DataType.FloatVector, dim: 768, }, { name: 'image_vector', data_type: DataType.FloatVector, dim: 512, }, { name: 'metadata', data_type: DataType.JSON, }, ]; ``` ### Schema with Consistency Level ```javascript await client.createCollection({ collection_name: 'my_collection', fields: schema, consistency_level: 'Bounded', // 'Strong', 'Session', 'Bounded', 'Eventually' }); ``` ## Dynamic Schema Enable dynamic schema to add fields without redefining the schema: ```javascript await client.createCollection({ collection_name: 'my_collection', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, }, ], enable_dynamic_field: true, // Enable dynamic fields }); ``` With dynamic schema enabled, you can insert data with additional fields: ```javascript await client.insert({ collection_name: 'my_collection', data: [ { vector: [ /* ... */ ], dynamic_field_1: 'value1', // Automatically added dynamic_field_2: 123, // Automatically added }, ], }); ``` ## Schema Validation The SDK validates schemas before creating collections. Common validation errors: - Missing primary key field - Multiple primary key fields - Missing dimension for vector fields - Missing max_length for VarChar fields - Invalid dimension for BinaryVector (must be multiple of 8) ## Schema Best Practices 1. **Choose appropriate data types**: Use Int64 for IDs, FloatVector for embeddings 2. **Set reasonable max_length**: For VarChar fields, set max_length based on expected content 3. **Use autoID**: Let Milvus generate IDs unless you have specific requirements 4. **Enable dynamic schema**: For flexible schemas that may change over time 5. **Document fields**: Use descriptions to document field purposes ## Next Steps - Learn about [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/) - Explore [Data Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/) - Check out [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) ## Text SDK 3.0.4 adds `DataType.Text` (25) for variable-length text without a `max_length` setting. It requires a Milvus deployment using **StorageV3**. Use VarChar for primary/partition keys and array string elements; Text cannot be used for these roles. Do not set `max_length` on Text fields. ```typescript const contentField = { name: 'content', data_type: DataType.Text, nullable: true, enable_analyzer: true, enable_match: true, analyzer_params: { tokenizer: 'standard' }, }; ``` Add this field alongside a primary key and vector field in `createCollection({ fields })`. Insert and upsert ordinary JavaScript strings (or `null` for nullable fields), and include `content` in `output_fields` to retrieve it. Text supports analyzer-based matching and BM25 input. Request and server resource limits still apply even though the schema has no VarChar length limit. --- # Create and Use Databases Create and select Milvus databases in Node.js, organize collections by database, and configure database properties. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/ ## Section links - [Creating a Database](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#creating-a-database) - [Listing Databases](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#listing-databases) - [Describing a Database](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#describing-a-database) - [Altering Database Properties](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#altering-database-properties) - [Dropping Database Properties](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#dropping-database-properties) - [Dropping a Database](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#dropping-a-database) - [Multi-Database Usage Patterns](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#multi-database-usage-patterns) - [Switching Between Databases](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#switching-between-databases) - [Working with Multiple Databases](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#working-with-multiple-databases) - [Database Isolation](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#database-isolation) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#best-practices) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/#next-steps) Milvus supports multiple databases, allowing you to organize collections into logical groups. This guide covers all database operations. ## Creating a Database Create a new database: ```javascript await client.createDatabase({ db_name: 'my_database', }); ``` Create a database with properties: ```javascript await client.createDatabase({ db_name: 'my_database', properties: { owner: 'analytics-team', environment: 'production', }, }); ``` ## Listing Databases List all databases: ```javascript const result = await client.listDatabases(); console.log('Databases:', result.db_names); // Output: ['default', 'my_database'] ``` ## Describing a Database Get detailed information about a database: ```javascript const result = await client.describeDatabase({ db_name: 'my_database', }); console.log('Database info:', result); ``` ## Altering Database Properties Modify database properties: ```javascript await client.alterDatabaseProperties({ db_name: 'my_database', properties: { owner: 'search-team', environment: 'staging', }, }); ``` ## Dropping Database Properties Remove specific properties from a database: ```javascript await client.dropDatabaseProperties({ db_name: 'my_database', properties: ['environment'], }); ``` ## Dropping a Database Delete a database (all collections in the database will be deleted): ```javascript await client.dropDatabase({ db_name: 'my_database', }); ``` ## Multi-Database Usage Patterns ### Switching Between Databases When creating a client, specify the database: ```javascript const client = new MilvusClient({ address: 'localhost:19530', database: 'my_database', // Set default database }); ``` ### Working with Multiple Databases Create separate clients for different databases: ```javascript await client.createDatabase({ db_name: 'database1' }); await client.createDatabase({ db_name: 'database2' }); const db1Client = new MilvusClient({ address: 'localhost:19530', database: 'database1', }); const db2Client = new MilvusClient({ address: 'localhost:19530', database: 'database2', }); console.log('database1:', (await db1Client.listCollections()).data); console.log('database2:', (await db2Client.listCollections()).data); await db1Client.closeConnection(); await db2Client.closeConnection(); ``` ### Database Isolation Each database is isolated: - Collections in different databases are completely separate - Operations on one database don’t affect others - Users and roles can have different permissions per database ## Best Practices 1. **Use databases for logical separation**: Organize collections by application, environment, or team 2. **Default database**: The `default` database is created automatically 3. **Database naming**: Use descriptive names that reflect the purpose 4. **Permissions**: Configure user permissions at the database level for security ## Next Steps - Learn about [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/) - Explore [User & Role Management](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/) --- # Insert and Upsert Entities Insert and upsert Milvus entities from Node.js, prepare rows that match the collection schema, and handle write results. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/ ## Section links - [Inserting Data](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#inserting-data) - [Basic Insert](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#basic-insert) - [Insert with AutoID](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#insert-with-autoid) - [Insert into Specific Partition](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#insert-into-specific-partition) - [Batch Insertion](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#batch-insertion) - [Data Format](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#data-format) - [Vector Data Formats](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#vector-data-formats) - [FloatVector](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#floatvector) - [BinaryVector](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#binaryvector) - [SparseFloatVector](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#sparsefloatvector) - [Float16Vector / BFloat16Vector](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#float16vector--bfloat16vector) - [Scalar Data Formats](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#scalar-data-formats) - [Upserting Data](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#upserting-data) - [Conditional upsert](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#conditional-upsert) - [Partial Update](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#partial-update) - [Partial Array Upsert Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#partial-array-upsert-milvus-30) - [Replace a Value by Path Milvus 3.0.6](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#replace-a-value-by-path-milvus-306) - [Insert Transformers](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#insert-transformers) - [Insert Response](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#insert-response) - [Data Validation](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#data-validation) - [Error Handling](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#error-handling) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#best-practices) - [Complete Example](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#complete-example) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#next-steps) This guide covers inserting and updating data in Milvus collections. ## Inserting Data ### Basic Insert Insert data into a collection: ```javascript await client.insert({ collection_name: 'my_collection', data: [ { id: 1, vector: [0.1, 0.2, 0.3, 0.4], text: 'Hello Milvus', }, { id: 2, vector: [0.5, 0.6, 0.7, 0.8], text: 'Vector database', }, ], }); ``` ### Insert with AutoID If your collection uses autoID, omit the ID field: ```javascript await client.insert({ collection_name: 'my_collection', data: [ { vector: [0.1, 0.2, 0.3, 0.4], text: 'Hello Milvus', }, { vector: [0.5, 0.6, 0.7, 0.8], text: 'Vector database', }, ], }); ``` ### Insert into Specific Partition Insert data into a specific partition: ```javascript await client.insert({ collection_name: 'my_collection', partition_name: 'partition_1', data: [ { vector: [0.1, 0.2, 0.3, 0.4], text: 'Data for partition 1', }, ], }); ``` ### Batch Insertion Insert large amounts of data efficiently: ```javascript const batchSize = 1000; const allData = [ /* large array of data */ ]; for (let i = 0; i < allData.length; i += batchSize) { const batch = allData.slice(i, i + batchSize); await client.insert({ collection_name: 'my_collection', data: batch, }); } ``` ## Data Format ### Vector Data Formats #### FloatVector ```javascript { vector: [0.1, 0.2, 0.3, 0.4, /* ... */], // Array of numbers } ``` #### BinaryVector ```javascript { binary_vector: [0b10101010, 0b01010101], // Two bytes for dim = 16 } ``` #### SparseFloatVector Multiple formats supported: ```javascript // Array format const arrayRow = { sparse_vector: [1.0, undefined, undefined, 2.5, undefined], }; // Dictionary format const dictionaryRow = { sparse_vector: { 0: 1.0, 3: 2.5 }, }; // CSR format const csrRow = { sparse_vector: { indices: [0, 3], values: [1.0, 2.5], }, }; // COO format const cooRow = { sparse_vector: [ { index: 0, value: 1.0 }, { index: 3, value: 2.5 }, ], }; ``` #### Float16Vector / BFloat16Vector ```javascript { vector: [0.1, 0.2, 0.3, 0.4], // Array of numbers (will be converted) } ``` ### Scalar Data Formats ```javascript { id: 123, // Int64 age: 25, // Int64 score: 98.5, // Float is_active: true, // Bool name: 'John Doe', // VarChar metadata: { // JSON category: 'tech', tags: ['ai', 'ml'], }, } ``` ## Upserting Data Upsert updates existing entities or inserts new ones: ```javascript await client.upsert({ collection_name: 'my_collection', data: [ { id: 1, vector: [0.9, 0.8, 0.7, 0.6], // Update existing entity text: 'Updated text', }, { id: 999, vector: [0.1, 0.2, 0.3, 0.4], // Insert new entity text: 'New text', }, ], }); ``` ### Conditional upsert Use a business version to prevent older events from overwriting newer rows. Every serving Proxy must run Milvus 3.0.7 or later. Older proxies can ignore the condition and apply the write unconditionally. ```typescript const result = await client.upsert({ collection_name: 'products', data: [{ id: 42, revision: 12, stock: 8 }], write_condition: { field: 'revision', op: 'gt', on_missing: 'skip' }, }); ``` Each input row supplies a distinct primary key and a version in an ordinary Int8, Int16, Int32 or Int64 column. Use `gt` for strictly newer versions or `gte` to also accept equal versions. A condition implies a partial update, so existing rows keep omitted columns. For a missing primary key, `insert` (default) applies the collection’s normal insertion rules, `skip` ignores that row, and `error` rejects the write. Use `skip` if deleted or TTL-expired rows must stay absent. A stored null version accepts an incoming integer. An incoming null uses the field default if present and otherwise fails validation. The version field permits only `REPLACE`. With `gte`, this restriction applies to every field. On success, `succ_index` contains the zero-based input indexes of the written rows in the same order as the returned IDs. An all-skipped batch succeeds with a zero count and empty indexes. With the HTTP client, use `writeCondition: { field: 'revision', op: 'gt', onMissing: 'skip' }` and read `data.succIndex`. After an execution error (code 112) or a lost response, writes may already have committed. ### Partial Update Update only specific fields: ```javascript await client.upsert({ collection_name: 'my_collection', partial_update: true, data: [ { id: 1, text: 'Updated text only', // Only update text field // vector field not included, will remain unchanged }, ], }); ``` ### Partial Array Upsert Milvus 3.0 For Array fields, use `field_ops` to append values to or remove values from the existing array instead of replacing the whole field. ```javascript import { FieldPartialUpdateOpType } from '@zilliz/milvus2-sdk-node'; await client.upsert({ collection_name: 'my_collection', data: [ { id: 1, tags: ['new-tag'], // Appended to the existing tags array scores: [3], // Removed from the existing scores array }, ], field_ops: [ { field_name: 'tags', op: FieldPartialUpdateOpType.ARRAY_APPEND }, { field_name: 'scores', op: FieldPartialUpdateOpType.ARRAY_REMOVE }, ], }); ``` You can also pass operation names as strings: ```javascript await client.upsert({ collection_name: 'my_collection', data: [{ id: 1, tags: ['urgent'] }], field_ops: [{ field_name: 'tags', op: 'ARRAY_APPEND' }], }); ``` Notes: - `field_ops` is supported only by `upsert()`. - `ARRAY_APPEND` and `ARRAY_REMOVE` apply to Array fields. - The primary key must be included in each upsert row. - Fields not included in the upsert row remain unchanged. - `ARRAY_APPEND` must not make the array exceed its `max_capacity`. - `ARRAY_REMOVE` removes matching values from the existing array. - When `field_ops` is provided, the SDK automatically sends `partial_update: true`. ### Replace a Value by Path Milvus 3.0.6 Use `PATH_REPLACE` to replace one value in an existing row. Each Array or StructArray operand contains one element. A JSON operand is the new value itself. ```typescript await client.upsert({ collection_name: 'my_collection', data: [ { id: 1, scores: [100], items: [{ label: 'updated' }], settings: false }, ], field_ops: [ { field_name: 'scores', op: 'PATH_REPLACE', path: '[0]' }, { field_name: 'items', op: 'PATH_REPLACE', path: '[0][label]' }, { field_name: 'settings', op: 'PATH_REPLACE', path: '["enabled"]' }, ], }); ``` Use zero-based indexes like `[0]`. For a whole StructArray element, supply all its children. For a single child, use `[0][child]` and supply only that child. Quote JSON object keys, as in `["settings"][0]["enabled"]`. The primary key and the selected value must already exist. With `HttpClient`, use `collectionName` and pass operations as `fieldOps: [{ fieldName: 'scores', op: 'PATH_REPLACE', path: '[0]' }]`. ## Insert Transformers For Float16 and BFloat16 vectors, use transformers: ```javascript import { DataType, f32ArrayToF16Bytes } from '@zilliz/milvus2-sdk-node'; await client.insert({ collection_name: 'my_collection', data: [ { vector: [0.1, 0.2, 0.3, 0.4], // f32 array }, ], transformers: { [DataType.Float16Vector]: f32ArrayToF16Bytes, }, }); ``` ## Insert Response The insert operation returns mutation results: ```javascript const result = await client.insert({ collection_name: 'my_collection', data: [ /* ... */ ], }); console.log('IDs:', result.IDs); // Array of inserted IDs console.log('Insert count:', result.insert_cnt); console.log('Delete count:', result.delete_cnt); console.log('Upsert count:', result.upsert_cnt); console.log('Timestamp:', result.timestamp); ``` ## Data Validation The SDK validates data before insertion: - **Field existence**: All fields must exist in the collection schema - **Data types**: Values must match field data types - **Vector dimensions**: Vector length must match field dimension - **Binary vectors**: Length must be dimension / 8 - **VarChar length**: String length must not exceed max_length ## Error Handling Handle insertion errors: ```javascript try { await client.insert({ collection_name: 'my_collection', data: [ /* ... */ ], }); } catch (error) { if (error.message.includes('field does not exist')) { console.error('Invalid field name'); } else if (error.message.includes('dimension')) { console.error('Vector dimension mismatch'); } else { console.error('Insert failed:', error); } } ``` ## Best Practices 1. **Batch inserts**: Insert data in batches (1000-10000 entities per batch) 2. **Flush after insertion**: Call `flush()` after inserting data to ensure persistence 3. **Use autoID**: Let Milvus generate IDs unless you have specific requirements 4. **Validate data**: Validate data before insertion to avoid errors 5. **Handle errors**: Always wrap insertions in try-catch blocks 6. **Use upsert for updates**: Use `upsert()` instead of delete + insert for updates ## Complete Example ```javascript import { MilvusClient, DataType } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530', }); await client.connectPromise; // Create collection await client.createCollection({ collection_name: 'my_collection', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, }, { name: 'text', data_type: DataType.VarChar, max_length: 256, }, ], }); // Insert data const result = await client.insert({ collection_name: 'my_collection', data: [ { vector: Array.from({ length: 128 }, () => Math.random()), text: 'First document', }, { vector: Array.from({ length: 128 }, () => Math.random()), text: 'Second document', }, ], }); console.log('Inserted IDs:', result.IDs); // Flush to ensure data is persisted await client.flushSync({ collection_names: ['my_collection'], }); await client.closeConnection(); ``` ## Next Steps - Learn about [Query Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/) - Explore [Delete Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/) - Check out [Data Management](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/) --- # BulkWriter & Bulk Import Generate JSON or Parquet files with BulkWriter, upload them to object storage, and submit a Milvus bulk import from Node.js. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/ ## Section links - [When to Use](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#when-to-use) - [Quick Start](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#quick-start) - [Options](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#options) - [JSON vs Parquet](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#json-vs-parquet) - [Full Workflow: Write, Upload, Import](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#full-workflow-write-upload-import) - [Streaming from Any Data Source](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#streaming-from-any-data-source) - [Collection Clone via Query Iterator](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#collection-clone-via-query-iterator) - [Progress Events](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#progress-events) - [Dynamic Fields](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#dynamic-fields) - [Supported Types](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#supported-types) - [Sparse Vector Formats](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#sparse-vector-formats) - [Timestamptz](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#timestamptz) - [API Reference](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#api-reference) - [`BulkWriter`](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#bulkwriter) - [`bulkInsert` / Import APIs](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/#bulkinsert--import-apis) Generate Milvus-compatible files (JSON/Parquet) on the client side and import them via `bulkInsert`. This bypasses the WAL and real-time indexing pipeline, making it ideal for large-scale offline data loading. ## When to Use | Scenario | Use `insert()` | Use `BulkWriter` + `bulkInsert` | | --- | --- | --- | | Real-time writes (<10k rows) | **Yes** | No | | Batch import (100k+ rows) | Possible | **Yes** | | Offline data pipeline | No | **Yes** | | Minimize Milvus write pressure | No | **Yes** | | Data migration between clusters | No | **Yes** | | File-based import (CSV/JSON) | No | **Yes** | ## Quick Start ```javascript import { BulkWriter, DataType } from '@zilliz/milvus2-sdk-node'; // 1. Define schema (same as createCollection) const schema = { fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128 }, { name: 'text', data_type: DataType.VarChar, max_length: 512 }, { name: 'metadata', data_type: DataType.JSON }, ], }; // 2. Create writer const writer = new BulkWriter({ schema, localPath: './bulk_output', format: 'parquet', // or 'json' }); // 3. Append rows const rows = [ { vector: Array(128).fill(0.1), text: 'A sample document', metadata: { source: 'example.txt' }, }, ]; for (const row of rows) await writer.append(row); // 4. Close and get file paths const files = await writer.close(); console.log(files); ``` ## Options - `schema` is required and defines the collection fields. - `format` accepts `'json'` (default) or `'parquet'`. - `localPath` selects the output directory and defaults to `process.cwd()`. - `chunkSize` controls the automatic flush threshold in bytes and defaults to 128 MB. - `storage` selects the storage backend and defaults to `LocalStorage`. ## JSON vs Parquet | | JSON | Parquet | | --- | --- | --- | | File size | Large | **~77% smaller** | | Write speed | Fast | Slower | | Upload speed | Slow | **~4x faster** | | Server import | Slow | **~2x faster** | | Dependencies | None | `@shanghaikid/parquetjs` | | Human readable | Yes | No | **Recommendation:** Use Parquet for production, JSON for debugging. ## Full Workflow: Write, Upload, Import Use the schema from Quick Start and an existing collection that matches it. Pass rows keyed by field name in `rows`. Install `minio` and ensure the Milvus server can read the bucket used for the upload. ```javascript import { relative, sep } from 'node:path'; import * as Minio from 'minio'; import { BulkWriter, MilvusClient } from '@zilliz/milvus2-sdk-node'; // Step 1: Write files const localPath = './bulk_data'; const writer = new BulkWriter({ schema, format: 'parquet', localPath, }); for (const row of rows) { await writer.append(row); } const batchFiles = await writer.close(); // Step 2: Upload to MinIO/S3 const minio = new Minio.Client({ endPoint: '127.0.0.1', port: 9000, useSSL: false, accessKey: 'minioadmin', secretKey: 'minioadmin', }); const remotePaths = []; for (const chunk of batchFiles) { for (const localFile of chunk) { const remote = `imports/${relative(localPath, localFile).split(sep).join('/')}`; await minio.fPutObject('a-bucket', remote, localFile); remotePaths.push(remote); } } // Step 3: Trigger bulk import const client = new MilvusClient({ address: 'localhost:19530' }); try { const importRes = await client.bulkInsert({ collection_name: 'my_collection', files: remotePaths, }); if (importRes.status.error_code !== 'Success') { throw new Error(importRes.status.reason); } // Step 4: Wait for completion const deadline = Date.now() + 5 * 60_000; while (true) { if (Date.now() >= deadline) throw new Error('Import timed out'); const state = await client.getImportState({ task: importRes.tasks[0] }); if (state.status.error_code !== 'Success') throw new Error(state.status.reason); if (state.state === 'ImportCompleted') { console.log('Imported rows:', state.row_count); break; } if ( state.state === 'ImportFailed' || state.state === 'ImportFailedAndCleaned' ) { throw new Error(JSON.stringify(state.infos)); } await new Promise((resolve) => setTimeout(resolve, 1000)); } } finally { await client.closeConnection(); } ``` ## Streaming from Any Data Source BulkWriter supports `AsyncIterable` input via `writeFrom()`, enabling streaming from any source with constant memory: Use the same schema and a CSV header of `embedding,content,source`. Store each vector as a quoted JSON array in the `embedding` column. ```javascript import { parse } from 'csv-parse'; import * as fs from 'fs'; import { BulkWriter } from '@zilliz/milvus2-sdk-node'; // Stream CSV → BulkWriter → Parquet files const csvStream = fs .createReadStream('data.csv') .pipe(parse({ columns: true })); async function* transform(source) { for await (const row of source) { yield { vector: JSON.parse(row.embedding), text: row.content, metadata: { source: row.source }, }; } } const writer = new BulkWriter({ schema, format: 'parquet', localPath: './output', }); const files = await writer.writeFrom(transform(csvStream)); ``` ## Collection Clone via Query Iterator Pull data from an existing collection and write to files for import into another: ```javascript // Source: query all data const iterator = await sourceClient.queryIterator({ collection_name: 'source_collection', batchSize: 1000, output_fields: ['vector', 'text', 'metadata'], expr: 'id > 0', }); // Write to BulkWriter const writer = new BulkWriter({ schema: { fields: targetFields }, format: 'parquet', localPath: './migration', }); for await (const batch of iterator) { for (const row of batch) { await writer.append(row); } } const files = await writer.close(); // Upload + bulkInsert into target collection... ``` **Note on Int64:** Query returns Int64 values as strings (gRPC limitation). BulkWriter handles this automatically — no precision loss even for values beyond `Number.MAX_SAFE_INTEGER` (2^53-1). ## Progress Events ```javascript writer.on('flush', (event) => { console.log( `Chunk ${event.chunkIndex}: ${event.rowCount} rows → ${event.files}` ); }); ``` ## Dynamic Fields When `enable_dynamic_field: true`, extra keys not in the schema are collected into `$meta`: ```javascript const writer = new BulkWriter({ schema: { fields: FIELDS, enable_dynamic_field: true }, format: 'json', localPath: './output', }); await writer.append({ vector: [0.1, 0.2, 0.3, 0.4], text: 'hello', color: 'red', // dynamic field → stored in $meta score: 42, // dynamic field → stored in $meta }); ``` You can also pass dynamic fields explicitly via `$meta`: ```javascript await writer.append({ vector: [0.1, 0.2, 0.3, 0.4], text: 'hello', $meta: { color: 'red', score: 42 }, }); ``` ## Supported Types | Category | Types | | --- | --- | | Scalar | Bool, Int8, Int16, Int32, Int64, Float, Double, VarChar, JSON, Geometry, Timestamptz | | Vector | FloatVector, BinaryVector, Float16Vector, BFloat16Vector, SparseFloatVector, Int8Vector | | Complex | Array, Array (with nested vector/Int64 sub-fields) | | Special | Dynamic fields ($meta), nullable fields, default values, autoID | ### Sparse Vector Formats BulkWriter accepts all SDK sparse formats and normalizes automatically: ```javascript // All of these work: await writer.append({ sparse: { 2: 0.5, 5: 0.3 } }); // dict await writer.append({ sparse: { indices: [2, 5], values: [0.5, 0.3] } }); // CSR await writer.append({ sparse: [{ index: 2, value: 0.5 }] }); // COO await writer.append({ sparse: [undefined, 0.5, undefined, 0.3] }); // array ``` ### Timestamptz Accepts both ISO strings and Date objects: ```javascript await writer.append({ ts: '2025-01-15T12:00:00+08:00' }); await writer.append({ ts: new Date() }); // auto-converted to ISO string ``` ## API Reference ### `BulkWriter` | Method | Description | | --- | --- | | `append(row)` | Append a single row. Auto-flushes when buffer exceeds `chunkSize`. | | `commit()` | Manually flush the current buffer to disk. | | `close()` | Flush remaining data and return all file paths (`string[][]`). | | `writeFrom(source)` | Write all rows from an `AsyncIterable`, then close. | | Property | Type | Description | | --- | --- | --- | | `totalRowCount` | `number` | Total rows appended so far. | | `bufferRowCount` | `number` | Rows in the current (unflushed) buffer. | | `batchFiles` | `string[][]` | File paths generated so far. | | Event | Payload | Description | | --- | --- | --- | | `flush` | `{ files, rowCount, chunkIndex }` | Emitted after each chunk is flushed. | ### `bulkInsert` / Import APIs ```javascript // Trigger import const res = await client.bulkInsert({ collection_name: 'my_collection', files: ['path/to/data.parquet'], }); // Check progress const state = await client.getImportState({ task: res.tasks[0] }); // List all import jobs const jobs = await client.listImportTasks({ collection_name: 'my_collection', }); ``` --- # Query Entities and Search Vectors Query by scalar filter or primary key and run vector similarity searches in Milvus using Node.js. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/ ## Section links - [Query Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#query-operations) - [Basic Query](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#basic-query) - [Query by IDs](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#query-by-ids) - [Query with Limit, Offset, and Ordering](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#query-with-limit-offset-and-ordering) - [Query Specific Partitions](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#query-specific-partitions) - [Query Iterator](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#query-iterator) - [Get Operation](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#get-operation) - [Count Operation](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#count-operation) - [Query Aggregation](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#query-aggregation) - [Search Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-operations) - [Basic Search](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#basic-search) - [Search Aggregation](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-aggregation) - [Search by ID](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-by-id) - [Search Multiple Vectors](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-multiple-vectors) - [Search with Filter](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-with-filter) - [Search with Ordering](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-with-ordering) - [Search Parameters](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-parameters) - [Search Specific Partitions](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-specific-partitions) - [Search Iterator](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-iterator) - [Hybrid Search](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#hybrid-search) - [Filter Expressions](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#filter-expressions) - [Comparison Operators](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#comparison-operators) - [Logical Operators](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#logical-operators) - [In Operator](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#in-operator) - [String Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#string-operations) - [JSON Field Access](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#json-field-access) - [StructArray Element Filters](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#structarray-element-filters) - [Regex, Raw Strings, and Bitwise Operators Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#regex-raw-strings-and-bitwise-operators-milvus-30) - [Search Results](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-results) - [Element-Level Offsets Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#element-level-offsets-milvus-30) - [Output Fields](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#output-fields) - [Performance Optimization](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#performance-optimization) - [Search Parameters Tuning](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-parameters-tuning) - [Batch Search](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#batch-search) - [Pre-load Collections](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#pre-load-collections) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#best-practices) - [Complete Example](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#complete-example) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#next-steps) Use `get` to fetch known primary keys, `query` to match scalar filters, `search` to rank by vector similarity, and `hybridSearch` to combine similarity searches. Use an iterator when you need results in batches. Load the collection before reading it. | Method | Use it to | Main input | | --- | --- | --- | | `get` | Fetch entities by primary key | `ids` | | `query` | Read rows matching a scalar expression | `filter`, or `limit` for an unfiltered read | | `search` | Return the nearest vector matches | Query vectors in `data`, optional scalar `filter` | | `hybridSearch` | Fuse multiple ANN searches and rerank the candidates | Sub-searches in `data` and a `rerank` strategy | | `queryIterator` / `searchIterator` | Read a large scalar query or vector search in batches | The query or search inputs and `batchSize` | Use `filter` for scalar expressions in `query`, `search`, and iterators. Those APIs also accept `expr` as an alias. ## Query Operations Query retrieves entities based on filter expressions. ### Basic Query Query entities with a filter expression: ```javascript const results = await client.query({ collection_name: 'my_collection', filter: 'age > 25', output_fields: ['id', 'vector', 'text'], }); ``` ### Query by IDs Query specific entities by their IDs: ```javascript const results = await client.query({ collection_name: 'my_collection', ids: [1, 2, 3, 4, 5], output_fields: ['id', 'vector', 'text'], }); ``` ### Query with Limit, Offset, and Ordering ```javascript const results = await client.query({ collection_name: 'my_collection', filter: 'age > 25', output_fields: ['id', 'text', 'price'], limit: 10, offset: 0, order_by_fields: [{ field: 'price', order: 'desc' }], }); ``` `order_by_fields` can be a string, an array of strings, or an array of `{ field, order }` objects. Milvus requires an explicit `limit` for ordered queries: ```javascript await client.query({ collection_name: 'my_collection', filter: 'age > 25', output_fields: ['id', 'price', 'rating'], limit: 10, order_by_fields: 'price:asc,rating:desc', }); await client.query({ collection_name: 'my_collection', filter: 'age > 25', output_fields: ['id', 'price', 'rating'], limit: 10, order_by: ['price:asc', { field: 'rating', order: 'desc' }], // alias }); ``` ### Query Specific Partitions ```javascript const results = await client.query({ collection_name: 'my_collection', filter: 'age > 25', partition_names: ['partition_1', 'partition_2'], output_fields: ['id', 'text'], }); ``` ### Query Iterator Iterate through large result sets: ```javascript const iterator = await client.queryIterator({ collection_name: 'my_collection', filter: 'age > 25', output_fields: ['id', 'text'], batchSize: 100, }); for await (const batch of iterator) { console.log('Batch:', batch); } ``` ## Get Operation Get entities by IDs (simpler than query): ```javascript const results = await client.get({ collection_name: 'my_collection', ids: [1, 2, 3], output_fields: ['id', 'vector', 'text'], }); ``` ## Count Operation Count entities matching a filter: ```javascript const result = await client.count({ collection_name: 'my_collection', filter: 'age > 25', }); if (result.status.error_code !== 'Success') { throw new Error(result.status.reason); } console.log('Count:', result.data); ``` ### Query Aggregation Milvus 3.0 Put aggregation expressions in `output_fields`. Add `group_by_fields` when you want one result row per scalar group. ```javascript const result = await client.query({ collection_name: 'sales', filter: 'price > 0', group_by_fields: ['category'], output_fields: [ 'category', 'count(price)', 'min(price)', 'max(price)', 'sum(price)', 'avg(price)', ], limit: 20, }); result.data.forEach((row) => { console.log(row.category, row['count(price)'], row['avg(price)']); }); ``` The supported functions are `count`, `min`, `max`, `sum`, and `avg`. Without `group_by_fields`, Milvus returns collection-level aggregation values. ## Search Operations Search finds similar vectors using distance metrics. ### Basic Search ```javascript const results = await client.search({ collection_name: 'my_collection', data: [[0.1, 0.2, 0.3, 0.4]], // Search vector limit: 10, output_fields: ['id', 'text'], }); ``` ### Search Aggregation Milvus 3.0 Search aggregation groups the candidate set into buckets. Each bucket can include metrics, sorted top hits, and nested sub-aggregations. ```javascript const results = await client.search({ collection_name: 'products', anns_field: 'embedding', data: [0.1, 0.2, 0.3, 0.4], limit: 100, filter: 'in_stock == true', output_fields: ['category', 'brand', 'price'], search_aggregation: { fields: ['category'], size: 5, metrics: { item_count: { op: 'count', field_name: '*' }, average_price: { op: 'avg', field_name: 'price' }, }, order: [{ key: 'average_price', direction: 'desc' }], top_hits: { size: 2, sort: [{ field_name: 'price', direction: 'asc' }], }, sub_aggregation: { fields: ['brand'], size: 3, }, }, }); console.log(results.agg_buckets); ``` For one query vector, `agg_buckets` is an `AggregationBucket[]`. For multiple query vectors, it is an `AggregationBucket[][]`. Aggregation searches return their grouped data through `agg_buckets` instead of regular hit rows. Search aggregation is not available for hybrid search and cannot be combined with highlighters, grouping, or a positive offset. ### Search by ID perform a vector similarity search using the vectors associated with exact entity IDs: ```javascript const results = await client.search({ collection_name: 'my_collection', ids: [1, 2, 3], // primary keys limit: 10, output_fields: ['id', 'text'], }); ``` > [!NOTE] > > - When `ids` are provided, the `data` parameter (dummy vectors) is not required. > - The provided `ids` must match the collection’s Primary Key type (`Int64` or `VarChar`). > - For collections with multiple vector fields, explicitly specifying `anns_field` is recommended (and required to disambiguate). ### Search Multiple Vectors ```javascript const results = await client.search({ collection_name: 'my_collection', data: [ [0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], ], limit: 10, output_fields: ['id', 'text'], }); ``` ### Search with Filter Combine vector search with scalar filters: ```javascript const results = await client.search({ collection_name: 'my_collection', data: [[0.1, 0.2, 0.3, 0.4]], filter: 'age > 25 AND category == "tech"', limit: 10, output_fields: ['id', 'text', 'age'], }); ``` ### Search with Ordering Sort search results by scalar fields after vector retrieval: ```javascript const results = await client.search({ collection_name: 'my_collection', data: [[0.1, 0.2, 0.3, 0.4]], limit: 10, output_fields: ['id', 'price', 'rating'], order_by_fields: [ { field: 'price', order: 'asc' }, { field: 'rating', order: 'desc' }, ], }); ``` You can also pass `order_by_fields` as a string, for example `'price:asc,rating:desc'`. If you also pass `params.order_by_fields`, the top-level `order_by_fields` value takes precedence. ### Search Parameters Configure search parameters for different index types: ```javascript // For IVF indexes const ivfResults = await client.search({ collection_name: 'my_collection', data: [[0.1, 0.2, 0.3, 0.4]], params: { nprobe: 64, // Number of clusters to search }, limit: 10, }); // For HNSW indexes const hnswResults = await client.search({ collection_name: 'my_collection', data: [[0.1, 0.2, 0.3, 0.4]], params: { ef: 100, // Search width }, limit: 10, }); ``` ### Search Specific Partitions ```javascript const results = await client.search({ collection_name: 'my_collection', data: [[0.1, 0.2, 0.3, 0.4]], partition_names: ['partition_1'], limit: 10, }); ``` ### Search Iterator Iterate through large search results: ```javascript const iterator = await client.searchIterator({ collection_name: 'my_collection', data: [[0.1, 0.2, 0.3, 0.4]], filter: 'age > 25', limit: 1000, batchSize: 100, }); for await (const batch of iterator) { console.log('Batch:', batch); } ``` ### Hybrid Search Search with multiple vector fields: ```javascript const results = await client.hybridSearch({ collection_name: 'my_collection', data: [ { data: [0.1, 0.2, 0.3, 0.4], anns_field: 'text_vector', }, { data: [0.5, 0.6, 0.7, 0.8], anns_field: 'image_vector', }, ], rerank: { strategy: 'rrf', params: { k: 60 } }, limit: 10, output_fields: ['id', 'text'], }); ``` ## Filter Expressions Filter expressions use Milvus expression syntax: ### Comparison Operators ```javascript 'age > 25'; 'age >= 25'; 'age < 25'; 'age <= 25'; 'age == 25'; 'age != 25'; ``` ### Logical Operators ```javascript 'age > 25 AND category == "tech"'; 'age > 25 OR age < 18'; 'NOT (age > 25)'; ``` ### In Operator ```javascript 'id in [1, 2, 3, 4, 5]'; 'category in ["tech", "science"]'; ``` ### String Operations ```javascript 'text like "milvus%"'; 'text like "%database%"'; ``` ### JSON Field Access ```javascript 'metadata.category == "tech"'; 'metadata.tags[0] == "ai"'; ``` ### StructArray Element Filters Milvus 3.0 Use `element_filter` and `$[...]` to apply predicates to fields in the same StructArray element: ```javascript 'element_filter(profile, $[score] >= 90 AND $[active] == true)'; ``` Select child fields with bracketed paths such as `profile[score]` and `profile[tag]`. Element-level query and search results include an `offset` identifying the matching array element. ### Regex, Raw Strings, and Bitwise Operators Milvus 3.0 These expressions are passed through to the Milvus expression parser: ```javascript // Regular expression match and negative match 'name =~ "^milvus-[0-9]+$"'; 'name !~ "-archived$"'; // Raw string literal for patterns with backslashes 'path == r"C:\\data\\vectors"'; // Bitwise AND, OR, and XOR '(permissions & 4) != 0'; '(flags | 2) == 3'; '(mask ^ 1) == 0'; ``` ## Search Results Search results include: ```javascript const results = await client.search({ collection_name: 'my_collection', data: [[0.1, 0.2, 0.3, 0.4]], limit: 10, }); results.results.forEach((result) => { console.log('ID:', result.id); console.log('Distance:', result.distance); console.log('Score:', result.score); console.log('Entity:', result.entity); }); ``` ### Element-Level Offsets Milvus 3.0 For element-level retrieval, Milvus can return the matching element offsets for array or multi-vector fields. The SDK flattens `element_indices` into result rows and adds an `offset` property that identifies the matched element within the source field. ```javascript const results = await client.search({ collection_name: 'chunked_docs', data: [ [ /* query vector */ ], ], anns_field: 'chunk_embeddings', limit: 10, output_fields: ['doc_id', 'title'], }); results.results.forEach((row) => { console.log('Document:', row.doc_id); console.log('Matched element offset:', row.offset); }); ``` Grouped search responses can also include `group_by_field_values`, which the SDK exposes on each result row: ```javascript results.results.forEach((row) => { console.log('Score:', row.score); console.log('Group by values:', row.group_by_field_values); }); ``` ## Output Fields Specify which fields to return: ```javascript // Return specific fields output_fields: ['id', 'text', 'age']; // Return all fields output_fields: ['*']; // Return vector fields output_fields: ['id', 'vector']; ``` ## Performance Optimization ### Search Parameters Tuning **IVF indexes:** - `nprobe`: Higher values improve recall but slower (typical: 16-256) **HNSW indexes:** - `ef`: Higher values improve recall but slower (typical: 50-200) ### Batch Search Search multiple vectors efficiently: ```javascript const results = await client.search({ collection_name: 'my_collection', data: [ [ /* vector 1 */ ], [ /* vector 2 */ ], [ /* vector 3 */ ], ], limit: 10, }); ``` ### Pre-load Collections Load collections before searching: ```javascript await client.loadCollectionSync({ collection_name: 'my_collection', }); // Now search const results = await client.search({ collection_name: 'my_collection', data: [queryVector], limit: 10, }); ``` ## Best Practices 1. **Use appropriate limits**: Set reasonable limits to avoid large result sets 2. **Filter before search**: Use filter expressions to narrow down results 3. **Tune search parameters**: Adjust nprobe/ef based on your recall/performance needs 4. **Use iterators**: For large result sets, use query/search iterators 5. **Load collections**: Always load collections before searching 6. **Batch operations**: Search multiple vectors in one call when possible ## Complete Example Use a collection named `my_collection` with an indexed 128-dimensional vector field and scalar fields named `id`, `text`, and `age`. Insert rows with ages above and below 25 to see how the filter changes the results. ```javascript import { MilvusClient } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530', }); await client.connectPromise; // Load collection await client.loadCollectionSync({ collection_name: 'my_collection', }); // Query const queryResults = await client.query({ collection_name: 'my_collection', filter: 'age > 25', output_fields: ['id', 'text', 'age'], limit: 10, }); console.log('Query results:', queryResults.data); // Search const searchResults = await client.search({ collection_name: 'my_collection', data: [Array.from({ length: 128 }, () => Math.random())], filter: 'age > 25', limit: 10, output_fields: ['id', 'text'], }); console.log('Search results:', searchResults.results); await client.closeConnection(); ``` ## Next Steps - Learn about [Delete Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/) - Explore [Data Management](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/) - Check out [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) --- # Delete Entities Delete Milvus entities by primary key or filter expression with the Node.js SDK and check the deletion response. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/ ## Section links - [Delete by IDs](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#delete-by-ids) - [Delete with String IDs](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#delete-with-string-ids) - [Delete by Filter Expression](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#delete-by-filter-expression) - [Delete Entities (Advanced)](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#delete-entities-advanced) - [Delete Response](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#delete-response) - [Delete from Specific Partition](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#delete-from-specific-partition) - [Filter Expressions for Delete](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#filter-expressions-for-delete) - [Comparison Operators](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#comparison-operators) - [Logical Operators](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#logical-operators) - [In Operator](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#in-operator) - [String Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#string-operations) - [Batch Deletion](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#batch-deletion) - [Flush After Delete](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#flush-after-delete) - [Error Handling](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#error-handling) - [Delete Best Practices](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#delete-best-practices) - [Complete Example](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#complete-example) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-delete/#next-steps) This guide covers deleting data from Milvus collections. ## Delete by IDs Delete entities by their primary key IDs: ```javascript await client.delete({ collection_name: 'my_collection', ids: [1, 2, 3, 4, 5], }); ``` ### Delete with String IDs For VarChar primary keys: ```javascript await client.delete({ collection_name: 'my_collection', ids: ['id1', 'id2', 'id3'], }); ``` ## Delete by Filter Expression Delete entities matching a filter expression: ```javascript await client.delete({ collection_name: 'my_collection', filter: 'age < 18', }); ``` Combine conditions with `AND`: ```javascript await client.delete({ collection_name: 'my_collection', filter: 'age < 18 AND category == "old"', }); ``` ## Delete Entities (Advanced) Use `deleteEntities` for more control: ```javascript await client.deleteEntities({ collection_name: 'my_collection', expr: 'age < 18', }); ``` ## Delete Response Delete operations return mutation results: ```javascript const result = await client.delete({ collection_name: 'my_collection', ids: [1, 2, 3], }); console.log('Delete count:', result.delete_cnt); console.log('IDs:', result.IDs); console.log('Timestamp:', result.timestamp); ``` ## Delete from Specific Partition Delete entities from a specific partition: ```javascript await client.delete({ collection_name: 'my_collection', partition_name: 'partition_1', ids: [1, 2, 3], }); ``` ## Filter Expressions for Delete Use the same filter expression syntax as queries: ### Comparison Operators ```javascript 'age > 25'; 'age >= 25'; 'age < 25'; 'age <= 25'; 'age == 25'; 'age != 25'; ``` ### Logical Operators ```javascript 'age > 25 AND category == "tech"'; 'age > 25 OR age < 18'; 'NOT (age > 25)'; ``` ### In Operator ```javascript 'id in [1, 2, 3, 4, 5]'; 'category in ["old", "deprecated"]'; ``` ### String Operations ```javascript 'text like "%deprecated%"'; ``` ## Batch Deletion Delete large numbers of entities efficiently: ```javascript // Delete by IDs in batches const idsToDelete = [ /* large array of IDs */ ]; const batchSize = 1000; for (let i = 0; i < idsToDelete.length; i += batchSize) { const batch = idsToDelete.slice(i, i + batchSize); await client.delete({ collection_name: 'my_collection', ids: batch, }); } ``` ## Flush After Delete Flush to ensure deletions are persisted: ```javascript await client.delete({ collection_name: 'my_collection', ids: [1, 2, 3], }); // Flush to persist deletions await client.flush({ collection_names: ['my_collection'], }); ``` ## Error Handling Handle deletion errors: ```javascript try { await client.delete({ collection_name: 'my_collection', ids: [1, 2, 3], }); } catch (error) { if (error.message.includes('CollectionNotExists')) { console.error('Collection does not exist'); } else if (error.message.includes('IllegalArgument')) { console.error('Invalid delete parameters'); } else { console.error('Delete failed:', error); } } ``` ## Delete Best Practices 1. **Use filters for bulk deletion**: Use filter expressions for deleting many entities 2. **Use IDs for specific deletion**: Use IDs when deleting specific entities 3. **Flush after deletion**: Always flush after deletions to ensure persistence 4. **Batch operations**: Delete in batches for large deletions 5. **Verify before delete**: Query first to verify what will be deleted 6. **Use transactions**: Consider using transactions for related deletions ## Complete Example Use a collection named `my_collection` with an Int64 primary key and an integer `age` field. Load it before using `count()` to verify the deletion. ```javascript import { ConsistencyLevelEnum, MilvusClient } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530', }); await client.connectPromise; // Delete by IDs const deleteResult = await client.delete({ collection_name: 'my_collection', ids: [1, 2, 3], }); console.log('Deleted:', deleteResult.delete_cnt); // Delete by filter await client.delete({ collection_name: 'my_collection', filter: 'age < 18', }); // Flush to persist await client.flush({ collection_names: ['my_collection'], }); // Verify deletion const count = await client.count({ collection_name: 'my_collection', filter: 'age < 18', consistency_level: ConsistencyLevelEnum.Strong, }); console.log('Remaining entities:', count.data); await client.closeConnection(); ``` ## Next Steps - Learn about [Data Management](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/) - Explore [Query Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/) - Check out [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) --- # Flush, Compact, and Import Data Flush and compact Milvus collections, inspect their segments, and track bulk import jobs with the Node.js SDK. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/operations/data-management/ ## Section links - [Flush Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#flush-operations) - [Flush Collection](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#flush-collection) - [Flush Synchronously](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#flush-synchronously) - [Get Flush State](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#get-flush-state) - [Flush All Collections](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#flush-all-collections) - [Compaction](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#compaction) - [Trigger Compaction](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#trigger-compaction) - [Get Compaction State](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#get-compaction-state) - [Get Compaction Plans](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#get-compaction-plans) - [Bulk Import](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#bulk-import) - [Import Data](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#import-data) - [List Import Tasks](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#list-import-tasks) - [Load Balancing](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#load-balancing) - [Segment Information](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#segment-information) - [Get Query Segment Info](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#get-query-segment-info) - [Get Persistent Segment Info](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#get-persistent-segment-info) - [Publish Segment Manifest Updates](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#publish-segment-manifest-updates) - [Metrics](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#metrics) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#best-practices) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/operations/data-management/#next-steps) This guide covers data management operations including flushing, compaction, bulk import, and segment management. ## Flush Operations Flush ensures data is persisted to disk. ### Flush Collection Flush a collection asynchronously: ```javascript const result = await client.flush({ collection_names: ['my_collection'], }); console.log('Flush segment IDs:', result.coll_segIDs); ``` ### Flush Synchronously Wait until flush completes: ```javascript const result = await client.flushSync({ collection_names: ['my_collection'], }); console.log('Flush completed:', result.flushed); ``` ### Get Flush State Check if segments are flushed: ```javascript const state = await client.getFlushState({ segmentIDs: [12345, 12346], }); console.log('Flushed:', state.flushed); ``` ### Flush All Collections Flush all collections in the cluster, or wait until the flush-all operation completes: ```javascript const flushAll = await client.flushAll(); const state = await client.getFlushAllState({ flush_all_tss: flushAll.flush_all_tss, }); console.log('Flush-all completed:', state.flushed); ``` Use `flushAllSync()` to trigger flush-all and poll until completion: ```javascript const result = await client.flushAllSync(); console.log('Flush-all completed:', result.flushed); ``` `flushAll()` and `getFlushAllState()` also accept the common request options such as `timeout`. The legacy `db_name` and `flush_all_ts` fields are still accepted for compatibility, but `flush_all_tss` is preferred. ## Compaction Compaction merges small segments to improve query performance. ### Trigger Compaction ```javascript const result = await client.compact({ collection_name: 'my_collection', }); console.log('Compaction ID:', result.compactionID); ``` Pass advanced compaction options when you need to target specific partitions, channels, or segments: ```javascript const result = await client.compact({ collection_name: 'my_collection', timetravel: 0, majorCompaction: true, partition_id: '12345', channel: 'by-dev-rootcoord-dml_0', segment_ids: [111, 222], l0Compaction: false, target_size: '536870912', // bytes }); ``` Common advanced fields: | Field | Description | | --- | --- | | `timetravel` | Timestamp boundary for compaction | | `majorCompaction` | Request major compaction | | `partition_id` | Target a specific partition | | `channel` | Target a specific DML channel | | `segment_ids` | Compact specific segments | | `l0Compaction` | Request L0 compaction | | `target_size` | Target segment size in bytes | ### Get Compaction State Check compaction status: ```javascript const state = await client.getCompactionState({ compactionID: 12345, }); console.log('State:', state.state); ``` ### Get Compaction Plans Get detailed compaction information: ```javascript const plans = await client.getCompactionStateWithPlans({ compactionID: 12345, }); console.log('Plans:', plans.mergeInfos); ``` ## Bulk Import Import data from files. ### Import Data ```javascript const result = await client.bulkInsert({ collection_name: 'my_collection', files: ['/path/to/data.json', '/path/to/data2.json'], }); console.log('Task ID:', result.tasks[0]); ``` ### List Import Tasks Check import task status: ```javascript const tasks = await client.listImportTasks({ collection_name: 'my_collection', }); tasks.tasks.forEach((task) => { console.log('Task ID:', task.id); console.log('State:', task.state); console.log('Imported rows:', task.row_count); }); ``` ## Load Balancing Balance data across nodes: ```javascript await client.loadBalance({ src_nodeID: 1, dst_nodeIDs: [2, 3], sealed_segmentIDs: [12345, 12346], }); ``` ## Segment Information ### Get Query Segment Info Get information about query segments: ```javascript const info = await client.getQuerySegmentInfo({ collectionName: 'my_collection', dbName: 'default', }); info.infos.forEach((segment) => { console.log('Segment ID:', segment.segmentID); console.log('State:', segment.state); console.log('Level:', segment.level); }); ``` > The segment info APIs use proto field names: `collectionName` and `dbName`. ### Get Persistent Segment Info Get information about persistent segments: ```javascript const info = await client.getPersistentSegmentInfo({ collectionName: 'my_collection', dbName: 'default', }); info.infos.forEach((segment) => { console.log('Segment ID:', segment.segmentID); console.log('State:', segment.state); console.log('Level:', segment.level); }); ``` ### Publish Segment Manifest Updates `batchUpdateManifest()` publishes already-written Storage V3 manifest versions to Milvus metadata. Pass the segment ID and manifest version as decimal strings to preserve their full int64 precision. This API was verified with Milvus 3.0.6. ```typescript await client.batchUpdateManifest({ collection_name: 'my_collection', items: [ { segment_id: segmentId, manifest_version: publishedManifestVersion }, ], }); ``` ## Metrics Get collection metrics: ```javascript const metrics = await client.getMetric({ request: { metric_type: 'system_info', }, }); console.log('Metrics:', metrics); ``` ## Best Practices 1. **Flush regularly**: Flush after bulk insertions 2. **Monitor compaction**: Check compaction state for large collections 3. **Use bulk import**: Use bulk import for large datasets 4. **Balance load**: Use load balancing for distributed deployments 5. **Monitor segments**: Check segment information for optimization ## Next Steps - Learn about [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/) - Explore [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) --- # Hybrid Search Combine multiple vector searches across different fields in Milvus and rerank the results with weighted or reciprocal rank fusion. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/ ## Section links - [Overview](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/#overview) - [Basic Usage](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/#basic-usage) - [Search Request Parameters](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/#search-request-parameters) - [Reranking Strategies](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/#reranking-strategies) - [RRF (Reciprocal Rank Fusion)](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/#rrf-reciprocal-rank-fusion) - [Weighted Ranker](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/#weighted-ranker) - [FunctionScore](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/#functionscore) - [Top-Level Parameters](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/#top-level-parameters) - [End-to-End Example](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/#end-to-end-example) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/#next-steps) Hybrid search combines multiple vector similarity searches across different vector fields and merges the results using a reranking strategy. This is useful when your data has multiple vector representations (e.g., dense + sparse vectors, or text + image embeddings). ## Overview In the Milvus Node.js SDK, `hybridSearch()` is an alias for `search()`. When you pass a `HybridSearchReq` (with `data` as an array of individual search requests), the SDK automatically performs a hybrid search. You can also call `search()` directly with the same parameter shape. ## Basic Usage ```javascript const results = await client.hybridSearch({ collection_name: 'my_collection', data: [ { data: [0.1, 0.2, 0.3, 0.4], // dense vector anns_field: 'dense_vector', params: { nprobe: 10 }, }, { data: { 1: 0.5, 100: 0.3, 500: 0.8 }, // sparse vector anns_field: 'sparse_vector', }, ], rerank: { strategy: 'rrf', params: { k: 60 }, }, limit: 10, output_fields: ['id', 'text'], }); ``` ## Search Request Parameters Each item in the `data` array is a `HybridSearchSingleReq`: | Parameter | Type | Description | | --- | --- | --- | | `data` | `number[]` or `object` | The search vector (dense array or sparse dict) | | `anns_field` | `string` | The vector field to search | | `expr` | `string` | Optional filter expression | | `exprValues` | `object` | Optional template values for filter expression | | `params` | `object` | Optional search parameters (e.g., `{ nprobe: 10 }`) | | `group_by_field` | `string` | Optional field to group results by | ## Reranking Strategies The `rerank` parameter controls how results from multiple searches are merged. ### RRF (Reciprocal Rank Fusion) Combines results based on their rank positions. Higher-ranked results from any search get more weight. ```javascript const rerank = { strategy: 'rrf', params: { k: 60 }, // k controls rank smoothing (default: 60) }; ``` ### Weighted Ranker Assigns explicit weights to each search request’s results. ```javascript const rerank = { strategy: 'weighted', params: { weights: [0.7, 0.3] }, // weights correspond to each search in data[] }; ``` ### FunctionScore Advanced reranking using custom scoring functions. A `FunctionScore` contains one or more function definitions plus optional top-level parameters for the reranker. ```javascript import { FunctionType } from '@zilliz/milvus2-sdk-node'; const results = await client.hybridSearch({ collection_name: 'my_collection', data: [ { data: [0.1, 0.2, 0.3, 0.4], anns_field: 'dense_vector', params: { nprobe: 10 }, }, { data: { 1: 0.5, 100: 0.3 }, anns_field: 'sparse_vector', }, ], rerank: { functions: [ { name: 'freshness_boost', type: FunctionType.RERANK, input_field_names: ['publish_time'], params: { reranker: 'decay', function: 'exp', origin: Math.floor(Date.now() / 1000), scale: 86400, offset: 0, decay: 0.5, }, }, ], params: {}, }, limit: 10, output_fields: ['id', 'text', 'publish_time'], }); ``` Use FunctionScore when you need to blend vector similarity with business signals such as recency, popularity, quality scores, or custom server-side rerank functions. ## Top-Level Parameters | Parameter | Type | Description | | --- | --- | --- | | `collection_name` | `string` | The collection to search | | `data` | `HybridSearchSingleReq[]` | Array of individual search requests | | `rerank` | `RerankerObj \| FunctionScore` | Reranking strategy | | `limit` | `number` | Maximum number of results to return | | `output_fields` | `string[]` | Fields to include in results | | `consistency_level` | `string` | Optional consistency level | | `partition_names` | `string[]` | Optional partitions to search | ## End-to-End Example ```javascript import { ConsistencyLevelEnum, MilvusClient, DataType, } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530' }); // 1. Create a collection with two vector fields await client.createCollection({ collection_name: 'hybrid_demo', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'text', data_type: DataType.VarChar, max_length: 512 }, { name: 'dense_vector', data_type: DataType.FloatVector, dim: 4 }, { name: 'sparse_vector', data_type: DataType.SparseFloatVector }, ], }); // 2. Insert data await client.insert({ collection_name: 'hybrid_demo', data: [ { text: 'machine learning fundamentals', dense_vector: [0.1, 0.2, 0.3, 0.4], sparse_vector: { 10: 0.5, 20: 0.3 }, }, { text: 'deep learning neural networks', dense_vector: [0.5, 0.6, 0.7, 0.8], sparse_vector: { 15: 0.8, 25: 0.2 }, }, ], }); await client.flushSync({ collection_names: ['hybrid_demo'] }); // 3. Create indexes for both vector fields await client.createIndex([ { collection_name: 'hybrid_demo', field_name: 'dense_vector', index_type: 'AUTOINDEX', metric_type: 'COSINE', }, { collection_name: 'hybrid_demo', field_name: 'sparse_vector', index_type: 'SPARSE_INVERTED_INDEX', metric_type: 'IP', }, ]); // 4. Load collection await client.loadCollectionSync({ collection_name: 'hybrid_demo' }); // 5. Hybrid search const results = await client.hybridSearch({ collection_name: 'hybrid_demo', data: [ { data: [0.1, 0.2, 0.3, 0.4], anns_field: 'dense_vector', }, { data: { 10: 0.5, 20: 0.3 }, anns_field: 'sparse_vector', }, ], rerank: { strategy: 'rrf', params: { k: 60 }, }, limit: 10, output_fields: ['text'], consistency_level: ConsistencyLevelEnum.Strong, }); console.log('Results:', results.results); // 6. Cleanup await client.dropCollection({ collection_name: 'hybrid_demo' }); await client.closeConnection(); ``` ## Next Steps - Learn about [Full-Text Search](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/) for text-based hybrid search - Explore [Iterators](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/) for paginating large result sets - Check [Query & Search](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/) for standard search operations --- # Iterators Read large Milvus result sets in batches with the Node.js query and search iterators, and close iterators when finished. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/operations/iterators/ ## Section links - [Search Iterator](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/#search-iterator) - [Basic Usage](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/#basic-usage) - [Parameters](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/#parameters) - [Client-Side Filtering](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/#client-side-filtering) - [Query Iterator](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/#query-iterator) - [Basic Usage](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/#basic-usage-1) - [Parameters](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/#parameters-1) - [End-to-End Example: Full Collection Scan](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/#end-to-end-example-full-collection-scan) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/#best-practices) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/operations/iterators/#next-steps) Iterators allow you to paginate through large result sets that exceed the `topk` limit (16,384). Instead of retrieving all results at once, iterators fetch data in configurable batches. ## Search Iterator `searchIterator()` performs vector similarity search and returns results in batches. ### Basic Usage ```javascript const iterator = await client.searchIterator({ collection_name: 'my_collection', data: [0.1, 0.2, 0.3, 0.4], batchSize: 100, limit: 1000, // total results to return (-1 or omit for no limit) output_fields: ['id', 'text'], expr: 'age > 25', }); for await (const batch of iterator) { console.log('Batch size:', batch.length); // Process each batch } ``` ### Parameters | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `collection_name` | `string` | Yes | Collection to search | | `data` | `number[]` or `number[][]` | Yes | Search vector(s) | | `batchSize` | `number` | Yes | Items per batch (max 16384) | | `limit` | `number` | No | Total results limit (-1 for unlimited) | | `expr` | `string` | No | Filter expression | | `output_fields` | `string[]` | No | Fields to return | | `anns_field` | `string` | No | Vector field name (auto-detected if only one) | | `params` | `object` | No | Search parameters (e.g., `{ nprobe: 10 }`) | | `external_filter_fn` | `function` | No | Client-side filter function (see below) | ### Client-Side Filtering Use `external_filter_fn` to apply additional filtering on the client side after results are returned from the server: ```javascript const iterator = await client.searchIterator({ collection_name: 'my_collection', data: [0.1, 0.2, 0.3, 0.4], batchSize: 100, output_fields: ['text'], external_filter_fn: (row) => { // Only keep results where the text length > 50 return row.text && row.text.length > 50; }, }); for await (const batch of iterator) { // All items in batch satisfy the external filter console.log(batch); } ``` ## Query Iterator `queryIterator()` retrieves entities matching a filter expression in batches. ### Basic Usage ```javascript const iterator = await client.queryIterator({ collection_name: 'my_collection', expr: 'age > 30', output_fields: ['id', 'text', 'age'], batchSize: 100, limit: 5000, }); for await (const batch of iterator) { console.log('Batch:', batch.length); // Process each batch of query results } ``` ### Parameters | Parameter | Type | Required | Description | | --- | --- | --- | --- | | `collection_name` | `string` | Yes | Collection to query | | `expr` | `string` | Yes | Filter expression | | `batchSize` | `number` | Yes | Items per batch | | `limit` | `number` | No | Total results limit | | `output_fields` | `string[]` | No | Fields to return | | `partition_names` | `string[]` | No | Partitions to query | ## End-to-End Example: Full Collection Scan ```javascript import { MilvusClient, DataType } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530' }); // Create and populate a collection await client.createCollection({ collection_name: 'iterator_demo', consistency_level: 'Strong', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'category', data_type: DataType.VarChar, max_length: 64 }, { name: 'vector', data_type: DataType.FloatVector, dim: 4 }, ], }); await client.createIndex({ collection_name: 'iterator_demo', field_name: 'vector', index_type: 'AUTOINDEX', metric_type: 'COSINE', }); await client.loadCollectionSync({ collection_name: 'iterator_demo' }); // Insert sample data const data = Array.from({ length: 1000 }, (_, i) => ({ category: `cat_${i % 10}`, vector: Array.from({ length: 4 }, () => Math.random()), })); await client.insert({ collection_name: 'iterator_demo', data }); // Scan all entities in category 'cat_5' let totalCount = 0; const iterator = await client.queryIterator({ collection_name: 'iterator_demo', expr: 'category == "cat_5"', output_fields: ['id', 'category'], batchSize: 50, }); for await (const batch of iterator) { totalCount += batch.length; console.log(`Fetched ${batch.length} items, total: ${totalCount}`); } console.log(`Total matching entities: ${totalCount}`); // Cleanup await client.dropCollection({ collection_name: 'iterator_demo' }); await client.closeConnection(); ``` ## Best Practices 1. **Batch size tuning** — Start with 100-500. Larger batches reduce round trips but increase memory usage per batch. Maximum is 16,384. 2. **Use filters** — Apply server-side filters (`expr`) to reduce data transfer. Use `external_filter_fn` only for logic that can’t be expressed as a Milvus filter. 3. **Output fields** — Only request fields you need to minimize data transfer. 4. **Memory** — For very large scans, process and discard each batch promptly rather than accumulating all results in memory. ## Next Steps - Learn about [Hybrid Search](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/) for multi-vector search - Explore [Query & Search](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/) for standard operations --- # Collection Management Create Milvus collections in Node.js, define and evolve their schemas, and manage loading, aliases, and collection functions. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/management/collection-management/ ## Section links - [Creating Collections](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#creating-collections) - [Basic Collection Creation](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#basic-collection-creation) - [Collection with Consistency Level](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#collection-with-consistency-level) - [Collection with Properties](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#collection-with-properties) - [Entity-Level TTL](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#entity-level-ttl) - [Collection with Partition Configuration](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#collection-with-partition-configuration) - [Allow Insert with AutoID](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#allow-insert-with-autoid) - [Checking Collection Existence](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#checking-collection-existence) - [Listing Collections](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#listing-collections) - [Describing Collections](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#describing-collections) - [Modifying Collections](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#modifying-collections) - [Alter Collection Properties](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#alter-collection-properties) - [Rename Collection](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#rename-collection) - [Drop Collection Properties](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#drop-collection-properties) - [Dynamic Schema](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#dynamic-schema) - [Adding Fields to Existing Collection](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#adding-fields-to-existing-collection) - [Dropping Fields](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#dropping-fields) - [Alter Field Properties](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#alter-field-properties) - [Collection Statistics](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#collection-statistics) - [Collection Loading](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#collection-loading) - [Load Collection](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#load-collection) - [Check Loading Progress](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#check-loading-progress) - [Check Load State](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#check-load-state) - [Refresh Load](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#refresh-load) - [Release Collection](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#release-collection) - [Collection Aliases](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#collection-aliases) - [Create Alias](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#create-alias) - [Describe Alias](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#describe-alias) - [List Aliases](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#list-aliases) - [Alter Alias](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#alter-alias) - [Drop Alias](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#drop-alias) - [Collection Compaction](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#collection-compaction) - [Compact Collection](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#compact-collection) - [Get Compaction State](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#get-compaction-state) - [Get Compaction Plans](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#get-compaction-plans) - [Collection Replicas](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#collection-replicas) - [Primary Key Information](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#primary-key-information) - [Get Primary Key Field Name](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#get-primary-key-field-name) - [Get Primary Key Field Type](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#get-primary-key-field-type) - [Get Primary Key Field Schema](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#get-primary-key-field-schema) - [Dropping Collections](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#dropping-collections) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#best-practices) - [Truncate Collection](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#truncate-collection) - [Batch Describe Collections](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#batch-describe-collections) - [Alter Collection Properties](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#alter-collection-properties-1) - [Alter Field Properties](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#alter-field-properties-1) - [Drop Collection Properties](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#drop-collection-properties-1) - [External Collections Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#external-collections-milvus-30) - [Project children from a Struct source column](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#project-children-from-a-struct-source-column) - [Refresh the collection](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#refresh-the-collection) - [Collection Snapshots Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#collection-snapshots-milvus-30) - [Export and Restore a Portable Snapshot Milvus 3.0.6](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#export-and-restore-a-portable-snapshot-milvus-306) - [Collection Functions](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#collection-functions) - [Add a Function Output Field and Index](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#add-a-function-output-field-and-index) - [Drop a Function and Its Output Field](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#drop-a-function-and-its-output-field) - [Refresh Load](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#refresh-load-1) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#next-steps) - [Function-field backfill](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#function-field-backfill) Collections are the primary data structure in Milvus, similar to tables in traditional databases. This guide covers all collection management operations. ## Creating Collections ### Basic Collection Creation ```javascript import { MilvusClient, DataType } from '@zilliz/milvus2-sdk-node'; const schema = [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, }, ]; await client.createCollection({ collection_name: 'my_collection', fields: schema, }); ``` ### Collection with Consistency Level ```javascript await client.createCollection({ collection_name: 'my_collection', fields: schema, consistency_level: 'Bounded', // 'Strong', 'Session', 'Bounded', 'Eventually' }); ``` ### Collection with Properties ```javascript await client.createCollection({ collection_name: 'my_collection', fields: schema, properties: { 'collection.ttl.seconds': 3600, // Collection-level TTL in seconds }, }); ``` ### Entity-Level TTL Entity-level TTL lets each row carry its own expiration time. Create a nullable `Timestamptz` field and set the collection property `ttl_field` to that field name. ```javascript import { CollectionProperties, DataType } from '@zilliz/milvus2-sdk-node'; await client.createCollection({ collection_name: 'entity_ttl_collection', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true }, { name: 'vector', data_type: DataType.FloatVector, dim: 128 }, { name: 'expire_at', data_type: DataType.Timestamptz, nullable: true }, ], properties: { [CollectionProperties.TTL_FIELD]: 'expire_at', }, }); await client.insert({ collection_name: 'entity_ttl_collection', data: [ { id: 1, vector: [ /* ... */ ], expire_at: null, }, // never expires { id: 2, vector: [ /* ... */ ], expire_at: '2099-12-31T00:00:00Z', }, { id: 3, vector: [ /* ... */ ], expire_at: '2000-01-01T00:00:00Z', }, // expired ], }); ``` Expired entities are excluded from query and search results. You can add a TTL field to an existing collection with `addCollectionField()` and then set `CollectionProperties.TTL_FIELD` with `alterCollectionProperties()`. ### Collection with Partition Configuration ```javascript await client.createCollection({ collection_name: 'my_collection', fields: schema, num_partitions: 8, // Number of partitions }); ``` ### Allow Insert with AutoID For collections whose primary key field uses `autoID: true`, inserts normally omit the primary key. If you need to import or backfill rows with explicit primary keys, enable the `allow_insert_auto_id` collection property. ```javascript await client.alterCollectionProperties({ collection_name: 'my_collection', properties: { allow_insert_auto_id: 'true', }, }); await client.insert({ collection_name: 'my_collection', data: [ { id: 10001, // accepted even when the primary key field has autoID: true vector: [ /* ... */ ], }, ], }); ``` Use this only when you need to preserve existing IDs. For normal writes to an AutoID collection, keep omitting the primary key field. ## Checking Collection Existence Check if a collection exists: ```javascript const exists = await client.hasCollection({ collection_name: 'my_collection', }); console.log('Collection exists:', exists.value); ``` ## Listing Collections List all collections: ```javascript const result = await client.showCollections(); console.log( 'Collections:', result.data.map((collection) => collection.name) ); // Output: ['collection1', 'collection2', 'my_collection'] ``` List collections with details: ```javascript const result = await client.showCollections({ type: ShowCollectionsType.All, // 'All' or 'InMemory' }); result.data.forEach((collection) => { console.log(`Collection: ${collection.name}`); console.log(`ID: ${collection.id}`); console.log(`Loaded: ${collection.loadedPercentage}%`); }); ``` ## Describing Collections Get detailed information about a collection: ```javascript const result = await client.describeCollection({ collection_name: 'my_collection', }); console.log('Schema:', result.schema); console.log('Collection ID:', result.collectionID); console.log('Consistency Level:', result.consistency_level); ``` ## Modifying Collections ### Alter Collection Properties Modify collection properties: ```javascript await client.alterCollectionProperties({ collection_name: 'my_collection', properties: { 'collection.ttl.seconds': 7200, }, }); ``` ### Rename Collection Rename a collection: ```javascript await client.renameCollection({ collection_name: 'old_name', new_collection_name: 'new_name', }); ``` ### Drop Collection Properties Remove specific properties: ```javascript await client.dropCollectionProperties({ collection_name: 'my_collection', properties: ['collection.ttl.seconds'], }); ``` ## Dynamic Schema Milvus 3.0 ### Adding Fields to Existing Collection Add a single field: ```javascript await client.addCollectionField({ collection_name: 'my_collection', field: { name: 'new_field', data_type: DataType.Int64, description: 'A new field', }, }); ``` Add multiple fields: ```javascript await client.addCollectionFields({ collection_name: 'my_collection', fields: [ { name: 'field1', data_type: DataType.Int64, }, { name: 'field2', data_type: DataType.VarChar, max_length: 256, }, ], }); ``` ### Dropping Fields Drop a field by name: ```javascript await client.dropCollectionField({ collection_name: 'my_collection', field_name: 'field1', }); ``` You can also pass `field_id` instead of `field_name`. Get the field ID from `describeCollection({ cache: false })` and provide exactly one identifier. ### Alter Field Properties Modify field properties: ```javascript await client.alterCollectionFieldProperties({ collection_name: 'my_collection', field_name: 'my_field', properties: { max_length: 512, }, }); ``` ## Collection Statistics Get collection statistics: ```javascript const stats = await client.getCollectionStatistics({ collection_name: 'my_collection', }); console.log('Row count:', stats.data.row_count); console.log('Statistics:', stats.stats); ``` ## Collection Loading ### Load Collection Load a collection into memory for search: ```javascript // Synchronous load (waits until loaded) await client.loadCollectionSync({ collection_name: 'my_collection', }); // Asynchronous load (returns immediately) await client.loadCollectionAsync({ collection_name: 'my_collection', }); ``` ### Check Loading Progress ```javascript const progress = await client.getLoadingProgress({ collection_name: 'my_collection', }); console.log('Loading progress:', progress.progress); ``` ### Check Load State ```javascript const state = await client.getLoadState({ collection_name: 'my_collection', }); console.log('Load state:', state.state); // 'LoadStateNotExist', 'LoadStateNotLoad', 'LoadStateLoading', 'LoadStateLoaded' ``` ### Refresh Load Refresh the loaded collection: ```javascript await client.refreshLoad({ collection_name: 'my_collection', }); ``` ### Release Collection Release a collection from memory: ```javascript await client.releaseCollection({ collection_name: 'my_collection', }); ``` ## Collection Aliases ### Create Alias Create an alias for a collection: ```javascript await client.createAlias({ collection_name: 'my_collection', alias: 'my_alias', }); ``` ### Describe Alias Get information about an alias: ```javascript const result = await client.describeAlias({ collection_name: 'my_collection', alias: 'my_alias', }); console.log('Collection name:', result.collection); console.log('Alias:', result.alias); ``` ### List Aliases List all aliases for a collection: ```javascript const result = await client.listAliases({ collection_name: 'my_collection', }); console.log('Aliases:', result.aliases); ``` ### Alter Alias Change which collection an alias points to: ```javascript await client.alterAlias({ collection_name: 'new_collection', alias: 'my_alias', }); ``` ### Drop Alias Remove an alias: ```javascript await client.dropAlias({ alias: 'my_alias', }); ``` ## Collection Compaction ### Compact Collection Trigger compaction: ```javascript const result = await client.compact({ collection_name: 'my_collection', }); console.log('Compaction ID:', result.compactionID); ``` ### Get Compaction State Check compaction status: ```javascript const state = await client.getCompactionState({ compactionID: 12345, }); console.log('State:', state.state); ``` ### Get Compaction Plans Get detailed compaction plans: ```javascript const plans = await client.getCompactionStateWithPlans({ compactionID: 12345, }); console.log('Plans:', plans.mergeInfos); ``` ## Collection Replicas Get replica information: ```javascript const { collectionID } = await client.describeCollection({ collection_name: 'my_collection', }); const replicas = await client.getReplicas({ collectionID }); console.log('Replicas:', replicas.replicas); ``` Pass the collection ID to include shard node details: ```javascript const replicas = await client.getReplicas({ collectionID, with_shard_nodes: true, }); replicas.replicas.forEach((replica) => { console.log('Resource group:', replica.resource_group_name); console.log('Outbound nodes:', replica.num_outbound_node); console.log('Shard replicas:', replica.shard_replicas); }); ``` `getReplicas()` accepts either `collection_name`/`db_name` or a `collectionID`, depending on what identifiers are available in your application. ## Primary Key Information ### Get Primary Key Field Name ```javascript const pkField = await client.getPkFieldName({ collection_name: 'my_collection', }); console.log('Primary key field:', pkField); ``` ### Get Primary Key Field Type ```javascript const pkType = await client.getPkFieldType({ collection_name: 'my_collection', }); console.log('Primary key type:', pkType); ``` ### Get Primary Key Field Schema ```javascript const pkFieldSchema = await client.getPkField({ collection_name: 'my_collection', }); console.log('Primary key schema:', pkFieldSchema); ``` ## Dropping Collections Drop a collection (this permanently deletes all data): ```javascript await client.dropCollection({ collection_name: 'my_collection', }); ``` ## Best Practices 1. **Naming**: Use descriptive collection names 2. **Schema Design**: Plan your schema carefully before creating collections 3. **Loading**: Load collections before performing searches 4. **Aliases**: Use aliases for easier collection management and zero-downtime updates 5. **Compaction**: Regularly compact collections to optimize performance 6. **Release**: Release collections from memory when not in use to free resources ## Truncate Collection Remove all data from a collection while keeping its schema and indexes: ```javascript await client.truncateCollection({ collection_name: 'my_collection', }); ``` This is faster than dropping and recreating the collection when you only need to clear data. ## Batch Describe Collections Describe multiple collections in a single call: ```javascript const result = await client.batchDescribeCollections({ collection_names: ['collection_a', 'collection_b', 'collection_c'], }); result.responses.forEach((col) => { console.log(`Collection: ${col.collection_name}`); console.log(`Fields: ${col.schema.fields.map((f) => f.name)}`); }); ``` ## Alter Collection Properties Modify collection-level properties: ```javascript await client.alterCollectionProperties({ collection_name: 'my_collection', properties: { 'collection.ttl.seconds': 7200, }, }); ``` ### Alter Field Properties Modify field-level properties: ```javascript await client.alterCollectionFieldProperties({ collection_name: 'my_collection', field_name: 'text', properties: { max_length: 1024, }, }); ``` ### Drop Collection Properties Remove collection properties: ```javascript await client.dropCollectionProperties({ collection_name: 'my_collection', properties: ['collection.ttl.seconds'], }); ``` ## External Collections Milvus 3.0 External collections reference data stored outside Milvus. Use `external_source` and `external_spec` at collection creation time, and map Milvus fields to source fields with `external_field`. Milvus supplies the primary key for the external collection. ```javascript await client.createCollection({ collection_name: 'external_products', external_source: 's3://bucket/path/products/', external_spec: JSON.stringify({ format: 'parquet' }), fields: [ { name: 'id', data_type: DataType.Int64, external_field: 'product_id', }, { name: 'name', data_type: DataType.VarChar, max_length: 256, external_field: 'title', }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, external_field: 'embedding', }, ], }); ``` ### Project children from a Struct source column On Milvus 3.0.7+, set the StructArray parent’s `external_field` to the top-level Arrow column name. For example, add this field to the external collection schema to expose only `raw_events.score` under the Milvus field `events`: ```typescript const eventsField = { name: 'events', data_type: DataType.Array, element_type: DataType.Struct, external_field: 'raw_events', nullable: true, max_capacity: 8, fields: [{ name: 'score', data_type: DataType.Int32 }], }; ``` Declare each selected child with its source name. Milvus derives the child’s mapping (here `raw_events[score]`), which you can inspect with `describeCollection()`. A non-null Arrow Struct returns a one-element array. A List of Structs retains its element order, including an empty list. A null source parent returns `null`. With `HttpClient`, declare the parent in `schema.structFields`, set `externalField: 'raw_events'`, and declare the scalar child as `{ fieldName: 'score', dataType: 'Array', elementDataType: 'Int32' }`. Specify the parent’s capacity with `typeParams: { max_capacity: 8 }`. ### Refresh the collection Refresh an external collection when the source changes: ```javascript const refresh = await client.refreshExternalCollection({ collection_name: 'external_products', external_source: 's3://bucket/path/products-v2/', // optional external_spec: JSON.stringify({ format: 'parquet' }), // optional }); const progress = await client.getRefreshExternalCollectionProgress({ job_id: refresh.job_id, }); const jobs = await client.listRefreshExternalCollectionJobs({ collection_name: 'external_products', }); ``` ## Collection Snapshots Milvus 3.0 Snapshots capture a collection at a point in time. You can describe, restore, pin, and remove snapshots with the snapshot APIs. ```javascript await client.createSnapshot({ collection_name: 'my_collection', snapshot_name: 'my_collection_snapshot_001', description: 'Before schema migration', compaction_protection_seconds: 3600, }); const snapshots = await client.listSnapshots({ collection_name: 'my_collection', }); const snapshot = await client.describeSnapshot({ collection_name: 'my_collection', snapshot_name: 'my_collection_snapshot_001', }); ``` Restore a snapshot into another collection and check the restore job: ```javascript const restore = await client.restoreSnapshot({ snapshot_name: 'my_collection_snapshot_001', source_collection_name: 'my_collection', target_collection_name: 'my_collection_restored', }); const state = await client.getRestoreSnapshotState({ job_id: restore.job_id, }); const restoreJobs = await client.listRestoreSnapshotJobs({ collection_name: 'my_collection_restored', }); ``` Pin snapshot data while copying it out, then release the pin when finished: ```javascript const pin = await client.pinSnapshotData({ collection_name: 'my_collection', snapshot_name: 'my_collection_snapshot_001', ttl_seconds: 3600, }); await client.unpinSnapshotData({ pin_id: pin.pin_id }); await client.dropSnapshot({ collection_name: 'my_collection', snapshot_name: 'my_collection_snapshot_001', }); ``` ### Export and Restore a Portable Snapshot Milvus 3.0.6 Export a snapshot to an object-storage path to create a self-contained bundle. Use the completed export’s metadata URI to restore into a new collection. ```typescript import { ExportSnapshotState } from '@zilliz/milvus2-sdk-node'; const job = await client.exportSnapshot({ collection_name: 'my_collection', snapshot_name: 'my_collection_snapshot_001', target_s3_path: 'exports/my_collection_snapshot_001', }); const { info } = await client.getExportSnapshotState({ job_id: job.job_id }); if (info.state === ExportSnapshotState.ExportSnapshotCompleted) { const restore = await client.restoreExternalSnapshot({ target_collection_name: 'my_collection_from_export', snapshot_metadata_uri: info.snapshot_metadata_uri, }); const restoreState = await client.getRestoreSnapshotState({ job_id: restore.job_id, }); } ``` A relative destination uses the cluster’s configured storage. Export and restore accept an optional `external_spec` JSON string for configuring external object storage. Poll the job methods until the state is completed or failed. `listSnapshots()` also exposes snapshot descriptions and Unix creation times in `snapshot_summaries` when the server provides them. ## Collection Functions Collection functions are auto-processing pipelines that transform data at insert and query time. The most common use case is BM25 full-text search, where a function automatically converts text to sparse vectors. ### Add a Function Output Field and Index Milvus 3.0 Use `addFunctionField()` to atomically add a function output field, the function schema, and its bound index. The wrapper supports BM25 and MinHash functions. ```javascript import { DataType, FunctionType, IndexType, MetricType, } from '@zilliz/milvus2-sdk-node'; await client.addFunctionField({ collection_name: 'my_collection', field: { name: 'sparse_vector', data_type: DataType.SparseFloatVector, is_function_output: true, }, function: { name: 'text_bm25', type: FunctionType.BM25, input_field_names: ['body'], output_field_names: ['sparse_vector'], params: {}, }, index_name: 'text_bm25_index', extra_params: { index_type: IndexType.SPARSE_INVERTED_INDEX, metric_type: MetricType.BM25, }, }); ``` MinHash functions generate binary signatures for set or shingle similarity: ```javascript await client.addFunctionField({ collection_name: 'my_collection', field: { name: 'minhash_vector', data_type: DataType.BinaryVector, dim: 512, is_function_output: true, }, function: { name: 'body_minhash', type: FunctionType.MINHASH, input_field_names: ['body'], output_field_names: ['minhash_vector'], params: { num_hashes: 16, shingle_size: 3 }, }, index_name: 'minhash_index', extra_params: { index_type: IndexType.MINHASH_LSH, metric_type: MetricType.MHJACCARD, params: { mh_lsh_band: 8 }, }, }); ``` The lower-level `alterCollectionSchema()` API exposes the same schema mutation when you need to build the complete request yourself. ### Drop a Function and Its Output Field ```javascript await client.dropFunctionField({ collection_name: 'my_collection', function_name: 'text_bm25', }); ``` `dropFunctionField()` also removes the function output field and bound index. For more details on BM25 functions, see [Full-Text Search](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/). ## Refresh Load After modifying a loaded collection’s schema (e.g., adding fields or functions), refresh the load to pick up changes: ```javascript await client.refreshLoad({ collection_name: 'my_collection', }); ``` ## Next Steps - Learn about [Partition Management](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/) - Explore [Index Management](https://milvus-io.github.io/milvus-sdk-node/management/index-management/) - Check out [Data Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/) ## Function-field backfill In SDK 3.0.4+, `addFunctionField()` returns after the schema change is accepted. Milvus asynchronously backfills existing sealed segments through schema-bump compaction. The wrapper supports BM25 → SparseFloatVector and MINHASH → BinaryVector; provide an explicit bound `index_type` other than `AUTOINDEX`. ```typescript const stats = await client.getCollectionStatistics({ collection_name: 'documents', }); if (stats.status.error_code !== ErrorCode.SUCCESS) { throw new Error(stats.status.reason); } console.log({ consistent: stats.data.schema_version_consistent_segments, total: stats.data.schema_version_total_segments, }); ``` For an existing collection with sealed segments, poll these values with a timeout until `total > 0` and `consistent === total` after numeric conversion. Missing counters do not prove completion. Also check `getIndexState({ collection_name, index_name })` reaches `Finished` (stop on `Failed`) before loading and searching the new field. Empty collections need no historical backfill. --- # Partition Management Organize data into Milvus partitions and create, load, release, or target selected partitions from the Node.js SDK. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/management/partition-management/ ## Section links - [Creating Partitions](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#creating-partitions) - [Checking Partition Existence](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#checking-partition-existence) - [Listing Partitions](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#listing-partitions) - [Partition Statistics](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#partition-statistics) - [Partition Loading](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#partition-loading) - [Load Partitions](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#load-partitions) - [Release Partitions](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#release-partitions) - [Dropping Partitions](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#dropping-partitions) - [Working with Partitions](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#working-with-partitions) - [Inserting Data into Partitions](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#inserting-data-into-partitions) - [Querying Partitions](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#querying-partitions) - [Searching Partitions](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#searching-partitions) - [Default Partition](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#default-partition) - [Partition Best Practices](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#partition-best-practices) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/#next-steps) Partitions allow you to organize data within a collection for better performance and management. This guide covers all partition operations. ## Creating Partitions Create a new partition: ```javascript await client.createPartition({ collection_name: 'my_collection', partition_name: 'partition_1', }); ``` ## Checking Partition Existence Check if a partition exists: ```javascript const exists = await client.hasPartition({ collection_name: 'my_collection', partition_name: 'partition_1', }); console.log('Partition exists:', exists.value); ``` ## Listing Partitions List all partitions in a collection: ```javascript const result = await client.listPartitions({ collection_name: 'my_collection', }); console.log('Partitions:', result.partition_names); // Output: ['_default', 'partition_1', 'partition_2'] ``` ## Partition Statistics Get statistics for a partition: ```javascript const stats = await client.getPartitionStatistics({ collection_name: 'my_collection', partition_name: 'partition_1', }); console.log('Row count:', stats.data.row_count); console.log('Statistics:', stats.stats); ``` ## Partition Loading ### Load Partitions Load partitions into memory: ```javascript // Asynchronous load await client.loadPartitions({ collection_name: 'my_collection', partition_names: ['partition_1', 'partition_2'], }); // Synchronous load (waits until loaded) await client.loadPartitionsSync({ collection_name: 'my_collection', partition_names: ['partition_1', 'partition_2'], }); ``` ### Release Partitions Release partitions from memory: ```javascript await client.releasePartitions({ collection_name: 'my_collection', partition_names: ['partition_1', 'partition_2'], }); ``` ## Dropping Partitions Drop a partition (this permanently deletes all data in the partition): ```javascript await client.dropPartition({ collection_name: 'my_collection', partition_name: 'partition_1', }); ``` ## Working with Partitions ### Inserting Data into Partitions Insert data into a specific partition: ```javascript await client.insert({ collection_name: 'my_collection', partition_name: 'partition_1', data: [ { vector: [ /* ... */ ], text: 'data for partition 1', }, ], }); ``` ### Querying Partitions Query data from specific partitions: ```javascript const results = await client.query({ collection_name: 'my_collection', expr: 'id > 100', partition_names: ['partition_1'], output_fields: ['vector', 'text'], }); ``` ### Searching Partitions Search within specific partitions: ```javascript const results = await client.search({ collection_name: 'my_collection', data: [ /* vector */ ], partition_names: ['partition_1', 'partition_2'], limit: 10, }); ``` ## Default Partition Every collection has a default partition named `_default`. Data inserted without specifying a partition goes to the default partition: ```javascript // Data goes to _default partition await client.insert({ collection_name: 'my_collection', data: [ /* ... */ ], }); // Explicitly specify partition await client.insert({ collection_name: 'my_collection', partition_name: 'partition_1', data: [ /* ... */ ], }); ``` ## Partition Best Practices 1. **Use partitions for data organization**: Organize data by time, category, or region 2. **Load only needed partitions**: Load only the partitions you need to query 3. **Partition naming**: Use descriptive names that reflect the partition’s purpose 4. **Default partition**: Use the default partition for general data 5. **Partition size**: Keep partitions at reasonable sizes for optimal performance ## Next Steps - Learn about [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/) - Explore [Data Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/) - Check out [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) --- # Index Management Build and tune vector and scalar indexes for Milvus collections, check index status, and drop or rebuild indexes from Node.js. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/management/index-management/ ## Section links - [Creating Indexes](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#creating-indexes) - [Basic Index Creation](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#basic-index-creation) - [Index with Parameters](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#index-with-parameters) - [Index Types](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#index-types) - [HNSW (Hierarchical Navigable Small World)](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#hnsw-hierarchical-navigable-small-world) - [IVF_FLAT (Inverted File Flat)](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#ivf_flat-inverted-file-flat) - [IVF_SQ8 (Inverted File Scalar Quantization)](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#ivf_sq8-inverted-file-scalar-quantization) - [IVF_PQ (Inverted File Product Quantization)](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#ivf_pq-inverted-file-product-quantization) - [FLAT](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#flat) - [AUTOINDEX](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#autoindex) - [MINHASH_LSH](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#minhash_lsh) - [Metric Types](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#metric-types) - [Index Operations](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#index-operations) - [Describe Index](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#describe-index) - [List Indexes](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#list-indexes) - [Get Index State](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#get-index-state) - [Get Index Build Progress](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#get-index-build-progress) - [Alter Index Properties](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#alter-index-properties) - [Drop Index Properties](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#drop-index-properties) - [Drop Index](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#drop-index) - [Index Best Practices](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#index-best-practices) - [Choosing an Index Type](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#choosing-an-index-type) - [Index Parameters](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#index-parameters) - [Metric Type Selection](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#metric-type-selection) - [Index Building](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#index-building) - [Complete Example](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#complete-example) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#next-steps) - [Additional index enums in SDK 3.0.5](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#additional-index-enums-in-sdk-305) Indexes are crucial for optimizing search performance in Milvus. This guide covers creating, managing, and optimizing indexes. ## Creating Indexes ### Basic Index Creation Create an index on a vector field: ```javascript await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'HNSW', metric_type: 'L2', }); ``` ### Index with Parameters Specify index parameters: ```javascript await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'HNSW', metric_type: 'L2', params: { M: 16, efConstruction: 200, }, }); ``` ## Index Types ### HNSW (Hierarchical Navigable Small World) Best for high-dimensional vectors and high recall: ```javascript await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'HNSW', metric_type: 'L2', params: { M: 16, // Number of connections efConstruction: 200, // Construction parameter }, }); ``` ### IVF_FLAT (Inverted File Flat) Good balance of speed and accuracy: ```javascript await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'IVF_FLAT', metric_type: 'L2', params: { nlist: 1024, // Number of clusters }, }); ``` ### IVF_SQ8 (Inverted File Scalar Quantization) Memory-efficient version of IVF_FLAT: ```javascript await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'IVF_SQ8', metric_type: 'L2', params: { nlist: 1024, }, }); ``` ### IVF_PQ (Inverted File Product Quantization) Most memory-efficient, good for large datasets: ```javascript await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'IVF_PQ', metric_type: 'L2', params: { nlist: 1024, m: 8, // Number of sub-vectors nbits: 8, // Number of bits per sub-vector }, }); ``` ### FLAT Exact search, no index (for small datasets): ```javascript await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'FLAT', metric_type: 'L2', }); ``` ### AUTOINDEX Let Milvus choose the best index: ```javascript await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'AUTOINDEX', metric_type: 'L2', }); ``` ### MINHASH_LSH `MINHASH_LSH` is an index for binary vectors that uses MinHash locality-sensitive hashing. It is useful for approximate similarity search on binary signatures, sets, shingles, or other binary encodings where Jaccard-style similarity is appropriate. ```javascript await client.createCollection({ collection_name: 'binary_docs', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true }, { name: 'binary_vector', data_type: DataType.BinaryVector, dim: 128 }, ], }); await client.createIndex({ collection_name: 'binary_docs', field_name: 'binary_vector', index_type: 'MINHASH_LSH', metric_type: 'JACCARD', }); ``` For binary vectors, the `dim` value must be a multiple of 8, and inserted binary vector payloads use `dim / 8` bytes. Milvus 3.0 can generate MinHash binary signatures from a text field and create the bound index atomically: ```javascript import { DataType, FunctionType, IndexType, MetricType, } from '@zilliz/milvus2-sdk-node'; await client.addFunctionField({ collection_name: 'documents', field: { name: 'minhash_vector', data_type: DataType.BinaryVector, dim: 512, is_function_output: true, }, function: { name: 'body_minhash', type: FunctionType.MINHASH, input_field_names: ['body'], output_field_names: ['minhash_vector'], params: { num_hashes: 16, shingle_size: 3 }, }, index_name: 'minhash_index', extra_params: { index_type: IndexType.MINHASH_LSH, metric_type: MetricType.MHJACCARD, params: { mh_lsh_band: 8 }, }, }); ``` Use `MHJACCARD` for MinHash function output. Plain binary-vector workflows can continue to use `JACCARD` when appropriate. ## Metric Types Choose the appropriate metric type for your use case: - **L2**: Euclidean distance (most common) - **IP**: Inner product - **COSINE**: Cosine similarity - **HAMMING**: Hamming distance (for binary vectors) - **JACCARD**: Jaccard distance (for binary vectors, including MinHash use cases) ```javascript // L2 distance await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'HNSW', metric_type: 'L2', }); // Cosine similarity await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'HNSW', metric_type: 'COSINE', }); ``` ## Index Operations ### Describe Index Get index information: ```javascript const indexInfo = await client.describeIndex({ collection_name: 'my_collection', field_name: 'vector', }); for (const index of indexInfo.index_descriptions) { const params = Object.fromEntries( index.params.map(({ key, value }) => [key, value]) ); console.log('Index type:', params.index_type); console.log('Metric type:', params.metric_type); console.log('Parameters:', params); } ``` ### List Indexes List all indexes in a collection: ```javascript const indexes = await client.listIndexes({ collection_name: 'my_collection', }); console.log('Indexes:', indexes.indexes); ``` ### Get Index State Check if index is built: ```javascript const state = await client.getIndexState({ collection_name: 'my_collection', field_name: 'vector', }); console.log('Index state:', state.state); // 'IndexStateNone', 'IndexStateUnissued', 'IndexStateInProgress', 'IndexStateFinished', 'IndexStateFailed' ``` ### Get Index Build Progress Monitor index build progress: ```javascript const progress = await client.getIndexBuildProgress({ collection_name: 'my_collection', field_name: 'vector', }); console.log('Indexed rows:', progress.indexed_rows); console.log('Total rows:', progress.total_rows); ``` ### Alter Index Properties Release the collection before modifying its index properties: ```javascript await client.alterIndexProperties({ collection_name: 'my_collection', index_name: 'vector_idx', params: { 'mmap.enabled': true, }, }); ``` ### Drop Index Properties Remove index properties: ```javascript await client.dropIndexProperties({ collection_name: 'my_collection', index_name: 'vector_idx', properties: ['mmap.enabled'], }); ``` ### Drop Index Delete an index: ```javascript await client.dropIndex({ collection_name: 'my_collection', field_name: 'vector', }); ``` ## Index Best Practices ### Choosing an Index Type 1. **Small datasets (< 1M vectors)**: Use FLAT for exact search 2. **Medium datasets (1M - 10M vectors)**: Use HNSW for high recall 3. **Large datasets (> 10M vectors)**: Use IVF_PQ for memory efficiency 4. **High-dimensional vectors**: Prefer HNSW or IVF_FLAT 5. **Memory-constrained**: Use IVF_SQ8 or IVF_PQ 6. **Binary signatures / set similarity**: Use MINHASH_LSH with JACCARD ### Index Parameters **HNSW Parameters:** - `M`: Higher values improve recall but increase memory (typical: 16-32) - `efConstruction`: Higher values improve index quality but slower build (typical: 100-500) **IVF Parameters:** - `nlist`: Number of clusters (typical: sqrt(total_vectors) to total_vectors/10) **IVF_PQ Parameters:** - `m`: Number of sub-vectors (typical: 8-16) - `nbits`: Bits per sub-vector (typical: 8) ### Metric Type Selection - **L2**: Use for embeddings trained with L2 distance - **IP**: Use for embeddings trained with inner product - **COSINE**: Use for normalized embeddings - **HAMMING/JACCARD**: Use for binary vectors - **JACCARD + MINHASH_LSH**: Use for binary signatures and set-similarity workloads ### Index Building 1. **Build after insertion**: Create index after inserting data 2. **Monitor progress**: Check build progress for large datasets 3. **Load after indexing**: Load collection after index is built 4. **One index per vector field**: Each vector field can have one index ## Complete Example ```javascript // Create collection await client.createCollection({ collection_name: 'my_collection', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, }, ], }); // Insert data await client.insert({ collection_name: 'my_collection', data: [ /* ... */ ], }); // Create index await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'HNSW', metric_type: 'L2', params: { M: 16, efConstruction: 200, }, }); // Wait for index to be built let state; do { state = await client.getIndexState({ collection_name: 'my_collection', field_name: 'vector', }); await new Promise((resolve) => setTimeout(resolve, 1000)); } while (state.state !== 'IndexStateFinished'); // Load collection await client.loadCollectionSync({ collection_name: 'my_collection', }); // Now you can search const results = await client.search({ collection_name: 'my_collection', data: [ /* vector */ ], limit: 10, }); ``` ## Next Steps - Learn about [Data Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/) - Explore [Search Operations](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/) - Check out [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) ## Additional index enums in SDK 3.0.5 | Enum | Purpose | | --- | --- | | `IndexType.HNSW_SQ` | HNSW with scalar quantization | | `IndexType.HNSW_PQ` | HNSW with product quantization | | `IndexType.HNSW_PRQ` | HNSW with product residual quantization | | `IndexType.AISAQ` | DiskANN variant with PQ codes stored with the graph | | `IndexType.NGRAM` | N-gram scalar index for VarChar / JSON paths, accelerating LIKE | | `IndexType.FMINDEX` | FM-index for VarChar pattern matching | Use these constants as `createIndex({ index_type: IndexType.HNSW_SQ, ... })` values. The enum additions do not enable an index on older servers; consult your server’s supported index types and parameters. Legacy enum members remain for compatibility and do not guarantee current server support. --- # User & Role Management Manage Milvus users, passwords, roles, and permissions in Node.js, including role assignment and privilege grants. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/ ## Section links - [User Operations](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#user-operations) - [Create User](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#create-user) - [Update User](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#update-user) - [Delete User](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#delete-user) - [List Users](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#list-users) - [Describe User](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#describe-user) - [Role Operations](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#role-operations) - [Create Role](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#create-role) - [Drop Role](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#drop-role) - [List Roles](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#list-roles) - [Describe Role](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#describe-role) - [Has Role](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#has-role) - [User-Role Relationships](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#user-role-relationships) - [Add User to Role](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#add-user-to-role) - [Remove User from Role](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#remove-user-from-role) - [Privilege Management](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#privilege-management) - [Grant Privilege](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#grant-privilege) - [Revoke Privilege](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#revoke-privilege) - [Select Grant](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#select-grant) - [List Grants](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#list-grants) - [Privilege Groups](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#privilege-groups) - [Create Privilege Group](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#create-privilege-group) - [Drop Privilege Group](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#drop-privilege-group) - [List Privilege Groups](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#list-privilege-groups) - [Add Privileges to Group](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#add-privileges-to-group) - [Remove Privileges from Group](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#remove-privileges-from-group) - [RBAC v2](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#rbac-v2) - [Grant Privilege v2](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#grant-privilege-v2) - [Revoke Privilege v2](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#revoke-privilege-v2) - [Backup RBAC](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#backup-rbac) - [Restore RBAC](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#restore-rbac) - [Drop All Roles](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#drop-all-roles) - [Privilege Objects](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#privilege-objects) - [Privilege Names](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#privilege-names) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#best-practices) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/#next-steps) This guide covers user and role management, including authentication, authorization, and RBAC operations. ## User Operations ### Create User Create a new user: ```javascript await client.createUser({ username: 'newuser', password: 'securepassword', }); ``` ### Update User Update user password: ```javascript await client.updateUser({ username: 'newuser', oldPassword: 'securepassword', newPassword: 'newpassword', }); ``` ### Delete User Delete a user: ```javascript await client.deleteUser({ username: 'newuser', }); ``` ### List Users List all users: ```javascript const result = await client.listUsers(); console.log('Users:', result.usernames); ``` ### Describe User Get user information: ```javascript const user = await client.describeUser({ username: 'newuser', }); console.log('User info:', user); ``` ## Role Operations ### Create Role Create a new role: ```javascript await client.createRole({ roleName: 'catalog_reader', }); ``` ### Drop Role Delete a role: ```javascript await client.dropRole({ roleName: 'catalog_reader', }); ``` ### List Roles List all roles: ```javascript const result = await client.listRoles(); console.log('Roles:', result.results); ``` ### Describe Role Get role information: ```javascript const role = await client.describeRole({ roleName: 'catalog_reader', }); console.log('Role info:', role); ``` ### Has Role Check if a role exists: ```javascript const hasRole = await client.hasRole({ roleName: 'catalog_reader', }); console.log('Role exists:', hasRole.hasRole); ``` ## User-Role Relationships ### Add User to Role Assign a user to a role: ```javascript await client.addUserToRole({ username: 'newuser', roleName: 'catalog_reader', }); ``` ### Remove User from Role Remove a user from a role: ```javascript await client.removeUserFromRole({ username: 'newuser', roleName: 'catalog_reader', }); ``` ## Privilege Management Connect as an administrator to a Milvus server with authorization enabled before granting or revoking privileges. ### Grant Privilege Grant privileges to a role: ```javascript import { RbacObjects } from '@zilliz/milvus2-sdk-node'; await client.grantPrivilege({ roleName: 'catalog_reader', object: RbacObjects.Collection, objectName: 'my_collection', privilegeName: 'Load', }); ``` ### Revoke Privilege Revoke privileges from a role: ```javascript import { RbacObjects } from '@zilliz/milvus2-sdk-node'; await client.revokePrivilege({ roleName: 'catalog_reader', object: RbacObjects.Collection, objectName: 'my_collection', privilegeName: 'Load', }); ``` ### Select Grant Get granted privileges: ```javascript import { RbacObjects } from '@zilliz/milvus2-sdk-node'; const grants = await client.selectGrant({ roleName: 'catalog_reader', object: RbacObjects.Collection, objectName: 'my_collection', }); console.log('Grants:', grants.entities); ``` ### List Grants List all grants for a role: ```javascript const grants = await client.listGrants({ roleName: 'catalog_reader', }); console.log('Grants:', grants.entities); ``` ## Privilege Groups ### Create Privilege Group Create a privilege group: ```javascript await client.createPrivilegeGroup({ group_name: 'readonly_group', }); ``` ### Drop Privilege Group Delete a privilege group: ```javascript await client.dropPrivilegeGroup({ group_name: 'readonly_group', }); ``` ### List Privilege Groups List all privilege groups: ```javascript const groups = await client.listPrivilegeGroups(); console.log( 'Groups:', groups.privilege_groups.map((group) => group.group_name) ); ``` ### Add Privileges to Group Add privileges to a group: ```javascript await client.addPrivilegesToGroup({ group_name: 'readonly_group', privileges: ['DescribeCollection'], }); ``` ### Remove Privileges from Group Remove privileges from a group: ```javascript await client.removePrivilegesFromGroup({ group_name: 'readonly_group', privileges: ['DescribeCollection'], }); ``` ## RBAC v2 ### Grant Privilege v2 Grant privileges using RBAC v2: ```javascript await client.grantPrivilegeV2({ role: 'catalog_reader', db_name: 'default', collection_name: 'my_collection', privilege: 'Load', }); ``` ### Revoke Privilege v2 Revoke privileges using RBAC v2: ```javascript await client.revokePrivilegeV2({ role: 'catalog_reader', db_name: 'default', collection_name: 'my_collection', privilege: 'Load', }); ``` ### Backup RBAC Backup RBAC configuration: ```javascript const backup = await client.backupRBAC(); console.log('Backup:', backup); ``` ### Restore RBAC Restore RBAC configuration: ```javascript await client.restoreRBAC({ RBAC_meta: backup.RBAC_meta, }); ``` ## Drop All Roles Drop all roles (use with caution): ```javascript const results = await client.dropAllRoles(); console.log('Dropped roles:', results); ``` ## Privilege Objects Supported privilege objects: - `Collection` - `Global` - `User` ## Privilege Names Common privilege names: - `Create` - `Drop` - `Describe` - `Show` - `Load` - `Release` - `Insert` - `Delete` - `Update` - `Search` - `Query` - `Flush` - `Compact` ## Best Practices 1. **Principle of least privilege**: Grant only necessary privileges 2. **Use roles**: Group users into roles for easier management 3. **Regular audits**: Review user and role assignments regularly 4. **Secure passwords**: Enforce strong password policies 5. **Backup RBAC**: Regularly backup RBAC configuration ## Next Steps - Learn about [Client Configuration](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/) - Explore [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) --- # Manage Query Nodes and Resource Groups Allocate Milvus query nodes and collection replicas with resource groups, and use the Node.js SDK to inspect or move them. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/management/resource-management/ ## Section links - [Resource Groups](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#resource-groups) - [Create Resource Group](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#create-resource-group) - [List Resource Groups](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#list-resource-groups) - [Describe Resource Group](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#describe-resource-group) - [Update Resource Group](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#update-resource-group) - [Drop Resource Groups](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#drop-resource-groups) - [Node Management](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#node-management) - [Transfer Node](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#transfer-node) - [Replica Management](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#replica-management) - [Transfer Replica](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#transfer-replica) - [Resource Group Configuration](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#resource-group-configuration) - [Configuration Structure](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#configuration-structure) - [Transfer Policies and Node Filters](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#transfer-policies-and-node-filters) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#best-practices) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/#next-steps) This guide covers resource group management and node/replica operations. ## Resource Groups Resource groups allow you to organize and manage compute resources. ### Create Resource Group Create a new resource group: ```javascript await client.createResourceGroup({ resource_group: 'rg1', config: { requests: { node_num: 2, }, limits: { node_num: 4, }, }, }); ``` ### List Resource Groups List all resource groups: ```javascript const groups = await client.listResourceGroups(); console.log('Resource groups:', groups.resource_groups); ``` ### Describe Resource Group Get detailed information about a resource group: ```javascript const info = await client.describeResourceGroup({ resource_group: 'rg1', }); console.log('Resource group info:', info); ``` ### Update Resource Group Update resource group configuration: ```javascript await client.updateResourceGroups({ resource_groups: { rg1: { requests: { node_num: 3 }, limits: { node_num: 6 }, }, }, }); ``` ### Drop Resource Groups Delete resource groups: ```javascript await client.dropResourceGroup({ resource_group: 'rg1' }); ``` ## Node Management ### Transfer Node Move a node to a different resource group: ```javascript await client.transferNode({ source_resource_group: 'rg1', target_resource_group: 'rg2', num_node: 1, }); ``` ## Replica Management ### Transfer Replica Move replicas to a different resource group: ```javascript await client.transferReplica({ source_resource_group: 'rg1', target_resource_group: 'rg2', collection_name: 'my_collection', num_replica: 1, }); ``` ## Resource Group Configuration ### Configuration Structure ```javascript { requests: { node_num: 2, // Requested number of nodes }, limits: { node_num: 4, // Maximum number of nodes }, } ``` ### Transfer Policies and Node Filters Resource group configuration can also define where to borrow missing nodes from, where to send redundant nodes, and which node labels are allowed in the group. ```javascript await client.updateResourceGroups({ resource_groups: { rg1: { requests: { node_num: 2 }, limits: { node_num: 4 }, transfer_from: [{ resource_group: '__default_resource_group' }], transfer_to: [{ resource_group: 'rg_overflow' }], node_filter: { node_labels: [{ key: 'workload', value: 'search' }], }, }, }, }); ``` When describing a resource group, the response includes node and movement details when Milvus returns them: ```javascript const info = await client.describeResourceGroup({ resource_group: 'rg1', }); console.log('Available nodes:', info.resource_group.num_available_node); console.log('Incoming nodes:', info.resource_group.num_incoming_node); console.log('Outgoing nodes:', info.resource_group.num_outgoing_node); console.log('Nodes:', info.resource_group.nodes); ``` ## Best Practices 1. **Organize by workload**: Create resource groups for different workloads 2. **Set appropriate limits**: Configure limits based on available resources 3. **Monitor usage**: Regularly check resource group usage 4. **Balance resources**: Use transfer operations to balance load ## Next Steps - Learn about [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/) - Explore [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) --- # Connection Pooling, Retries, and Tracing Configure connection pools, retries, error handling, logging, request tracing, and iterators in the Milvus Node.js SDK. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/ ## Section links - [Connection Pooling](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#connection-pooling) - [Configuration](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#configuration) - [Benefits](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#benefits) - [Retry Mechanisms](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#retry-mechanisms) - [Configuration](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#configuration-1) - [Retry Behavior](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#retry-behavior) - [Error Handling](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#error-handling) - [Error Types](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#error-types) - [Common Error Codes](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#common-error-codes) - [Error Response Structure](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#error-response-structure) - [Logging and Debugging](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#logging-and-debugging) - [Log Levels](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#log-levels) - [Log Levels](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#log-levels-1) - [Debugging](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#debugging) - [Request Tracing (TraceID)](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#request-tracing-traceid) - [Overview](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#overview) - [Automatic Timestamp](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#automatic-timestamp) - [Using TraceID](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#using-traceid) - [Supported Operations](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#supported-operations) - [Use Cases](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#use-cases) - [Implementation Details](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#implementation-details) - [Iterator Patterns](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#iterator-patterns) - [Query Iterator](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#query-iterator) - [Search Iterator](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#search-iterator) - [Sparse Vectors](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#sparse-vectors) - [Binary Vectors](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#binary-vectors) - [Float16/BFloat16 Vectors](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#float16bfloat16-vectors) - [Dynamic Fields](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#dynamic-fields) - [Performance Monitoring](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#performance-monitoring) - [Get Metrics](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#get-metrics) - [Replica Management](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#replica-management) - [Get Replicas](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#get-replicas) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#best-practices) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#next-steps) This guide covers advanced features including connection pooling, retry mechanisms, error handling, logging, and iterator patterns. ## Connection Pooling The SDK uses connection pooling to manage gRPC connections efficiently. ### Configuration ```javascript const client = new MilvusClient({ address: 'localhost:19530', pool: { min: 2, // Minimum pool size max: 10, // Maximum pool size idleTimeoutMillis: 30000, // Idle timeout }, }); ``` ### Benefits - **Efficiency**: Reuses connections instead of creating new ones - **Performance**: Reduces connection overhead - **Resource management**: Limits concurrent connections ## Retry Mechanisms Configure automatic retries for failed operations. ### Configuration ```javascript const client = new MilvusClient({ address: 'localhost:19530', maxRetries: 3, // Maximum retry attempts retryDelay: 1000, // Delay between retries (ms) }); ``` ### Retry Behavior The SDK automatically retries on: - Network errors - Transient server errors - Timeout errors ## Error Handling ### Error Types ```javascript import { ErrorCode } from '@zilliz/milvus2-sdk-node'; try { const { status } = await client.describeCollection({ collection_name: 'my_collection', }); if (status.error_code !== ErrorCode.SUCCESS) { console.error(status.error_code, status.reason); } } catch (error) { console.error('Transport or SDK error:', error); } ``` ### Common Error Codes - `Success`: Operation succeeded - `CollectionNotExists`: Collection not found - `IllegalArgument`: Invalid parameter - `IndexNotExist`: Index not found - `UnexpectedError`: Unexpected server error - `RateLimit`: Rate limit exceeded - `SchemaMismatch`: Schema mismatch ### Error Response Structure ```javascript { error_code: 'CollectionNotExists', reason: 'Collection my_collection does not exist', // ... other fields } ``` ## Logging and Debugging ### Log Levels Configure logging levels: ```javascript const client = new MilvusClient({ address: 'localhost:19530', logLevel: 'debug', // 'error', 'warn', 'info', 'debug' logPrefix: 'milvus-client', }); ``` ### Log Levels - **error**: Only error messages - **warn**: Warnings and errors - **info**: Informational messages, warnings, and errors - **debug**: All messages including debug information ### Debugging Enable trace for detailed debugging: ```javascript const client = new MilvusClient({ address: 'localhost:19530', trace: true, }); ``` ## Request Tracing (TraceID) Track and trace individual requests using trace IDs for debugging and monitoring purposes. ### Overview The SDK automatically adds a timestamp (`client-request-unixmsec`) to every request. You can optionally provide a `client_request_id` (or `client-request-id`) to track specific requests across your application. ### Automatic Timestamp Every request automatically includes a `client-request-unixmsec` timestamp: ```javascript // This request will have client-request-unixmsec automatically added await client.listCollections({ // Timestamp is added automatically, no configuration needed }); ``` ### Using TraceID Add a trace ID to track specific requests: ```javascript // Recommended: use client_request_id (JavaScript/TypeScript convention) const traceId = `trace-${Date.now()}`; await client.listCollections({ client_request_id: traceId, }); // Alternative: use client-request-id (compatible with pymilvus) await client.listCollections({ 'client-request-id': traceId, }); ``` **Note**: If both formats are provided, `client_request_id` takes priority (JavaScript/TypeScript convention). ### Supported Operations All API methods that extend `GrpcTimeOut` support trace IDs: ```javascript // Insert with trace ID await client.insert({ collection_name: 'my_collection', data: [{ id: 1, vector: [0.1, 0.2, 0.3] }], client_request_id: 'insert-trace-123', }); // Search with trace ID await client.search({ collection_name: 'my_collection', vector: [0.1, 0.2, 0.3], limit: 10, client_request_id: 'search-trace-456', }); // Query with trace ID await client.query({ collection_name: 'my_collection', expr: 'id > 100', client_request_id: 'query-trace-789', }); // All other operations support trace IDs await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'IVF_FLAT', client_request_id: 'index-trace-101', }); ``` ### Use Cases 1. **Request Tracking**: Track requests across distributed systems 2. **Debugging**: Identify specific requests in logs 3. **Performance Monitoring**: Correlate trace IDs with performance metrics 4. **Error Investigation**: Trace errors back to specific requests ### Implementation Details - Trace IDs are passed through gRPC metadata - Both `client_request_id` and `client-request-id` formats are supported - Trace IDs are automatically extracted from request parameters - The timestamp `client-request-unixmsec` is automatically added by the interceptor - No need to modify API method implementations ## Iterator Patterns ### Query Iterator Iterate through large query results: ```javascript const iterator = await client.queryIterator({ collection_name: 'my_collection', expr: 'age > 25', output_fields: ['id', 'text'], batchSize: 100, }); while (true) { const batch = await iterator.next(); if (batch.done) break; console.log('Batch:', batch.value); } ``` ### Search Iterator Iterate through large search results: ```javascript const iterator = await client.searchIterator({ collection_name: 'my_collection', data: [[0.1, 0.2, 0.3, 0.4]], limit: 10000, batchSize: 100, }); while (true) { const batch = await iterator.next(); if (batch.done) break; console.log('Batch:', batch.value); } ``` ## Sparse Vectors Work with sparse vector data: ```javascript // Array format const sparseVector = [1.0, undefined, undefined, 2.5, undefined]; // Dictionary format const sparseVector = { 0: 1.0, 3: 2.5 }; // CSR format const sparseVector = { indices: [0, 3], values: [1.0, 2.5], }; // COO format const sparseVector = [ { index: 0, value: 1.0 }, { index: 3, value: 2.5 }, ]; await client.insert({ collection_name: 'my_collection', data: [ { sparse_vector: sparseVector, }, ], }); ``` ## Binary Vectors Work with binary vector data: ```javascript // Binary vector: length must be dim / 8 const binaryVector = [1, 0, 1, 0, 1, 0, 1, 0]; // For dim=64 await client.insert({ collection_name: 'my_collection', data: [ { binary_vector: binaryVector, }, ], }); ``` ## Float16/BFloat16 Vectors Use transformers for Float16 and BFloat16 vectors: ```javascript import { DataType, f32ArrayToF16Bytes } from '@zilliz/milvus2-sdk-node'; await client.insert({ collection_name: 'my_collection', data: [ { vector: [0.1, 0.2, 0.3, 0.4], // f32 array }, ], transformers: { [DataType.Float16Vector]: f32ArrayToF16Bytes, }, }); ``` ## Dynamic Fields Enable dynamic fields for flexible schemas: ```javascript // Create collection with dynamic fields await client.createCollection({ collection_name: 'my_collection', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'vector', data_type: DataType.FloatVector, dim: 128, }, ], enable_dynamic_field: true, }); // Insert data with dynamic fields await client.insert({ collection_name: 'my_collection', data: [ { vector: [ /* ... */ ], dynamic_field_1: 'value1', // Automatically added dynamic_field_2: 123, // Automatically added }, ], }); ``` ## Performance Monitoring ### Get Metrics Get system metrics: ```javascript const metrics = await client.getMetric({ request: { metric_type: 'system_info', }, }); console.log('Metrics:', metrics); ``` ## Replica Management ### Get Replicas Get replica information: ```javascript const { collectionID } = await client.describeCollection({ collection_name: 'my_collection', }); const replicas = await client.getReplicas({ collectionID }); console.log('Replicas:', replicas.replicas); ``` ## Best Practices 1. **Connection pooling**: Configure appropriate pool sizes 2. **Retry configuration**: Set reasonable retry limits 3. **Error handling**: Always handle errors appropriately 4. **Logging**: Use appropriate log levels for your environment 5. **Iterators**: Use iterators for large result sets 6. **Monitoring**: Monitor metrics for performance optimization ## Next Steps - Learn about [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) - Explore [HTTP Client](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/) - Check out [Examples & Tutorials](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/) --- # Use the HttpClient for Milvus REST Requests Choose the REST-based HttpClient for HTTP-only and serverless runtimes. Connect to Milvus, configure timeouts, and handle HTTP errors. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/ ## Section links - [HttpClient vs MilvusClient](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/#httpclient-vs-milvusclient) - [Creating HTTP Client](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/#creating-http-client) - [Using HTTP Client in Serverless Environments](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/#using-http-client-in-serverless-environments) - [HTTP Client Configuration](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/#http-client-configuration) - [Error Handling](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/#error-handling) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/#best-practices) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/#next-steps) - [Operation shortcuts](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/#operation-shortcuts) Use `HttpClient` to call Milvus REST v2 from runtimes with Fetch support, including HTTP-only edge and serverless platforms. Choose `MilvusClient` when your runtime supports gRPC and you need the SDK’s streaming or gRPC administration APIs. ## HttpClient vs MilvusClient | Decision | MilvusClient (gRPC) | HttpClient (REST) | | --- | --- | --- | | Protocol | gRPC over HTTP/2 | Milvus REST v2 over HTTP with JSON | | Request field casing | snake_case, such as `collection_name` | camelCase, such as `collectionName` | | Serverless and edge support | Use in Node.js runtimes that support gRPC connections | Use in Fetch-capable runtimes, including HTTP-only serverless and edge environments | | Streaming and gRPC-only admin RPCs | Supports replication and WAL streams, plus proxy and telemetry administration | Supports REST management operations and returns JSON responses | | Response and error handling | Inspect `error_code` on a status or `status.error_code` on a result. Transport failures can reject. | Inspect `code` where the REST response provides it. Non-2xx responses throw `HttpError`. | ## Creating HTTP Client ```ts import { HttpClient } from '@zilliz/milvus2-sdk-node'; const client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT ?? 'http://localhost:19530', token: process.env.MILVUS_TOKEN, }); const { code, data } = await client.listCollections({ dbName: 'default' }); if (code !== 0) throw new Error(`Milvus returned code ${code}`); console.log(data); ``` ## Using HTTP Client in Serverless Environments For edge runtimes without Node.js built-ins, import `HttpClient` from `@zilliz/milvus2-sdk-node/dist/milvus/HttpClient.js`. See the deployment guides for [Cloudflare Workers](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/), [Vercel](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/), and [AWS Lambda](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/). ## HTTP Client Configuration See the [constructor and per-request options](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#constructor) for database defaults, timeouts, and custom Fetch implementations. ## Error Handling Catch [`HttpError`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#errors) for non-2xx HTTP responses. Inspect the Milvus `code` in successful HTTP responses. ## Best Practices Use environment variables for credentials and reuse the client across requests in long-running services. See [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) for deployment advice. ## Next Steps Use the [SDK reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/) to look up TypeScript methods, or use the [REST explorer](https://milvus-io.github.io/milvus-sdk-node/rest-api/) to run a request directly. ## Operation shortcuts - [ Why HTTP Client for Serverless? ](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/#using-http-client-in-serverless-environments) - [ Vercel Example ](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/) - [ Cloudflare Workers Example ](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/) - [ AWS Lambda Example ](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/) - [ Serverless Best Practices ](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/#best-practices) - [ Collection Operations ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#collection-apis) - [ Create Collection ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createcollection) - [ List Collections ](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/list/) - [ Describe Collection ](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/describe/) - [ Drop Collection ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropcollection) - [ Vector Operations ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#data-apis) - [ Insert Vectors ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#insert) - [ Search Vectors ](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/search/) - [ Query Vectors ](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/query/) - [ Delete Vectors ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#delete) - [ Index Operations ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#index-apis) - [ Create Index ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createindex) - [ Describe Index ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describeindex) - [ List Indexes ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listindexes) - [ Drop Index ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropindex) - [ Partition Operations ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#partition-apis) - [ Create Partition ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createpartition) - [ List Partitions ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listpartitions) - [ Drop Partition ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#droppartition) - [ Alias Operations ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alias-apis) - [ Create Alias ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createalias) - [ List Aliases ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listaliases) - [ Drop Alias ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropalias) - [ Import Operations ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#import-apis) - [ Import Data ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createimportjobs) - [ User Operations ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#user-and-role-apis) - [ Create User ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createuser) - [ List Users ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listusers) - [ Role Operations ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#user-and-role-apis) - [ Create Role ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createrole) - [ List Roles ](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listroles) --- # Function Chains Use the Milvus Node.js SDK to apply server-side function chains for score rewriting, hybrid reranking, and query processing. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/function-chains/ ## Section links - [Rerank search results](https://milvus-io.github.io/milvus-sdk-node/advanced/function-chains/#rerank-search-results) - [Fuse hybrid search results](https://milvus-io.github.io/milvus-sdk-node/advanced/function-chains/#fuse-hybrid-search-results) - [Export columns from a query chain](https://milvus-io.github.io/milvus-sdk-node/advanced/function-chains/#export-columns-from-a-query-chain) - [Rerank with XGBoost](https://milvus-io.github.io/milvus-sdk-node/advanced/function-chains/#rerank-with-xgboost) Function chains run ordered processing steps on the Milvus server. Use them to rewrite search scores, fuse hybrid search results, or process query candidates. The gRPC `MilvusClient` accepts a single chain or an ordered array in `function_chains`. ## Rerank search results This example uses a 2-dimensional `embedding` field, a Unix timestamp in `published_at`, and a numeric `popularity` field. Search retrieves up to 100 candidates. The chain computes a freshness score, blends it with the vector score and popularity, and keeps the first 10 rows after sorting. With function chains, `hit.score` always contains the server’s score, even when the collection also has an output field named `score`. ```ts import { col, fn, FunctionChain, FunctionChainStage, } from '@zilliz/milvus2-sdk-node'; const chain = new FunctionChain(FunctionChainStage.L2_RERANK, { name: 'fresh_popular', }) .map( 'freshness', fn.decay(col('published_at'), { function: 'exp', origin: Math.floor(Date.now() / 1000), scale: 86400, }) ) .map( '$score', fn.numCombine([col('$score'), col('freshness'), col('popularity')], { mode: 'weighted', weights: [0.7, 0.2, 0.1], }) ) .map('$score', fn.roundDecimal(col('$score'), { decimal: 4 })) .sort(col('$score'), { tieBreakCol: col('$id') }) .limit(10); const { results } = await client.search({ collection_name: 'articles', anns_field: 'embedding', data: [0.1, 0.2], limit: 100, output_fields: ['id', 'title'], function_chains: chain, }); ``` Top-level `function_chains` is mutually exclusive with `rerank` and `function_score` in search and hybrid search. ## Fuse hybrid search results Put the fusion chain at the top level of `hybridSearch()`. Each ANN request can also specify a chain that runs on its own candidates before fusion. RRF defaults to `k = 60`. `weighted`, `max`, `sum`, and `avg` normalize scores by default. ```ts const fusion = new FunctionChain(FunctionChainStage.L2_RERANK) .merge('rrf') .sort('$score', { tieBreakCol: '$id' }); const { results } = await client.hybridSearch({ collection_name: 'articles', data: [ { anns_field: 'embedding', data: [0.1, 0.2] }, { anns_field: 'title_embedding', data: [0.2, 0.1] }, ], limit: 10, output_fields: ['id', 'title'], function_chains: fusion, }); ``` ## Export columns from a query chain `query()` accepts one `QUERY_SCAN` chain. A named chain can export values through the builder’s `outputColumns` option or the raw spec’s `output_columns` field. The exported columns appear alongside ordinary fields in `response.data`. Use a Milvus server build with QueryScan support. Older servers may ignore the chain. ```ts const response = await client.query({ collection_name: 'articles', limit: 20, output_fields: ['id', 'title'], function_chains: { stage: FunctionChainStage.QUERY_SCAN, name: 'find_timeout', output_columns: ['matches'], ops: [ { op: 'grep', inputs: ['body'], outputs: ['matches'], params: { arguments: { string_value: '-i -e timeout' } }, }, ], }, }); ``` Raw `FunctionChainSpec` objects also let you send server operators and expressions directly. Use protobuf field names and explicit `FunctionParamValue` variants such as `{ double_value: 1 }` or `{ int64_value: '9007199254740993' }`. The builder encodes known floating-point parameters such as weights and decay settings as doubles even when their values are whole numbers. ## Rerank with XGBoost Use an XGBoost-enabled Milvus server. Train or obtain a tree model in UBJ format, upload it to the object-storage bucket Milvus uses, then register the bucket-relative object path as a file resource. Pass feature columns in the same order used during training. With `output: 'raw'`, Milvus uses the model’s raw prediction margin as the score. ```ts await client.addFileResource({ name: 'articles_ranker', path: 'models/articles-ranker.ubj', }); const xgb = new FunctionChain(FunctionChainStage.L0_RERANK).map( '$score', fn.xgboost([col('popularity'), col('click_rate')], { modelResource: 'articles_ranker', output: 'raw', }) ); const { results } = await client.search({ collection_name: 'articles', anns_field: 'embedding', data: [0.1, 0.2], limit: 10, output_fields: ['id', 'popularity', 'click_rate'], function_chains: xgb, }); ``` For an external rerank provider, use `fn.rerankModel(col('body'), { queries: ['example query'], provider, model })` in a `map('$score', ...)` operation. The server handles the inference call using the provider settings you supply. --- # Full-Text Search Build BM25 full-text search in Milvus by configuring an analyzer and a function that turns text into searchable sparse vectors. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/ ## Section links - [How It Works](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#how-it-works) - [Testing Analyzers](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#testing-analyzers) - [Analyzer Types](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#analyzer-types) - [Custom Dictionary Files](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#custom-dictionary-files) - [Creating a Full-Text Search Collection](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#creating-a-full-text-search-collection) - [Adding Functions to Existing Collections](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#adding-functions-to-existing-collections) - [Searching with Full-Text](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#searching-with-full-text) - [Highlighting Search Results](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#highlighting-search-results) - [Lexical Highlighting](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#lexical-highlighting) - [Semantic Highlighting](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#semantic-highlighting) - [Highlight Results](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#highlight-results) - [Managing Collection Functions](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#managing-collection-functions) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#next-steps) Full-text search enables keyword-based text retrieval using BM25 scoring. Milvus supports this through **collection functions** that automatically tokenize text and convert it to sparse vectors at insert and query time. ## How It Works 1. You define a VarChar field for text and a SparseFloatVector field for the generated vectors 2. You add a BM25 function to the collection that maps the text field to the sparse vector field 3. When you insert text, Milvus automatically tokenizes it and generates sparse vectors 4. When you search, you pass text queries and Milvus automatically converts them to sparse vectors for matching ## Testing Analyzers Before creating a collection, you can test how an analyzer tokenizes text using `runAnalyzer()`: ```javascript const result = await client.runAnalyzer({ text: ['machine learning is great', 'deep learning fundamentals'], analyzer_params: { type: 'standard', }, }); console.log('Results:', result.results); // Each text input produces an AnalyzerResult with tokens ``` You can also test analyzers that are configured on a collection field, request detailed token data, and include token hashes: ```javascript const result = await client.runAnalyzer({ db_name: 'default', collection_name: 'articles', field_name: 'body', analyzer_names: ['english_analyzer'], text: ['Running analyzers with offsets and hashes'], with_detail: true, with_hash: true, }); result.results[0].tokens.forEach((token) => { console.log(token.token, token.start_offset, token.end_offset, token.hash); }); ``` `runAnalyzer()` accepts either `analyzer_params` for an ad-hoc analyzer configuration or collection context fields (`db_name`, `collection_name`, `field_name`, `analyzer_names`) to use analyzers defined in a schema. ### Analyzer Types | Type | Description | | --- | --- | | `standard` | Standard tokenizer with lowercase filter | | `english` | English-specific tokenizer with stemming | | `chinese` | Chinese text tokenizer | ### Custom Dictionary Files Milvus 3.0 For analyzers that load a custom dictionary or synonym file, register the server-visible object before referencing it from analyzer parameters: ```javascript await client.addFileResource({ name: 'product_dictionary', path: 'analyzer-resources/product-dictionary.txt', }); const resources = await client.listFileResources(); console.log(resources.resources); ``` The file must already be available through the storage configured for Milvus. `addFileResource()` registers metadata; it does not upload a local Node.js file. Remove the registration when it is no longer used: ```javascript await client.removeFileResource({ name: 'product_dictionary' }); ``` ## Creating a Full-Text Search Collection ```javascript import { MilvusClient, DataType, FunctionType, IndexType, MetricType, ConsistencyLevelEnum, } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530' }); // 1. Create collection with text and sparse vector fields await client.createCollection({ collection_name: 'articles', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'title', data_type: DataType.VarChar, max_length: 256, enable_analyzer: true, analyzer_params: { tokenizer: 'standard', filter: ['lowercase'] }, }, { name: 'body', data_type: DataType.VarChar, max_length: 10000, enable_analyzer: true, analyzer_params: { tokenizer: 'standard', filter: ['lowercase'] }, }, { name: 'sparse_vector', data_type: DataType.SparseFloatVector }, ], functions: [ { name: 'bm25', type: FunctionType.BM25, input_field_names: ['body'], output_field_names: ['sparse_vector'], params: {}, }, ], }); ``` ## Adding Functions to Existing Collections You can add the BM25 output field, function, and bound index to an existing collection in one schema alteration: ```javascript await client.addFunctionField({ collection_name: 'articles', field: { name: 'title_sparse', data_type: DataType.SparseFloatVector, is_function_output: true, }, function: { name: 'title_bm25', type: FunctionType.BM25, input_field_names: ['title'], output_field_names: ['title_sparse'], params: {}, }, index_name: 'title_bm25_index', extra_params: { index_type: IndexType.SPARSE_INVERTED_INDEX, metric_type: MetricType.BM25, }, }); ``` ## Searching with Full-Text Pass a text string as the search data. Milvus uses the BM25 function to convert it to a sparse vector automatically. The example uses Strong consistency and flushes the inserted documents before searching so that the small test dataset is ready for BM25 retrieval. Avoid flushing after every insert in a production ingestion pipeline. ```javascript // Insert documents await client.insert({ collection_name: 'articles', data: [ { title: 'Introduction to Machine Learning', body: 'Machine learning is a branch of AI...', }, { title: 'Deep Learning Basics', body: 'Deep learning uses neural networks...', }, ], }); // Wait for the example documents to be flushed before searching await client.flushSync({ collection_names: ['articles'] }); await client.createIndex({ collection_name: 'articles', field_name: 'sparse_vector', index_type: 'SPARSE_INVERTED_INDEX', metric_type: 'BM25', }); await client.loadCollectionSync({ collection_name: 'articles' }); // Search by text const results = await client.search({ collection_name: 'articles', data: ['machine learning algorithms'], anns_field: 'sparse_vector', metric_type: 'BM25', consistency_level: ConsistencyLevelEnum.Strong, limit: 10, output_fields: ['title', 'body'], }); console.log('Results:', results.results); ``` ## Highlighting Search Results Use the `highlighter` parameter to highlight matched text fragments in search results. ### Lexical Highlighting Highlights keyword matches using the text field’s analyzer. Set `highlight_search_text: true` to highlight the BM25 search terms, and explicitly set `metric_type: 'BM25'` on the search request. Creating a BM25 index alone does not supply this request parameter to the highlighter. In this collection, the BM25 function takes `body` as its input, so search-term highlighting applies to `body`. Including `title` in `output_fields` returns its source text but does not automatically highlight it. ```javascript const results = await client.search({ collection_name: 'articles', data: ['machine learning'], anns_field: 'sparse_vector', metric_type: 'BM25', consistency_level: ConsistencyLevelEnum.Strong, limit: 10, output_fields: ['title', 'body'], highlighter: { type: 0, // HighlightType.Lexical highlight_search_text: true, pre_tags: [''], post_tags: [''], fragment_size: 100, num_of_fragments: 3, }, }); ``` For the first example document, `results.results[0].highlight.body` contains: ```json { "fragments": ["Machine learning is a branch of AI..."], "scores": [] } ``` ### Semantic Highlighting Highlights semantically similar text through a model service. Milvus must have the Zilliz model-service provider endpoint configured on the server, with access to an appropriate highlighting model deployment. The `highlighter` parameter does not configure or start that service. A standalone Milvus instance without this provider configuration returns an error such as `Create SemanticHighlight failed: zilliz client config error, lost endpoint config`. Use the following example only after configuring the service, and replace `YOUR_HIGHLIGHT_MODEL_DEPLOYMENT_ID` with your deployment ID: ```javascript const results = await client.search({ collection_name: 'articles', data: ['machine learning'], anns_field: 'sparse_vector', metric_type: 'BM25', consistency_level: ConsistencyLevelEnum.Strong, limit: 10, output_fields: ['title', 'body'], highlighter: { type: 1, // HighlightType.Semantic model_deployment_id: 'YOUR_HIGHLIGHT_MODEL_DEPLOYMENT_ID', queries: ['machine learning'], input_fields: ['body'], pre_tags: [''], post_tags: [''], threshold: 0.5, }, }); ``` `queries` must contain one string for each search query. Set `highlight_only: true` to request only highlighted fragments from the model service. The source fields requested through `output_fields` are still returned in the search hits. ### Highlight Results Search hits include highlight data for the fields processed by the highlighter. Each highlighted field contains `fragments` and `scores` arrays. Lexical highlighting returns an empty `scores` array; semantic highlighting can return scores from the model service. ```javascript results.results.forEach((hit) => { console.log('Title:', hit.title); console.log('Highlight:', hit.highlight); const bodyHighlight = hit.highlight?.body; bodyHighlight?.fragments.forEach((fragment, index) => { console.log('Fragment:', fragment); const score = bodyHighlight.scores[index]; if (score !== undefined) { console.log('Score:', score); } }); }); ``` ## Managing Collection Functions ```javascript // List functions on a collection const desc = await client.describeCollection({ collection_name: 'articles' }); console.log('Functions:', desc.schema.functions); // Drop the function, output field, and bound index await client.dropFunctionField({ collection_name: 'articles', function_name: 'bm25', }); ``` To change a BM25 function on Milvus 3.0.6, drop it and add the replacement with `addFunctionField()`. ## Next Steps - Learn about [Hybrid Search](https://milvus-io.github.io/milvus-sdk-node/operations/hybrid-search/) for combining full-text with vector search - Explore [Data Types & Schemas](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/) for SparseFloatVector details --- # Bloom and Roaring Membership Filters Encode large membership sets in Node.js with Bloom or Roaring filters and use them in Milvus Query and Search expressions. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/membership-filters/ ## Section links - [Choose a filter](https://milvus-io.github.io/milvus-sdk-node/advanced/membership-filters/#choose-a-filter) - [Exact integer membership](https://milvus-io.github.io/milvus-sdk-node/advanced/membership-filters/#exact-integer-membership) - [Approximate integer or string membership](https://milvus-io.github.io/milvus-sdk-node/advanced/membership-filters/#approximate-integer-or-string-membership) - [Estimate Bloom payload size](https://milvus-io.github.io/milvus-sdk-node/advanced/membership-filters/#estimate-bloom-payload-size) - [Incremental builders](https://milvus-io.github.io/milvus-sdk-node/advanced/membership-filters/#incremental-builders) SDK 3.0.5 exports helpers that encode large membership sets as binary filter parameters for the gRPC client. Your Milvus deployment must support `membership_match` with the corresponding `type=bloom` or `type=roaring`; upgrading the SDK alone does not add these server expressions. ## Choose a filter | Helper | Members | Semantics | | --- | --- | --- | | `buildBloomFilter(members, fpr?)` | All integers (`number`/`bigint`) or all strings | Approximate membership; false positives are possible | | `buildRoaringBitmap(members)` | Signed integers (`number`/`bigint`/decimal `string`) | Exact membership; duplicates collapse | Both return `Uint8Array`. Build once and reuse the blob in `exprValues` for query or search. Pass the bytes directly, without JSON stringification or base64 encoding. Empty sets match nothing. ## Exact integer membership Assume `documents` is loaded and contains an integer `user_id` field: ```typescript import { buildRoaringBitmap } from '@zilliz/milvus2-sdk-node'; const ids = buildRoaringBitmap([1, 2, '9223372036854775807']); const result = await client.query({ collection_name: 'documents', filter: 'membership_match(user_id, {ids}, type=roaring)', exprValues: { ids }, output_fields: ['user_id'], limit: 100, }); console.log(result.data); ``` Numbers must be safe integers. Use `bigint` or decimal strings for larger signed int64 values. Roaring does not support VarChar membership: `'123'` here means integer 123. The builder validates signed int64 range and serialized/decoded size limits; compactness depends on the distribution of IDs. ## Approximate integer or string membership ```typescript import { buildBloomFilter } from '@zilliz/milvus2-sdk-node'; const members = buildBloomFilter(['alice', 'bob'], 0.005); const result = await client.query({ collection_name: 'documents', filter: 'membership_match(owner, {members}, type=bloom)', exprValues: { members }, output_fields: ['owner'], limit: 100, }); ``` The target `owner` field must be VarChar for this string blob. Integer fields require integer members. Use `BigInt('9223372036854775807')` for large Bloom integer members: decimal strings are hashed as UTF-8, not parsed as integers. Mixing strings and integers in `buildBloomFilter` is rejected. The default false-positive rate is `0.005`; accepted values are `0.0001` through `0.05`. A lower rate generally needs a larger blob. Bloom membership is suitable for candidate filtering; verify candidates against the original set when exact inclusion matters. Do not use approximate membership as an authorization check or negate it for exact exclusion. ## Estimate Bloom payload size `estimateBloomFilterSize(n, fpr)` returns the serialized byte length, including the envelope, without building the filter. Both arguments are required. Compare the estimate with your deployment’s Bloom-filter and overall request limits before allocating a large set. ```typescript import { estimateBloomFilterSize, BLOOM_FILTER_DEFAULT_FPR, } from '@zilliz/milvus2-sdk-node'; console.log(estimateBloomFilterSize(100_000, BLOOM_FILTER_DEFAULT_FPR)); ``` The package also exports `BLOOM_FILTER_MIN_FPR` and `BLOOM_FILTER_MAX_FPR` for input validation. ## Incremental builders `BloomFilterBuilder` accepts an expected member count and optional false-positive rate. Add members with `addInt64()` or `addString()`, then call `build()`. Its returned bytes share the builder’s buffer; copy them before adding more members if you need an immutable snapshot. `RoaringBitmapBuilder` accepts `add()` and `addMany()` before `build()`. It retains the members for sorting and deduplication, so incremental input still requires memory proportional to the membership set. ```typescript import { BloomFilterBuilder, RoaringBitmapBuilder, } from '@zilliz/milvus2-sdk-node'; const bloom = new BloomFilterBuilder(2).addInt64(1).addInt64(2).build(); const roaring = new RoaringBitmapBuilder().addMany([1, 2]).build(); ``` See [Query & Search](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/) for combining these predicates with other filters. --- # Client Telemetry Configure or disable gRPC MilvusClient heartbeat telemetry and inspect the operation metrics the Node.js SDK collects. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/client-telemetry/ ## Section links - [Configuration and defaults](https://milvus-io.github.io/milvus-sdk-node/advanced/client-telemetry/#configuration-and-defaults) - [Collected information](https://milvus-io.github.io/milvus-sdk-node/advanced/client-telemetry/#collected-information) - [Inspection and server compatibility](https://milvus-io.github.io/milvus-sdk-node/advanced/client-telemetry/#inspection-and-server-compatibility) SDK 3.0.5 adds client telemetry to `MilvusClient` (gRPC). It sends operation metrics to the connected Milvus deployment through `ClientHeartbeat`. This is separate from OpenTelemetry tracing configured with `trace`. ## Configuration and defaults ```typescript import { MilvusClient } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'localhost:19530', telemetry: { enabled: true, heartbeatIntervalMs: 10_000, samplingRate: 1, errorMaxCount: 100, // clientId: 'recommendation-worker-1', }, }); await client.connectPromise; console.log(client.getTelemetry().getConfig()); // Call during application shutdown to stop telemetry and close channels. await client.closeConnection(); ``` | Option | Default | Meaning | | --- | --- | --- | | `enabled` | `true` | Enable metric collection and start heartbeats | | `heartbeatIntervalMs` | `10000` | Positive finite heartbeat interval, in milliseconds | | `samplingRate` | `1` | Fraction of logical operations sampled; finite numbers are clamped to 0–1 | | `errorMaxCount` | `100` | Positive integer cap on retained errors | | `clientId` | Generated UUID | Optional stable identity across process restarts; use a distinct identity per client | Disable telemetry at construction if you do not want it to start: ```typescript const client = new MilvusClient({ address: 'localhost:19530', telemetry: { enabled: false }, }); ``` ## Collected information Telemetry records request, success and error counts, plus average, p99 and maximum latency for supported data operations. High-level operations include their retries in a single logical operation; iterator setup and batches are excluded. Sampling reduces recorded operations rather than extrapolating counts to all requests. Heartbeats include SDK version, client identity, hostname, user and database context. The server can request collection metrics, recent errors and latency history, inspect configuration, and push changes to enabled state, heartbeat interval or sampling rate. Error details can include operation, collection, request ID and error text. Server-pushed disabling of collection keeps the heartbeat control channel active, so it differs from `enabled: false` at construction. Metrics arrive in windows and are not an instantaneous view of requests. ## Inspection and server compatibility `client.getTelemetry()` returns the public `ClientTelemetryManager`. Use `getConfig()` for effective settings and `getMetricsSnapshots()` for retained snapshots. Advanced integrations can register a command handler with `registerCommandHandler(type, handler)`; handlers return a `CommandReply` or a promise of one. Servers without `ClientHeartbeat` return `UNIMPLEMENTED`. The SDK backs off retries, up to 30 minutes, without blocking ordinary data operations. Transport failures also use heartbeat backoff. Call `closeConnection()` during shutdown to stop timers and release channels. --- # Global Cluster Connect the Milvus Node.js SDK to a multi-region deployment and configure topology discovery, routing, and failover. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/global-cluster/ ## Section links - [Enabling Global Cluster Mode](https://milvus-io.github.io/milvus-sdk-node/advanced/global-cluster/#enabling-global-cluster-mode) - [Auto-Detection](https://milvus-io.github.io/milvus-sdk-node/advanced/global-cluster/#auto-detection) - [How It Works](https://milvus-io.github.io/milvus-sdk-node/advanced/global-cluster/#how-it-works) - [Manual Primary Reconnection](https://milvus-io.github.io/milvus-sdk-node/advanced/global-cluster/#manual-primary-reconnection) - [Cluster-pinned DQL Sessions](https://milvus-io.github.io/milvus-sdk-node/advanced/global-cluster/#cluster-pinned-dql-sessions) - [Configuration](https://milvus-io.github.io/milvus-sdk-node/advanced/global-cluster/#configuration) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/advanced/global-cluster/#next-steps) Global cluster mode enables multi-region Milvus deployments with automatic failover. The SDK fetches cluster topology from the endpoint and routes requests to the primary cluster. ## Enabling Global Cluster Mode Set `isGlobal: true` in the client configuration: ```javascript import { MilvusClient } from '@zilliz/milvus2-sdk-node'; const client = new MilvusClient({ address: 'your-global-endpoint:19530', isGlobal: true, token: 'your-token', }); ``` ### Auto-Detection When `isGlobal` is not explicitly set, the SDK auto-detects global cluster mode by checking if the address URI contains `global-cluster`. You can override this by explicitly setting `isGlobal: true` or `isGlobal: false`. ## How It Works When global cluster mode is enabled: 1. **Connection:** The SDK connects to the provided endpoint and queries the cluster topology 2. **Routing:** Requests are routed to the primary cluster automatically 3. **Failover:** If the primary cluster becomes unavailable, the SDK can reconnect to a new primary ## Manual Primary Reconnection Use `reconnectToPrimary()` to manually trigger a reconnection to the current primary cluster: ```javascript const changed = await client.reconnectToPrimary(); if (changed) { console.log('Reconnected to new primary cluster'); } else { console.log('Primary unchanged, no reconnection needed'); } ``` This method: - Queries the endpoint for the current primary cluster - If the primary has changed, creates a new connection pool for the new primary - Drains the old connection pool gracefully - Returns `true` if a reconnection occurred, `false` if the primary is unchanged ## Cluster-pinned DQL Sessions Use `session(clusterId)` when you need search/query/get requests to target a specific cluster explicitly. The session reuses the parent client’s connection and only injects `cluster_id`; it does not create or close a separate connection pool. ```javascript const session = client.session('cluster-a'); const results = await session.search({ collection_name: 'my_collection', data: [[0.1, 0.2, 0.3, 0.4]], anns_field: 'vector', limit: 10, }); session.close(); ``` Supported session methods are `search()`, `hybridSearch()`, `searchIterator()`, `query()`, `queryIterator()`, `get()`, and `close()`. ## Configuration | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `isGlobal` | `boolean` | Auto-detected | Enable/disable global cluster mode | | `address` | `string` | Required | Global cluster endpoint address | | `token` | `string` | - | Authentication token | ## Next Steps - Learn about [Client Configuration](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/) for all connection options - Explore [Advanced Features](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/) for connection pooling and retries --- # Deploying to Cloudflare Workers Use the Milvus HttpClient in Cloudflare Workers with the Fetch API and store connection credentials as Worker secrets. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/ ## Section links - [Why HTTP Client for Cloudflare Workers?](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#why-http-client-for-cloudflare-workers) - [Prerequisites](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#prerequisites) - [Installation](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#installation) - [Basic Setup](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#basic-setup) - [1. Create Worker File](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#1-create-worker-file) - [2. Configure Wrangler](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#2-configure-wrangler) - [3. Set Secrets (Production)](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#3-set-secrets-production) - [Advanced Example: Client Reuse](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#advanced-example-client-reuse) - [Complete Example: Vector Search API](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#complete-example-vector-search-api) - [Deployment](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#deployment) - [Deploy to Cloudflare Workers](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#deploy-to-cloudflare-workers) - [Test Locally](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#test-locally) - [Timeout Limits](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#timeout-limits) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#best-practices) - [Troubleshooting](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#troubleshooting) - [Error: “gRPC is not supported”](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#error-grpc-is-not-supported) - [Error: “Request timeout”](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#error-request-timeout) - [Error: “Module not found”](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#error-module-not-found) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/#next-steps) This guide covers deploying the Milvus Node.js SDK to Cloudflare Workers using the HTTP client. ## Why HTTP Client for Cloudflare Workers? Cloudflare Workers only support HTTP/HTTPS protocols and do not support raw TCP connections required by gRPC. Therefore, you **must** use the `HttpClient` when deploying to Cloudflare Workers. ## Prerequisites - A Cloudflare account - Wrangler CLI installed: `npm install -g wrangler` - A Milvus instance (self-hosted or Zilliz Cloud) ## Installation Install the SDK in your Cloudflare Workers project: ```bash npm install @zilliz/milvus2-sdk-node # or yarn add @zilliz/milvus2-sdk-node ``` ## Basic Setup ### 1. Create Worker File Create `src/index.js` (or `worker.js`). Import the HTTP client directly so Wrangler can bundle it without the Node.js modules used by gRPC and BulkWriter. ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node/dist/milvus/HttpClient.js'; export default { async fetch(request, env, ctx) { const client = new HttpClient({ endpoint: env.MILVUS_ENDPOINT, token: env.MILVUS_TOKEN, timeout: 25000, // Cloudflare Workers free tier: 30s, paid: up to 15min }); try { const url = new URL(request.url); const path = url.pathname; // Handle different endpoints if (path === '/search' && request.method === 'POST') { const body = await request.json(); const results = await client.search({ collectionName: body.collectionName || 'my_collection', data: body.vectors, limit: body.limit || 10, outputFields: body.outputFields || [], }); return new Response(JSON.stringify({ results }), { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, }); } if (path === '/insert' && request.method === 'POST') { const body = await request.json(); const result = await client.insert({ collectionName: body.collectionName || 'my_collection', data: body.data, }); return new Response(JSON.stringify({ result }), { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, }); } return new Response('Not Found', { status: 404 }); } catch (error) { console.error('Milvus error:', error); return new Response( JSON.stringify({ error: error.message, status: error.status || 500, }), { status: error.status || 500, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, } ); } }, }; ``` ### 2. Configure Wrangler Create `wrangler.toml`: ```toml name = "milvus-worker" main = "src/index.js" compatibility_date = "2024-01-01" # Environment variables (use secrets for production) [vars] # MILVUS_ENDPOINT = "https://your-instance.zillizcloud.com" # MILVUS_TOKEN = "your-token" # For production, use secrets instead: # wrangler secret put MILVUS_ENDPOINT # wrangler secret put MILVUS_TOKEN # Worker limits [limits] cpu_ms = 50 # CPU time limit in milliseconds ``` ### 3. Set Secrets (Production) For production, use Wrangler secrets instead of environment variables: ```bash wrangler secret put MILVUS_ENDPOINT # Enter: https://your-instance.zillizcloud.com wrangler secret put MILVUS_TOKEN # Enter: your-api-token ``` ## Advanced Example: Client Reuse For better performance, reuse the client instance within the same request context: ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node/dist/milvus/HttpClient.js'; let clientCache = null; function getClient(env) { if (!clientCache) { clientCache = new HttpClient({ endpoint: env.MILVUS_ENDPOINT, token: env.MILVUS_TOKEN, timeout: 25000, }); } return clientCache; } export default { async fetch(request, env, ctx) { const client = getClient(env); // ... rest of your code }, }; ``` ## Complete Example: Vector Search API Here’s a complete example for a vector search API: ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node/dist/milvus/HttpClient.js'; export default { async fetch(request, env) { // Handle CORS preflight if (request.method === 'OPTIONS') { return new Response(null, { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type', }, }); } const client = new HttpClient({ endpoint: env.MILVUS_ENDPOINT, token: env.MILVUS_TOKEN, timeout: 25000, }); try { const url = new URL(request.url); if (url.pathname === '/api/search' && request.method === 'POST') { const body = await request.json(); if (!body.vector || !body.collectionName) { return new Response( JSON.stringify({ error: 'Missing required fields' }), { status: 400, headers: { 'Content-Type': 'application/json' }, } ); } const results = await client.search({ collectionName: body.collectionName, data: [body.vector], limit: body.limit || 10, outputFields: body.outputFields || [], searchParams: body.searchParams || {}, }); return new Response(JSON.stringify({ results }), { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, }); } return new Response('Not Found', { status: 404 }); } catch (error) { console.error('Error:', error); return new Response( JSON.stringify({ error: error.message, status: error.status || 500, }), { status: error.status || 500, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, } ); } }, }; ``` ## Deployment ### Deploy to Cloudflare Workers ```bash # Login to Cloudflare wrangler login # Deploy wrangler deploy # Deploy to a specific environment wrangler deploy --env production ``` ### Test Locally ```bash # Start local development server wrangler dev # Test with curl curl -X POST http://localhost:8787/api/search \ -H "Content-Type: application/json" \ -d '{ "collectionName": "my_collection", "vector": [0.1, 0.2, 0.3], "limit": 5 }' ``` ## Timeout Limits - **Free tier**: 30 seconds CPU time, 30 seconds wall-clock time - **Paid tier**: Up to 15 minutes CPU time, 30 seconds wall-clock time (can be extended) Set your timeout accordingly: ```javascript const client = new HttpClient({ endpoint: env.MILVUS_ENDPOINT, token: env.MILVUS_TOKEN, timeout: 25000, // Leave buffer for Worker overhead }); ``` ## Best Practices 1. **Use HTTP Client**: Cloudflare Workers only support HTTP/HTTPS, not gRPC 2. **Set appropriate timeouts**: Account for Worker execution limits 3. **Handle errors gracefully**: Return proper HTTP status codes 4. **Use secrets for credentials**: Never commit tokens to your repository 5. **Enable CORS**: If calling from browser, set appropriate CORS headers 6. **Client reuse**: Reuse client instances within the same request context 7. **Monitor performance**: Use Cloudflare Analytics to track execution times ## Troubleshooting ### Error: “gRPC is not supported” **Solution**: Use `HttpClient` instead of `MilvusClient`. ### Error: “Request timeout” **Solution**: - Reduce timeout value to leave buffer for Worker overhead - Optimize your Milvus queries - Consider upgrading to paid tier for longer execution times ### Error: “Module not found” **Solution**: Ensure `@zilliz/milvus2-sdk-node` is installed and listed in `package.json`. ## Next Steps - Learn about [Vercel Deployment](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/) - Explore [AWS Lambda Deployment](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/) - Check out [HTTP Client Guide](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/) - Read [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) --- # Deploying to Vercel Connect a Vercel serverless function to Milvus using the Node.js HttpClient and configure the deployment endpoint and credentials. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/ ## Section links - [Why HTTP Client for Vercel?](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#why-http-client-for-vercel) - [Prerequisites](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#prerequisites) - [Installation](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#installation) - [Basic Setup](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#basic-setup) - [1. Create API Route](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#1-create-api-route) - [2. Configure Vercel](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#2-configure-vercel) - [3. Set Environment Variables](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#3-set-environment-variables) - [Next.js App Router Example](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#nextjs-app-router-example) - [Complete Example: Multiple Endpoints](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#complete-example-multiple-endpoints) - [`api/search.js`](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#apisearchjs) - [`api/insert.js`](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#apiinsertjs) - [`api/query.js`](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#apiqueryjs) - [Deployment](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#deployment) - [Deploy to Vercel](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#deploy-to-vercel) - [Test Locally](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#test-locally) - [Timeout Limits](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#timeout-limits) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#best-practices) - [Troubleshooting](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#troubleshooting) - [Error: “Function execution timeout”](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#error-function-execution-timeout) - [Error: “Module not found”](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#error-module-not-found) - [Error: “Environment variable not found”](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#error-environment-variable-not-found) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/#next-steps) This guide covers deploying the Milvus Node.js SDK to Vercel serverless functions using the HTTP client. ## Why HTTP Client for Vercel? While Vercel supports both gRPC and HTTP, the HTTP client is recommended for serverless functions because: - **Better cold start performance**: No connection setup overhead - **Stateless design**: Perfect for serverless functions - **Simpler error handling**: Standard HTTP status codes - **Universal compatibility**: Works with all Vercel deployment types ## Prerequisites - A Vercel account - Vercel CLI installed: `npm install -g vercel` - A Milvus instance (self-hosted or Zilliz Cloud) ## Installation Install the SDK in your project: ```bash npm install @zilliz/milvus2-sdk-node # or yarn add @zilliz/milvus2-sdk-node ``` ## Basic Setup ### 1. Create API Route Create `api/search.js` (or `pages/api/search.js` for Next.js Pages Router): ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node'; let client; function getClient() { if (!client) { client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 10000, // Vercel Hobby: 10s, Pro: 60s }); } return client; } export default async function handler(req, res) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } try { const milvusClient = getClient(); const { collectionName, vector, limit = 10, outputFields = [] } = req.body; if (!collectionName || !vector) { return res.status(400).json({ error: 'Missing required fields: collectionName and vector', }); } const results = await milvusClient.search({ collectionName, data: Array.isArray(vector[0]) ? vector : [vector], limit, outputFields, }); res.status(200).json({ results }); } catch (error) { console.error('Milvus error:', error); res.status(error.status || 500).json({ error: error.message, status: error.status || 500, }); } } ``` ### 2. Configure Vercel Create `vercel.json`: ```json { "functions": { "api/search.js": { "maxDuration": 30 }, "api/insert.js": { "maxDuration": 30 } }, "env": { "MILVUS_ENDPOINT": "https://your-instance.zillizcloud.com", "MILVUS_TOKEN": "your-token" } } ``` ### 3. Set Environment Variables For production, set environment variables in Vercel dashboard: 1. Go to your project settings 2. Navigate to “Environment Variables” 3. Add: - `MILVUS_ENDPOINT`: Your Milvus endpoint URL - `MILVUS_TOKEN`: Your Milvus API token Or use Vercel CLI: ```bash vercel env add MILVUS_ENDPOINT vercel env add MILVUS_TOKEN ``` ## Next.js App Router Example For Next.js 13+ App Router, create `app/api/search/route.js`: ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node'; import { NextResponse } from 'next/server'; let client; function getClient() { if (!client) { client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 10000, }); } return client; } export async function POST(request) { try { const body = await request.json(); const { collectionName, vector, limit = 10, outputFields = [] } = body; if (!collectionName || !vector) { return NextResponse.json( { error: 'Missing required fields: collectionName and vector' }, { status: 400 } ); } const milvusClient = getClient(); const results = await milvusClient.search({ collectionName, data: Array.isArray(vector[0]) ? vector : [vector], limit, outputFields, }); return NextResponse.json({ results }); } catch (error) { console.error('Milvus error:', error); return NextResponse.json( { error: error.message, status: error.status || 500 }, { status: error.status || 500 } ); } } ``` ## Complete Example: Multiple Endpoints Create multiple API routes for different operations: ### `api/search.js` ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node'; let client; function getClient() { if (!client) { client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 10000, }); } return client; } export default async function handler(req, res) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } try { const milvusClient = getClient(); const { collectionName, vectors, limit = 10, outputFields = [] } = req.body; const results = await milvusClient.search({ collectionName, data: vectors, limit, outputFields, }); res.status(200).json({ results }); } catch (error) { res.status(error.status || 500).json({ error: error.message }); } } ``` ### `api/insert.js` ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node'; let client; function getClient() { if (!client) { client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 10000, }); } return client; } export default async function handler(req, res) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } try { const milvusClient = getClient(); const { collectionName, data } = req.body; const result = await milvusClient.insert({ collectionName, data, }); res.status(200).json({ result }); } catch (error) { res.status(error.status || 500).json({ error: error.message }); } } ``` ### `api/query.js` ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node'; let client; function getClient() { if (!client) { client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 10000, }); } return client; } export default async function handler(req, res) { if (req.method !== 'POST') { return res.status(405).json({ error: 'Method not allowed' }); } try { const milvusClient = getClient(); const { collectionName, filter, outputFields = [] } = req.body; const results = await milvusClient.query({ collectionName, filter, outputFields, }); res.status(200).json({ results }); } catch (error) { res.status(error.status || 500).json({ error: error.message }); } } ``` ## Deployment ### Deploy to Vercel ```bash # Login to Vercel vercel login # Deploy vercel # Deploy to production vercel --prod ``` ### Test Locally ```bash # Start development server vercel dev # Test with curl curl -X POST http://localhost:3000/api/search \ -H "Content-Type: application/json" \ -d '{ "collectionName": "my_collection", "vectors": [[0.1, 0.2, 0.3]], "limit": 5 }' ``` ## Timeout Limits - **Hobby (Free)**: 10 seconds - **Pro**: 60 seconds - **Enterprise**: Up to 5 minutes (configurable) Configure in `vercel.json`: ```json { "functions": { "api/search.js": { "maxDuration": 30 } } } ``` ## Best Practices 1. **Client reuse**: Reuse client instances using module-level variables 2. **Set appropriate timeouts**: Account for Vercel’s execution limits 3. **Error handling**: Always wrap operations in try-catch blocks 4. **Environment variables**: Use Vercel’s environment variable management 5. **CORS**: Configure CORS if calling from browser 6. **Monitoring**: Use Vercel Analytics to track function performance 7. **Cold starts**: HTTP client reduces cold start impact compared to gRPC ## Troubleshooting ### Error: “Function execution timeout” **Solution**: - Reduce timeout value in HttpClient configuration - Optimize your Milvus queries - Upgrade to Pro plan for longer execution times ### Error: “Module not found” **Solution**: Ensure `@zilliz/milvus2-sdk-node` is installed and listed in `package.json`. ### Error: “Environment variable not found” **Solution**: - Set environment variables in Vercel dashboard - Or use `vercel env add` command - Ensure variables are set for correct environments (development, preview, production) ## Next Steps - Learn about [Cloudflare Workers Deployment](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/) - Explore [AWS Lambda Deployment](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/) - Check out [HTTP Client Guide](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/) - Read [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) --- # Deploying to AWS Lambda Connect AWS Lambda functions to Milvus with the Node.js HttpClient and reuse the client across warm invocations. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/ ## Section links - [Why HTTP Client for AWS Lambda?](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#why-http-client-for-aws-lambda) - [Prerequisites](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#prerequisites) - [Installation](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#installation) - [Basic Setup](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#basic-setup) - [1. Create Lambda Function](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#1-create-lambda-function) - [2. Package Configuration](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#2-package-configuration) - [3. Deploy with AWS CLI](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#3-deploy-with-aws-cli) - [4. Update Environment Variables](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#4-update-environment-variables) - [API Gateway Integration](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#api-gateway-integration) - [Create API Gateway](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#create-api-gateway) - [Complete Example: Multiple Operations](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#complete-example-multiple-operations) - [`index.js`](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#indexjs) - [Using AWS SAM](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#using-aws-sam) - [`template.yaml`](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#templateyaml) - [Deploy with SAM](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#deploy-with-sam) - [Using Serverless Framework](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#using-serverless-framework) - [`serverless.yml`](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#serverlessyml) - [Deploy with Serverless](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#deploy-with-serverless) - [Timeout Configuration](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#timeout-configuration) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#best-practices) - [Using AWS Secrets Manager](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#using-aws-secrets-manager) - [Troubleshooting](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#troubleshooting) - [Error: “Task timed out”](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#error-task-timed-out) - [Error: “Out of memory”](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#error-out-of-memory) - [Error: “Module not found”](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#error-module-not-found) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/advanced/aws-lambda/#next-steps) This guide covers deploying the Milvus Node.js SDK to AWS Lambda using the HTTP client. ## Why HTTP Client for AWS Lambda? While AWS Lambda supports both gRPC and HTTP, the HTTP client is recommended for Lambda functions because: - **Better cold start performance**: No connection setup overhead - **Stateless design**: Perfect for Lambda’s execution model - **Simpler error handling**: Standard HTTP status codes - **Resource efficiency**: Lower memory footprint ## Prerequisites - An AWS account - AWS CLI installed and configured - A Milvus instance (self-hosted or Zilliz Cloud) ## Installation Install the SDK in your Lambda project: ```bash npm install @zilliz/milvus2-sdk-node # or yarn add @zilliz/milvus2-sdk-node ``` ## Basic Setup ### 1. Create Lambda Function Create `index.js`: ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node'; let client; function getClient() { if (!client) { client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 25000, // Leave buffer for Lambda timeout }); } return client; } export const handler = async (event) => { try { const milvusClient = getClient(); const { collectionName, vector, limit = 10, outputFields = [], } = JSON.parse(event.body || '{}'); if (!collectionName || !vector) { return { statusCode: 400, body: JSON.stringify({ error: 'Missing required fields: collectionName and vector', }), }; } const results = await milvusClient.search({ collectionName, data: Array.isArray(vector[0]) ? vector : [vector], limit, outputFields, }); return { statusCode: 200, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify({ results }), }; } catch (error) { console.error('Milvus error:', error); return { statusCode: error.status || 500, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify({ error: error.message, status: error.status || 500, }), }; } }; ``` ### 2. Package Configuration Create `package.json`: ```json { "name": "milvus-lambda", "version": "1.0.0", "type": "module", "main": "index.js", "dependencies": { "@zilliz/milvus2-sdk-node": "^2.0.0" } } ``` ### 3. Deploy with AWS CLI ```bash # Install dependencies npm install # Create deployment package zip -r function.zip . -x "*.git*" "*.zip" # Create Lambda function aws lambda create-function \ --function-name milvus-search \ --runtime nodejs20.x \ --role arn:aws:iam::YOUR_ACCOUNT_ID:role/lambda-execution-role \ --handler index.handler \ --zip-file fileb://function.zip \ --timeout 30 \ --memory-size 512 \ --environment Variables="{ MILVUS_ENDPOINT=https://your-instance.zillizcloud.com, MILVUS_TOKEN=your-token }" ``` ### 4. Update Environment Variables ```bash aws lambda update-function-configuration \ --function-name milvus-search \ --environment Variables="{ MILVUS_ENDPOINT=https://your-instance.zillizcloud.com, MILVUS_TOKEN=your-token }" ``` ## API Gateway Integration ### Create API Gateway ```bash # Create REST API aws apigatewayv2 create-api \ --name milvus-api \ --protocol-type HTTP \ --cors-configuration AllowOrigins="*",AllowMethods="GET,POST,OPTIONS",AllowHeaders="content-type" # Create integration aws apigatewayv2 create-integration \ --api-id YOUR_API_ID \ --integration-type AWS_PROXY \ --integration-uri arn:aws:lambda:REGION:ACCOUNT_ID:function:milvus-search # Create route aws apigatewayv2 create-route \ --api-id YOUR_API_ID \ --route-key "POST /search" \ --target integrations/YOUR_INTEGRATION_ID ``` ## Complete Example: Multiple Operations ### `index.js` ```javascript import { HttpClient } from '@zilliz/milvus2-sdk-node'; let client; function getClient() { if (!client) { client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 25000, }); } return client; } export const handler = async (event) => { const milvusClient = getClient(); const { httpMethod, path, body } = event; const parsedBody = body ? JSON.parse(body) : {}; try { // Search endpoint if (path === '/search' && httpMethod === 'POST') { const { collectionName, vectors, limit = 10, outputFields = [], } = parsedBody; const results = await milvusClient.search({ collectionName, data: vectors, limit, outputFields, }); return { statusCode: 200, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify({ results }), }; } // Insert endpoint if (path === '/insert' && httpMethod === 'POST') { const { collectionName, data } = parsedBody; const result = await milvusClient.insert({ collectionName, data, }); return { statusCode: 200, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify({ result }), }; } // Query endpoint if (path === '/query' && httpMethod === 'POST') { const { collectionName, filter, outputFields = [] } = parsedBody; const results = await milvusClient.query({ collectionName, filter, outputFields, }); return { statusCode: 200, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify({ results }), }; } return { statusCode: 404, body: JSON.stringify({ error: 'Not Found' }), }; } catch (error) { console.error('Error:', error); return { statusCode: error.status || 500, headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', }, body: JSON.stringify({ error: error.message, status: error.status || 500, }), }; } }; ``` ## Using AWS SAM ### `template.yaml` ```yaml AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Resources: MilvusSearchFunction: Type: AWS::Serverless::Function Properties: CodeUri: ./ Handler: index.handler Runtime: nodejs20.x Timeout: 30 MemorySize: 512 Environment: Variables: MILVUS_ENDPOINT: !Ref MilvusEndpoint MILVUS_TOKEN: !Ref MilvusToken Events: SearchApi: Type: Api Properties: Path: /search Method: post InsertApi: Type: Api Properties: Path: /insert Method: post Parameters: MilvusEndpoint: Type: String Description: Milvus endpoint URL MilvusToken: Type: String NoEcho: true Description: Milvus API token ``` ### Deploy with SAM ```bash # Build sam build # Deploy sam deploy --guided ``` ## Using Serverless Framework ### `serverless.yml` ```yaml service: milvus-lambda provider: name: aws runtime: nodejs20.x region: us-east-1 timeout: 30 memorySize: 512 environment: MILVUS_ENDPOINT: ${env:MILVUS_ENDPOINT} MILVUS_TOKEN: ${env:MILVUS_TOKEN} functions: search: handler: index.handler events: - http: path: search method: post cors: true insert: handler: index.handler events: - http: path: insert method: post cors: true plugins: - serverless-offline ``` ### Deploy with Serverless ```bash # Install Serverless Framework npm install -g serverless # Deploy serverless deploy ``` ## Timeout Configuration AWS Lambda supports up to 15 minutes timeout. Configure appropriately: ```javascript const client = new HttpClient({ endpoint: process.env.MILVUS_ENDPOINT, token: process.env.MILVUS_TOKEN, timeout: 25000, // Leave buffer for Lambda overhead }); ``` Set Lambda timeout: ```bash aws lambda update-function-configuration \ --function-name milvus-search \ --timeout 30 ``` ## Best Practices 1. **Client reuse**: Reuse client instances using module-level variables (Lambda reuses execution context) 2. **Set appropriate timeouts**: Account for Lambda’s execution limits 3. **Error handling**: Always wrap operations in try-catch blocks 4. **Environment variables**: Use AWS Systems Manager Parameter Store or Secrets Manager for sensitive data 5. **CORS**: Configure CORS if calling from browser 6. **Monitoring**: Use CloudWatch for logging and monitoring 7. **Cold starts**: HTTP client reduces cold start impact 8. **Memory allocation**: Adjust memory based on your workload (more memory = more CPU) ## Using AWS Secrets Manager For better security, use AWS Secrets Manager: ```javascript import { SecretsManagerClient, GetSecretValueCommand, } from '@aws-sdk/client-secrets-manager'; let client; let secrets; async function getSecrets() { if (!secrets) { const secretsClient = new SecretsManagerClient({}); const response = await secretsClient.send( new GetSecretValueCommand({ SecretId: process.env.MILVUS_SECRET_NAME, }) ); secrets = JSON.parse(response.SecretString); } return secrets; } async function getClient() { if (!client) { const { endpoint, token } = await getSecrets(); client = new HttpClient({ endpoint, token, timeout: 25000, }); } return client; } ``` ## Troubleshooting ### Error: “Task timed out” **Solution**: - Increase Lambda timeout - Optimize your Milvus queries - Reduce timeout value in HttpClient configuration ### Error: “Out of memory” **Solution**: - Increase Lambda memory allocation - Optimize your code - Reduce batch sizes ### Error: “Module not found” **Solution**: Ensure `@zilliz/milvus2-sdk-node` is included in your deployment package. ## Next Steps - Learn about [Cloudflare Workers Deployment](https://milvus-io.github.io/milvus-sdk-node/advanced/cloudflare/) - Explore [Vercel Deployment](https://milvus-io.github.io/milvus-sdk-node/advanced/vercel/) - Check out [HTTP Client Guide](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/) - Read [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) --- # Best Practices Run the Milvus Node.js SDK in production with connection reuse, batch writes, appropriate indexes, and retry handling. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/ ## Section links - [Connection Management](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#connection-management) - [Reuse Client Instances](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#reuse-client-instances) - [Proper Cleanup](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#proper-cleanup) - [Connection Pooling](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#connection-pooling) - [Error Handling Strategies](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#error-handling-strategies) - [Comprehensive Error Handling](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#comprehensive-error-handling) - [Retry Logic](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#retry-logic) - [Performance Optimization](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#performance-optimization) - [Batch Operations](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#batch-operations) - [Load Collections Before Search](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#load-collections-before-search) - [Use Appropriate Index Types](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#use-appropriate-index-types) - [Tune Search Parameters](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#tune-search-parameters) - [Data Modeling Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#data-modeling-best-practices) - [Schema Design](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#schema-design) - [Use AutoID](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#use-autoid) - [Appropriate Field Types](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#appropriate-field-types) - [Index Selection Guidelines](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#index-selection-guidelines) - [Index Type Selection](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#index-type-selection) - [Metric Type Selection](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#metric-type-selection) - [Query Optimization](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#query-optimization) - [Use Filters](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#use-filters) - [Limit Result Sets](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#limit-result-sets) - [Use Iterators for Large Results](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#use-iterators-for-large-results) - [Memory Management](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#memory-management) - [Release Collections](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#release-collections) - [Monitor Memory Usage](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#monitor-memory-usage) - [Production Deployment Considerations](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#production-deployment-considerations) - [Environment Configuration](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#environment-configuration) - [Logging Configuration](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#logging-configuration) - [SSL/TLS Configuration](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#ssltls-configuration) - [Health Checks](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#health-checks) - [Monitoring and Observability](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#monitoring-and-observability) - [Metrics Collection](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#metrics-collection) - [Error Tracking](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#error-tracking) - [Security Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#security-best-practices) - [Authentication](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#authentication) - [RBAC](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#rbac) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/#next-steps) This guide covers best practices for using the Milvus Node.js SDK in production environments. ## Connection Management ### Reuse Client Instances Create one client instance and reuse it: ```javascript // Good: Create once, reuse const client = new MilvusClient({ address: 'localhost:19530', }); // Use the same client throughout your application ``` ### Proper Cleanup Close connections when done: ```javascript // At application shutdown await client.closeConnection(); ``` ### Connection Pooling Configure appropriate pool sizes: ```javascript const client = new MilvusClient({ address: 'localhost:19530', pool: { min: 2, max: 10, // Adjust based on your workload }, }); ``` ## Error Handling Strategies ### Comprehensive Error Handling ```javascript try { const { status } = await client.describeCollection({ collection_name: 'my_collection', }); if (status.error_code === 'CollectionNotExists') { console.error('Collection does not exist'); } else if (status.error_code !== 'Success') { console.error(status.reason); } } catch (error) { console.error('Transport or SDK error:', error); } ``` ### Retry Logic Configure automatic retries: ```javascript const client = new MilvusClient({ address: 'localhost:19530', maxRetries: 3, retryDelay: 1000, }); ``` ## Performance Optimization ### Batch Operations Insert data in batches: ```javascript const batchSize = 1000; for (let i = 0; i < data.length; i += batchSize) { const batch = data.slice(i, i + batchSize); await client.insert({ collection_name: 'my_collection', data: batch, }); } ``` ### Load Collections Before Search Always load collections before searching: ```javascript await client.loadCollectionSync({ collection_name: 'my_collection', }); // Now search const results = await client.search({ collection_name: 'my_collection', data: [queryVector], limit: 10, }); ``` ### Use Appropriate Index Types Choose indexes based on your use case: ```javascript // Small dataset: FLAT // Medium dataset: HNSW // Large dataset: IVF_PQ await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'HNSW', // Choose based on dataset size metric_type: 'L2', }); ``` ### Tune Search Parameters Optimize search parameters: ```javascript // For IVF indexes const results = await client.search({ collection_name: 'my_collection', data: [/* vector */], params: { nprobe: 64, // Adjust based on recall/performance needs }, limit: 10, }); ``` ## Data Modeling Best Practices ### Schema Design Design schemas carefully: ```javascript // Good: Clear field names, appropriate types const schema = [ { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, }, { name: 'embedding', data_type: DataType.FloatVector, dim: 128, }, { name: 'metadata', data_type: DataType.JSON, // Use JSON for flexible data }, ]; ``` ### Use AutoID Let Milvus generate IDs unless you have specific requirements: ```javascript { name: 'id', data_type: DataType.Int64, is_primary_key: true, autoID: true, // Recommended } ``` ### Appropriate Field Types Choose appropriate data types: ```javascript // Use Int64 for IDs // Use FloatVector for embeddings // Use VarChar for text (with appropriate max_length) // Use JSON for flexible metadata ``` ## Index Selection Guidelines ### Index Type Selection - **FLAT**: < 1M vectors, exact search - **HNSW**: 1M - 10M vectors, high recall - **IVF_FLAT**: Balanced performance - **IVF_SQ8**: Memory-efficient - **IVF_PQ**: > 10M vectors, most memory-efficient ### Metric Type Selection - **L2**: Most common, for embeddings trained with L2 - **IP**: For embeddings trained with inner product - **COSINE**: For normalized embeddings - **HAMMING/JACCARD**: For binary vectors ## Query Optimization ### Use Filters Apply filters to narrow results: ```javascript const results = await client.search({ collection_name: 'my_collection', data: [/* vector */], expr: 'category == "tech" AND age > 25', // Filter before search limit: 10, }); ``` ### Limit Result Sets Set appropriate limits: ```javascript const results = await client.search({ collection_name: 'my_collection', data: [/* vector */], limit: 10, // Don't request more than needed }); ``` ### Use Iterators for Large Results Use iterators for large result sets: ```javascript const iterator = await client.queryIterator({ collection_name: 'my_collection', expr: 'age > 25', batchSize: 100, }); ``` ## Memory Management ### Release Collections Release collections when not in use: ```javascript await client.releaseCollection({ collection_name: 'my_collection', }); ``` ### Monitor Memory Usage Check collection loading status: ```javascript const state = await client.getLoadState({ collection_name: 'my_collection', }); console.log('Load state:', state.state); ``` ## Production Deployment Considerations ### Environment Configuration Use environment variables: ```javascript const client = new MilvusClient({ address: process.env.MILVUS_ADDRESS, username: process.env.MILVUS_USERNAME, password: process.env.MILVUS_PASSWORD, ssl: process.env.NODE_ENV === 'production', }); ``` ### Logging Configuration Use appropriate log levels: ```javascript const client = new MilvusClient({ address: 'localhost:19530', logLevel: process.env.NODE_ENV === 'production' ? 'warn' : 'debug', }); ``` ### SSL/TLS Configuration Enable SSL in production: ```javascript const client = new MilvusClient({ address: 'milvus.example.com:443', ssl: true, tls: { rootCertPath: '/path/to/ca.pem', serverName: 'milvus.example.com', }, }); ``` ### Health Checks Implement health checks: ```javascript async function healthCheck() { try { await client.listCollections(); return true; } catch (error) { return false; } } ``` ## Monitoring and Observability ### Metrics Collection Collect and monitor metrics: ```javascript const metrics = await client.getMetric({ request: { metric_type: 'system_info', }, }); ``` ### Error Tracking Track errors appropriately: ```javascript try { const { status } = await client.search({ collection_name: 'my_collection', data: [queryVector], limit: 10, }); if (status.error_code !== 'Success') throw new Error(status.reason); } catch (error) { // Log to your error tracking service errorTracker.captureException(error); } ``` ## Security Best Practices ### Authentication Always use authentication: ```javascript const client = new MilvusClient({ address: 'localhost:19530', username: 'root', password: 'securepassword', }); ``` ### RBAC Use role-based access control: ```javascript // Create roles with minimal privileges await client.createRole({ roleName: 'readonly', }); // Grant only necessary privileges import { RbacObjects } from '@zilliz/milvus2-sdk-node'; await client.grantPrivilege({ roleName: 'readonly', object: RbacObjects.Collection, objectName: '*', privilegeName: 'DescribeCollection', }); ``` ## Next Steps - Explore [Examples & Tutorials](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/) - Check out [Troubleshooting](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/) - Review [API Reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/) --- # SDK Reference Find Milvus Node.js SDK TypeScript methods, request and response types, and examples for the gRPC and HTTP clients. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/ ## Section links - [Client](https://milvus-io.github.io/milvus-sdk-node/api-reference/#client) - [Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/#operations) - [Types](https://milvus-io.github.io/milvus-sdk-node/api-reference/#types) - [Guide documentation](https://milvus-io.github.io/milvus-sdk-node/api-reference/#guide-documentation) Look up TypeScript methods for the Milvus Node.js SDK. ## Client - [MilvusClient](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/): constructor, SDK metadata, and client-level entry points. - [HttpClient](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/): REST client configuration, request naming conventions, and HTTP-only operations. ## Operations - [Collection Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/): create, describe, evolve schemas and functions, load, release, rename, snapshot, and manage collections. - [Data Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/): insert, upsert, query/search aggregation, delete, iterators, compaction, and bulk import. - [Index Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/): create, inspect, alter, and drop vector or scalar indexes. - [Partition Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/): create, list, and drop collection partitions. - [Database Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/databases/): create, list, describe, alter, and drop databases. - [User & Role Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/): create users, update passwords, create roles, and grant privileges. - [Resource Group Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/): create resource groups, inspect capacity, and transfer nodes or replicas. - [System Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/): check health, inspect versions, test analyzers, manage analyzer file resources, and get metrics. - [BulkWriter](https://milvus-io.github.io/milvus-sdk-node/api-reference/bulk-writer/): client-side JSON/Parquet bulk files, column buffering, storage adapters, and Zilliz Cloud volumes. ## Types - [Types & Enums](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/): common data types, error codes, and response shapes. ## Guide documentation If you are learning concepts or looking for end-to-end examples, use the main documentation instead: - [Getting Started](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/) - [Examples & Tutorials](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/) - [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) - [Troubleshooting](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/) --- # MilvusClient Look up the MilvusClient constructor, authentication, connection options, database context, and client methods for gRPC in Node.js. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/client/ ## Section links - [Constructor](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#constructor) - [Configuration object](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#configuration-object) - [Legacy positional form](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#legacy-positional-form) - [ClientConfig](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#clientconfig) - [Static properties](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#static-properties) - [sdkInfo](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#sdkinfo) - [Connection lifecycle](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#connection-lifecycle) - [connectPromise](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#connectpromise) - [use](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#use) - [closeConnection](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#closeconnection) - [reconnectToPrimary](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#reconnecttoprimary) - [session](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#session) - [High-level createCollection overload](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#high-level-createcollection-overload) - [Auth examples](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#auth-examples) - [Local Milvus username/password](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#local-milvus-usernamepassword) - [Zilliz Cloud token](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#zilliz-cloud-token) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#related) - [Client telemetry (SDK 3.0.5)](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#client-telemetry-sdk-305) `MilvusClient` is the main gRPC client for Milvus. It owns connection metadata, authentication, retry behavior, database context, and all high-level APIs exposed by the SDK. ## Constructor ```typescript new MilvusClient( config: ClientConfig | string, ssl?: boolean, username?: string, password?: string, channelOptions?: ChannelOptions ) ``` You can construct the client with either a configuration object or the legacy positional arguments. ### Configuration object ```typescript const client = new MilvusClient({ address: 'localhost:19530', ssl: false, username: 'root', password: 'Milvus', database: 'default', timeout: 30_000, maxRetries: 3, retryDelay: 200, }); await client.connectPromise; ``` ### Legacy positional form ```typescript const client = new MilvusClient('localhost:19530', false, 'root', 'Milvus'); ``` ## ClientConfig ```typescript interface ClientConfig { address: string; token?: string; ssl?: boolean; username?: string; password?: string; channelOptions?: ChannelOptions; option?: Record; timeout?: number | string; maxRetries?: number; retryDelay?: number; database?: string; logLevel?: string; logPrefix?: string; tls?: { rootCertPath?: string; rootCert?: Buffer; privateKeyPath?: string; privateKey?: Buffer; certChainPath?: string; certChain?: Buffer; verifyOptions?: Record; serverName?: string; skipCertCheck?: boolean; }; pool?: Options; loaderOptions?: LoaderOption; telemetry?: TelemetryConfig; trace?: boolean; isGlobal?: boolean; } ``` **Important fields**: - `address`: Milvus gRPC address, for example `localhost:19530`. - `token`: Auth token. Accepts `username:password` or a Zilliz Cloud API key. - `username` / `password`: Alternative auth fields when `token` is not provided. - `ssl`: Enables TLS when `true`. - `tls`: Certificate and verification options for TLS connections. - `database`: Initial database context. Defaults to `default`. - `timeout`: Default request timeout in milliseconds. - `maxRetries` / `retryDelay`: gRPC retry behavior. - `pool`: `generic-pool` options for the gRPC channel pool. - `loaderOptions`: protobuf loader options. `longs: String` is the default to avoid int64 precision loss. - `trace`: Enables request tracing metadata. - `isGlobal`: Explicitly enables or disables global-cluster routing. ## Static properties ### sdkInfo Return SDK version and the recommended Milvus version encoded at build time. ```typescript MilvusClient.sdkInfo; // { version: string, recommendMilvus: string } ``` Example: ```typescript console.log('SDK version:', MilvusClient.sdkInfo.version); console.log('Recommended Milvus:', MilvusClient.sdkInfo.recommendMilvus); ``` ## Connection lifecycle ### connectPromise `MilvusClient` starts connecting during construction unless `__SKIP_CONNECT__` is set. Await `connectPromise` before the first operation when you want explicit connection readiness. ```typescript const client = new MilvusClient({ address: 'localhost:19530' }); await client.connectPromise; ``` ### use Set the active database for subsequent gRPC requests. ```typescript use(data?: { db_name: string }): Promise useDatabase(data?: { db_name: string }): Promise // alias ``` Example: ```typescript await client.use({ db_name: 'analytics' }); await client.showCollections(); ``` Calling `use()` with no database resets the context to `default`. ### closeConnection Drain and clear the gRPC connection pool. ```typescript closeConnection(): Promise ``` Example: ```typescript await client.closeConnection(); ``` ### reconnectToPrimary For global-cluster connections, refresh topology and reconnect to a new primary cluster if failover occurred. ```typescript reconnectToPrimary(): Promise ``` Returns `true` when the primary endpoint changed and reconnection was performed. ### session Create a lightweight DQL session pinned to a target cluster id. ```typescript session(clusterId: string): MilvusClientSession ``` The session reuses the parent client’s connection and injects `cluster_id` into supported requests. Closing the session prevents future session calls, but it does not close the parent `MilvusClient` or the gRPC channel pool. Supported session methods: | Method | Description | | --- | --- | | `search(params)` | Search with the session cluster id. | | `hybridSearch(params)` | Hybrid search with the session cluster id. | | `searchIterator(params)` | Create a search iterator with the session cluster id. | | `query(params)` | Query with the session cluster id. | | `queryIterator(params)` | Create a query iterator with the session cluster id. | | `get(params)` | Get rows by primary key with the session cluster id. | | `close()` | Close only this session wrapper. | Example: ```typescript const session = client.session('cluster-a'); const results = await session.search({ collection_name: 'books', data: [[0.1, 0.2, 0.3, 0.4]], anns_field: 'vector', limit: 10, }); session.close(); ``` ## High-level createCollection overload `MilvusClient#createCollection` extends the lower-level collection API with a quick-create form that aligns with the Python SDK. ```typescript createCollection( data: CreateColReq | CreateColWithSchemaAndIndexParamsReq | CreateCollectionReq ): Promise ``` Quick-create example: ```typescript await client.createCollection({ collection_name: 'quick_start', dimension: 768, metric_type: 'COSINE', primary_field_name: 'id', vector_field_name: 'embedding', auto_id: false, }); ``` Schema + index example: ```typescript await client.createCollection({ collection_name: 'books', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true }, { name: 'embedding', data_type: DataType.FloatVector, dim: 768 }, ], index_params: { field_name: 'embedding', index_type: 'AUTOINDEX', metric_type: 'COSINE', }, }); ``` ## Auth examples ### Local Milvus username/password ```typescript const client = new MilvusClient({ address: 'localhost:19530', username: 'root', password: 'Milvus', }); ``` ### Zilliz Cloud token ```typescript const client = new MilvusClient({ address: 'your-cluster-endpoint:19530', ssl: true, token: process.env.ZILLIZ_CLOUD_API_KEY, }); ``` ## Related - [API Reference overview](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - [Collection Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/) - [Client Configuration](https://milvus-io.github.io/milvus-sdk-node/core-concepts/client-configuration/) ## Client telemetry (SDK 3.0.5) `telemetry` configures heartbeat reporting and is enabled by default. See [Client Telemetry](https://milvus-io.github.io/milvus-sdk-node/advanced/client-telemetry/) for defaults, collected information, disabling, and `getTelemetry()` inspection. `TelemetryConfig` is exported from the package root. --- # HttpClient Look up the Node.js HttpClient constructor, camelCase request fields, HttpError, and TypeScript methods backed by the Milvus REST API. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/ ## Section links - [Constructor](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#constructor) - [Float vector output](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#float-vector-output) - [Per-request options](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#per-request-options) - [Collection APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#collection-apis) - [createCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createcollection) - [describeCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describecollection) - [dropCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropcollection) - [addCollectionField](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addcollectionfield) - [alterCollectionProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#altercollectionproperties) - [alterCollectionFieldProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#altercollectionfieldproperties) - [dropCollectionProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropcollectionproperties) - [listCollections](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listcollections) - [hasCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#hascollection) - [renameCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#renamecollection) - [getCollectionStatistics](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getcollectionstatistics) - [flushCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#flushcollection) - [loadCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#loadcollection) - [releaseCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#releasecollection) - [getCollectionLoadState](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getcollectionloadstate) - [compactCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#compactcollection) - [getCompactionState](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getcompactionstate) - [refreshLoad](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#refreshload) - [Collection maintenance example](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#collection-maintenance-example) - [Data APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#data-apis) - [insert](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#insert) - [upsert](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#upsert) - [get](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#get) - [query](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#query) - [search](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#search) - [hybridSearch](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#hybridsearch) - [delete](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#delete) - [Filtering, ordering, and grouping](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#filtering-ordering-and-grouping) - [Database APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#database-apis) - [createDatabase](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createdatabase) - [dropDatabase](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropdatabase) - [describeDatabase](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describedatabase) - [listDatabases](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listdatabases) - [alterDatabaseProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alterdatabaseproperties) - [dropDatabaseProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropdatabaseproperties) - [Index APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#index-apis) - [createIndex](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createindex) - [dropIndex](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropindex) - [describeIndex](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describeindex) - [listIndexes](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listindexes) - [alterIndexProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alterindexproperties) - [dropIndexProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropindexproperties) - [Partition APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#partition-apis) - [listPartitions](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listpartitions) - [createPartition](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createpartition) - [dropPartition](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#droppartition) - [loadPartitions](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#loadpartitions) - [releasePartitions](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#releasepartitions) - [hasPartition](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#haspartition) - [getPartitionStatistics](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getpartitionstatistics) - [Alias APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alias-apis) - [listAliases](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listaliases) - [createAlias](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createalias) - [describeAlias](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describealias) - [alterAlias](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alteralias) - [dropAlias](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropalias) - [Import APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#import-apis) - [listImportJobs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listimportjobs) - [createImportJobs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createimportjobs) - [getImportJobProgress](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getimportjobprogress) - [commitImportJob](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#commitimportjob) - [abortImportJob](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#abortimportjob) - [Import job example](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#import-job-example) - [Collection Schema Changes](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#collection-schema-changes) - [addCollectionStructField](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addcollectionstructfield) - [dropCollectionField](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropcollectionfield) - [addFunctionField](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addfunctionfield) - [dropFunctionField](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropfunctionfield) - [alterCollectionFunction](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#altercollectionfunction) - [truncateCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#truncatecollection) - [External Collection Refresh](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#external-collection-refresh) - [refreshExternalCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#refreshexternalcollection) - [getRefreshExternalCollectionProgress](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getrefreshexternalcollectionprogress) - [listRefreshExternalCollectionJobs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listrefreshexternalcollectionjobs) - [Snapshot APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#snapshot-apis) - [createSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createsnapshot) - [listSnapshots](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listsnapshots) - [describeSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describesnapshot) - [dropSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropsnapshot) - [pinSnapshotData](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#pinsnapshotdata) - [unpinSnapshotData](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#unpinsnapshotdata) - [restoreSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#restoresnapshot) - [getRestoreSnapshotState](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getrestoresnapshotstate) - [listRestoreSnapshotJobs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listrestoresnapshotjobs) - [exportSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#exportsnapshot) - [getExportSnapshotState](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getexportsnapshotstate) - [restoreExternalSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#restoreexternalsnapshot) - [Resource Group APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#resource-group-apis) - [createResourceGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createresourcegroup) - [describeResourceGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describeresourcegroup) - [listResourceGroups](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listresourcegroups) - [dropResourceGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropresourcegroup) - [updateResourceGroups](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#updateresourcegroups) - [transferReplica](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#transferreplica) - [User and Role APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#user-and-role-apis) - [createUser](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createuser) - [updateUserPassword](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#updateuserpassword) - [dropUser](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropuser) - [describeUser](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describeuser) - [listUsers](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listusers) - [grantRoleToUser](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#grantroletouser) - [revokeRoleFromUser](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#revokerolefromuser) - [createRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createrole) - [alterRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alterrole) - [dropRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#droprole) - [describeRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describerole) - [listRoles](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listroles) - [grantPrivilegeToRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#grantprivilegetorole) - [revokePrivilegeFromRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#revokeprivilegefromrole) - [Role privilege example](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#role-privilege-example) - [grantPrivilegeV2](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#grantprivilegev2) - [revokePrivilegeV2](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#revokeprivilegev2) - [createPrivilegeGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createprivilegegroup) - [addPrivilegesToGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addprivilegestogroup) - [removePrivilegesFromGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#removeprivilegesfromgroup) - [listPrivilegeGroups](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listprivilegegroups) - [dropPrivilegeGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropprivilegegroup) - [Analyzer and File Resource APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#analyzer-and-file-resource-apis) - [runAnalyzer](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#runanalyzer) - [addFileResource](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addfileresource) - [listFileResources](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listfileresources) - [removeFileResource](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#removefileresource) - [Diagnostics APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#diagnostics-apis) - [getSegmentsInfo](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getsegmentsinfo) - [getQuotaMetrics](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getquotametrics) - [Errors](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#errors) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#related) `HttpClient` is the REST client exported by `@zilliz/milvus2-sdk-node`. Use it when an environment prefers HTTP over gRPC, such as serverless platforms, HTTP-only runtimes, or proxy-restricted deployments. HTTP request fields use the REST API’s camelCase naming convention, for example `collectionName`, `dbName`, `outputFields`, and `indexParams`. gRPC APIs on `MilvusClient` use snake_case fields such as `collection_name` and `output_fields`. ## Constructor ```text new HttpClient(config: HttpClientConfig) ``` ```typescript type HttpClientConfig = | { endpoint: string; baseURL?: string; database?: string; token?: string; username?: string; password?: string; timeout?: number; fetch?: typeof fetch; acceptInt64?: boolean; floatVectorEncoding?: 'array' | 'base64'; } | { baseURL: string; endpoint?: string; database?: string; token?: string; username?: string; password?: string; timeout?: number; fetch?: typeof fetch; acceptInt64?: boolean; floatVectorEncoding?: 'array' | 'base64'; }; ``` `endpoint` is the cluster origin, such as `https://your-cluster.example.com`. The SDK appends `/v2` automatically. If you set `baseURL` directly, include the full versioned base URL, such as `https://your-cluster.example.com/v2`. A base URL without `/v2` can produce 404 responses. Example: ```typescript import { HttpClient, HttpError } from '@zilliz/milvus2-sdk-node'; const client = new HttpClient({ endpoint: 'https://your-cluster.example.com', token: process.env.MILVUS_TOKEN, database: 'default', timeout: 30_000, acceptInt64: true, }); ``` ### Float vector output On Milvus 3.0.7+, set `floatVectorEncoding: 'base64'` to receive `FLOAT_VECTOR` output fields as standard padded Base64 strings, including vectors inside StructArray rows. The default is numeric arrays. This option applies to returned fields in get, query, search, and hybrid search. Supply input vectors in their usual format. Each coordinate is an IEEE 754 float32 encoded in little-endian order. Older servers can return numeric arrays even when Base64 is requested. The following Node.js example handles both formats. ```typescript const http = new HttpClient({ endpoint, floatVectorEncoding: 'base64' }); const { data } = await http.query({ collectionName: 'books', filter: 'id == 1', outputFields: ['embedding'], }); function decodeVector(value: string | number[]): number[] { if (Array.isArray(value)) return value; const bytes = Buffer.from(value, 'base64'); return Array.from({ length: bytes.length / 4 }, (_, i) => bytes.readFloatLE(i * 4) ); } const embedding = decodeVector(data[0].embedding); ``` ## Per-request options Every HTTP method accepts an optional `FetchOptions` object. ```typescript type FetchOptions = { abortController: AbortController; timeout: number; }; ``` Example: ```typescript await client.search( { collectionName: 'books', data: [[0.1, 0.2, 0.3, 0.4]], outputFields: ['title'], limit: 10, }, { abortController: new AbortController(), timeout: 10_000 } ); ``` ## Collection APIs ### createCollection `createCollection(data, options?)` Create a collection by dimension shortcut or explicit schema. ### describeCollection ```text describeCollection(data: HttpBaseReq, options?: FetchOptions): Promise ``` Pass `collectionName`. Optionally set `dbName`. ```ts const { code, data } = await client.describeCollection({ collectionName: 'books', }); ``` Returns a Milvus response envelope with collection metadata, including schema fields, indexes, and load state. [Try the REST operation](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/describe/). ### dropCollection `dropCollection(data, options?)` Drop a collection. ### addCollectionField `addCollectionField(data, options?)` Add a field to an existing collection. ### alterCollectionProperties `alterCollectionProperties(data, options?)` Add or update collection properties. ### alterCollectionFieldProperties `alterCollectionFieldProperties(data, options?)` Alter field-level properties such as `max_length`, `max_capacity`, or `mmap_enabled`. ### dropCollectionProperties `dropCollectionProperties(data, options?)` Remove collection properties by key. ### listCollections ```text listCollections(data?: HttpCollectionListReq, options?: FetchOptions): Promise ``` All inputs are optional. Set `dbName` to choose the database. ```ts const { code, data } = await client.listCollections({ dbName: 'default' }); ``` Returns a Milvus response envelope with collection names as a string array. [Try the REST operation](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/list/). ### hasCollection `hasCollection(data, options?)` Check whether a collection exists. ### renameCollection `renameCollection(data, options?)` Rename a collection, optionally into another database. ### getCollectionStatistics `getCollectionStatistics(data, options?)` Get collection statistics such as row count. ### flushCollection `flushCollection(data, options?)` Flush a collection. ### loadCollection `loadCollection(data, options?)` Load a collection into memory. ### releaseCollection `releaseCollection(data, options?)` Release a loaded collection. ### getCollectionLoadState `getCollectionLoadState(data, options?)` Get load progress and load state. ### compactCollection `compactCollection(data, options?)` Start collection compaction. ### getCompactionState `getCompactionState(data, options?)` Get compaction progress by compaction ID. ### refreshLoad `refreshLoad(data, options?)` Refresh an existing loaded collection. ### Collection maintenance example ```typescript await client.flushCollection({ collectionName: 'books' }); const loadState = await client.getCollectionLoadState({ collectionName: 'books', }); const compaction = await client.compactCollection({ collectionName: 'books', }); ``` ## Data APIs ### insert `insert(data, options?)` Insert rows. ### upsert `upsert(data, options?)` Insert or update rows. ### get `get(data, options?)` Fetch rows by ID. ### query ```text query(data: HttpVectorQueryReq, options?: FetchOptions): Promise ``` Pass `collectionName` and `outputFields`. Use `filter` to select rows or set a `limit` for an unfiltered query. ```ts const { code, data } = await client.query({ collectionName: 'books', outputFields: ['title'], limit: 5, }); ``` Returns a Milvus response envelope with matching rows. [Try the REST operation](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/query/). ### search ```text search(data: HttpVectorSearchReq | HttpVectorSearchByIdsReq, options?: FetchOptions): Promise ``` Pass `collectionName`, `outputFields`, and either a batch of search inputs in `data` or stored primary keys in `ids`. Specify `annsField` when the collection has multiple vector fields. ```ts const { code, data } = await client.search({ collectionName: 'books', data: [[0.1, 0.2, 0.3, 0.4]], annsField: 'vector', outputFields: ['title'], limit: 5, }); ``` Returns a Milvus response envelope with search hits with IDs, distances, and requested fields. The aggregation overload takes `HttpVectorSearchAggregationReq` and returns `HttpVectorSearchAggregationResponse` with buckets. [Try the REST operation](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/search/). ### hybridSearch `hybridSearch(data, options?)` Hybrid search over multiple vector requests with reranking. ### delete `delete(data, options?)` Delete rows by filter. ### Filtering, ordering, and grouping Use `exprParams` to bind filter placeholders such as `label in {labels}` in query, delete, search, or individual hybrid search requests. For query results, use `orderByFields` with keys such as `'price:desc'`. To group rows, pass scalar `groupByFields` and aggregation expressions such as `'count(*)'` in `outputFields`. These options were verified on Milvus 3.0.6. REST `search()` accepts a batch of vectors or text in `data`, or searches using stored primary keys in `ids`. Pass large int64 primary keys as decimal strings. Use `orderByFields` for scalar ordering and `groupingField`, `groupSize`, and `strictGroupSize` for grouped search. Hybrid search also accepts the grouping options. Use `functionChains` for REST search and hybrid reranking. A chain sends the protobuf stage name as a string such as `'FunctionChainStageL2Rerank'`, followed by its `ops`. In an expression argument, send a column as `{ column: '$score' }` or a JSON literal as `{ literal: 2 }`. Hybrid search accepts chains on the full request and on each sub-search. These options were verified on Milvus 3.0.6. Pass `searchAggregation` to `search()` to return buckets for each query vector. Set `fields` and `size`, and use `metrics`, `order`, `topHits`, or `subAggregation` to customize the buckets. The response returns each query’s `buckets` in `data` and the corresponding counts in `aggTopks`. Int64 bucket values and counts are decimal strings with the default `acceptInt64: false`. Milvus 3.0.6 supports this option on vector search. ## Database APIs ### createDatabase `createDatabase(data, options?)` Create a database. ### dropDatabase `dropDatabase(data, options?)` Drop a database. ### describeDatabase `describeDatabase(data, options?)` Describe database metadata and properties. ### listDatabases `listDatabases(options?)` List databases. ### alterDatabaseProperties `alterDatabaseProperties(data, options?)` Add or update database properties. ### dropDatabaseProperties `dropDatabaseProperties(data, options?)` Remove database properties by key. ## Index APIs ### createIndex `createIndex(data, options?)` Create one or more indexes. ### dropIndex `dropIndex(data, options?)` Drop an index. ### describeIndex `describeIndex(data, options?)` Describe indexes. ### listIndexes `listIndexes(data, options?)` List index names. ### alterIndexProperties `alterIndexProperties(data, options?)` Add or update index properties. ### dropIndexProperties `dropIndexProperties(data, options?)` Remove index properties by key. ## Partition APIs ### listPartitions `listPartitions(data, options?)` List partitions. ### createPartition `createPartition(data, options?)` Create a partition. ### dropPartition `dropPartition(data, options?)` Drop a partition. ### loadPartitions `loadPartitions(data, options?)` Load partitions. ### releasePartitions `releasePartitions(data, options?)` Release partitions. ### hasPartition `hasPartition(data, options?)` Check whether a partition exists. ### getPartitionStatistics `getPartitionStatistics(data, options?)` Get partition statistics such as row count. ## Alias APIs ### listAliases `listAliases(data, options?)` List aliases in a database or collection. ### createAlias `createAlias(data, options?)` Create an alias for a collection. ### describeAlias `describeAlias(data, options?)` Describe an alias. ### alterAlias `alterAlias(data, options?)` Move an alias to another collection. ### dropAlias `dropAlias(data, options?)` Drop an alias. ## Import APIs HTTP import APIs are separate from the gRPC `bulkInsert`, `getImportState`, and `listImportTasks` APIs. ### listImportJobs `listImportJobs(data, options?)` List REST import jobs for a collection. ### createImportJobs `createImportJobs(data, options?)` Create REST import jobs from staged files. ### getImportJobProgress `getImportJobProgress(data, options?)` Get progress for a REST import job. ### commitImportJob `commitImportJob(data, options?)` Commit an `Uncommitted` import job. ### abortImportJob `abortImportJob(data, options?)` Abort an import job before it commits. ### Import job example ```typescript const job = await client.createImportJobs({ collectionName: 'books', files: [['imports/books/part-0.parquet']], }); const progress = await client.getImportJobProgress({ jobId: job.data.jobId, }); ``` On Milvus 3.0.6, create a manual-commit job with `options: { auto_commit: 'false' }`. Poll `getImportJobProgress()` until the state is `Uncommitted`, then call `commitImportJob({ jobId })` to make the imported rows visible. To discard a staged import, call `abortImportJob({ jobId })` before committing. Poll the job again for its final state. For Zilliz Cloud import workflows, include `projectId` and `regionId` when required by the cloud endpoint. ## Collection Schema Changes These methods were verified on Milvus 3.0.6. ### addCollectionStructField Add a nullable StructArray field using `schema`. ### dropCollectionField Remove a field by `fieldName` or `fieldId`. ### addFunctionField Add a function, its output field, and the bound index together. ### dropFunctionField Remove a function together with its output field and index. ### alterCollectionFunction Update supported settings for an existing function, such as a text embedding function’s description. Milvus 3.0.6 rejects BM25 function alterations. ### truncateCollection Remove all rows while keeping the schema and indexes. ## External Collection Refresh These methods were verified on Milvus 3.0.6. ### refreshExternalCollection Submit a refresh for an external collection. ### getRefreshExternalCollectionProgress Poll a refresh job. Pass the decimal job ID as returned by the SDK. ```typescript const { data: { jobId }, } = await client.refreshExternalCollection({ collectionName: 'external_books', }); const { data } = await client.getRefreshExternalCollectionProgress({ jobId }); ``` ### listRefreshExternalCollectionJobs List refresh jobs for a collection or database. ## Snapshot APIs The SDK preserves snapshot job IDs, pin IDs, and int64 metadata as decimal strings. These methods were verified on Milvus 3.0.6. ### createSnapshot Create a named snapshot of a collection. ### listSnapshots List snapshot names and summary metadata for a collection. ### describeSnapshot Read a named snapshot’s metadata and storage location. ### dropSnapshot Delete a named collection snapshot. ### pinSnapshotData Protect snapshot data for the requested lifetime and return a pin ID. ### unpinSnapshotData Release protection using its pin ID. ### restoreSnapshot Restore into a new collection. Omitted source and target database names default to the configured database. ### getRestoreSnapshotState Get restore progress by job ID. ### listRestoreSnapshotJobs List restore jobs for a collection or database. ### exportSnapshot Copy a snapshot to an object storage destination and return a job ID. ```typescript const { data: { jobId }, } = await client.exportSnapshot({ collectionName: 'books', snapshotName: 'before_migration', targetS3Path: 'exports/books', }); const { data } = await client.getExportSnapshotState({ jobId }); ``` ### getExportSnapshotState Check export progress and retrieve `snapshotMetadataURI` when complete. ### restoreExternalSnapshot Restore a portable snapshot using the exported `snapshotMetadataURI`. ## Resource Group APIs These methods were verified on Milvus 3.0.6. ### createResourceGroup Create a resource group with the requested node allocation. ### describeResourceGroup Read the top-level `resource_group` object. The SDK returns query node IDs as decimal strings. ### listResourceGroups List resource group names. ### dropResourceGroup Drop a resource group. ### updateResourceGroups Pass `{ resource_groups }` to update requests, limits, transfer preferences, and node labels. ### transferReplica Transfer collection replicas in the default database with `sourceRgName`, `targetRgName`, `collectionName`, and `replicaNum`. The target group needs available query nodes. ## User and Role APIs ### createUser `createUser(data, options?)` Create a user. ### updateUserPassword `updateUserPassword(data, options?)` Update a user’s password. ### dropUser `dropUser(data, options?)` Drop a user. ### describeUser `describeUser(data, options?)` Describe user details. ### listUsers `listUsers(options?)` List users. ### grantRoleToUser `grantRoleToUser(data, options?)` Grant a role to a user. ### revokeRoleFromUser `revokeRoleFromUser(data, options?)` Revoke a role from a user. ### createRole `createRole(data, options?)` Create a role. ### alterRole `alterRole(data, options?)` Update the description of a role. ### dropRole `dropRole(data, options?)` Drop a role. ### describeRole `describeRole(data, options?)` Describe role privileges. ### listRoles `listRoles(options?)` List roles. ### grantPrivilegeToRole `grantPrivilegeToRole(data, options?)` Grant a privilege to a role. ### revokePrivilegeFromRole `revokePrivilegeFromRole(data, options?)` Revoke a privilege from a role. ### Role privilege example ```typescript await client.grantPrivilegeToRole({ roleName: 'reader', objectType: 'Collection', objectName: 'books', privilege: 'Search', }); ``` ### grantPrivilegeV2 Grant a privilege or privilege group by `roleName`, `dbName`, `collectionName`, and `privilege`. Milvus requires authentication for v2 grants. ### revokePrivilegeV2 Revoke a v2 grant using the same scope and privilege fields. ### createPrivilegeGroup Create a group by `privilegeGroupName`. ### addPrivilegesToGroup Pass `privilegeGroupName` and a `privileges` array to add permissions. ### removePrivilegesFromGroup Pass `privilegeGroupName` and a `privileges` array to remove permissions. ### listPrivilegeGroups List privilege groups. The server returns each group’s privileges as a comma-separated string. ### dropPrivilegeGroup Drop a group by `privilegeGroupName`. ## Analyzer and File Resource APIs These methods were verified on Milvus 3.0.6. ### runAnalyzer Use `{ text, analyzerParams }` to preview tokens for strings, or pass `collectionName` and `fieldName` to reuse a field’s analyzer. Set `withDetail` for offsets and positions or `withHash` for token hashes. ### addFileResource Register `{ name, path }` for a file in the server’s storage. ### listFileResources List file resource registrations. File resource IDs are returned as decimal strings. ### removeFileResource Remove a registration by `name`. ## Diagnostics APIs These methods were verified on Milvus 3.0.6. ### getSegmentsInfo Pass `collectionID`, `segmentIDs`, or both to inspect segment state, row counts, and binlog IDs. Use decimal strings for large IDs. The SDK returns IDs and row counts as decimal strings. ### getQuotaMetrics Inspect quota center metrics. The response’s `data` contains JSON text. ## Errors Non-2xx responses throw `HttpError`. For HTTP success responses, inspect the Milvus response envelope. A `code` of `0` indicates success. ```typescript try { await client.describeCollection({ collectionName: 'missing' }); } catch (error) { if (error instanceof HttpError) { console.error(error.status, error.statusText, error.url); } } ``` Milvus 3.0.6 returns a top-level `resource_group` object on successful `describeResourceGroup()` calls. Handle that response shape directly. ## Related - [HTTP Client guide](https://milvus-io.github.io/milvus-sdk-node/advanced/http-client/) - [MilvusClient](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/) - [BulkWriter](https://milvus-io.github.io/milvus-sdk-node/api-reference/bulk-writer/) --- # Collection Operations Look up TypeScript methods for creating, describing, loading, releasing, and altering Milvus collections, schemas, aliases, and functions. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/ ## Section links - [createCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#createcollection) - [Quick-create parameters](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#quick-create-parameters) - [Explicit schema parameters](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#explicit-schema-parameters) - [Schema mutation](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#schema-mutation) - [addCollectionField](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#addcollectionfield) - [addCollectionFields](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#addcollectionfields) - [dropCollectionField](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#dropcollectionfield) - [alterCollectionFieldProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#altercollectionfieldproperties) - [Collection inspection](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#collection-inspection) - [hasCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#hascollection) - [showCollections](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#showcollections) - [describeCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#describecollection) - [batchDescribeCollections](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#batchdescribecollections) - [getCollectionStatistics](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#getcollectionstatistics) - [Collection properties](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#collection-properties) - [alterCollectionProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#altercollectionproperties) - [dropCollectionProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#dropcollectionproperties) - [Load and release](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#load-and-release) - [loadCollectionAsync](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#loadcollectionasync) - [loadCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#loadcollection) - [refreshLoad](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#refreshload) - [releaseCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#releasecollection) - [getLoadingProgress](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#getloadingprogress) - [getLoadState](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#getloadstate) - [Rename, truncate, and drop](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#rename-truncate-and-drop) - [renameCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#renamecollection) - [truncateCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#truncatecollection) - [dropCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#dropcollection) - [Alias operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#alias-operations) - [createAlias](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#createalias) - [describeAlias](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#describealias) - [listAliases](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#listaliases) - [alterAlias](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#alteralias) - [dropAlias](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#dropalias) - [Function operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#function-operations) - [alterCollectionSchema](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#altercollectionschema) - [addFunctionField](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#addfunctionfield) - [dropFunctionField](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#dropfunctionfield) - [addCollectionFunction](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#addcollectionfunction) - [alterCollectionFunction](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#altercollectionfunction) - [dropCollectionFunction](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#dropcollectionfunction) - [Compaction and replicas](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#compaction-and-replicas) - [compact](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#compact) - [getCompactionState](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#getcompactionstate) - [getCompactionStateWithPlans](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#getcompactionstatewithplans) - [getReplicas](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#getreplicas) - [Primary key helpers](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#primary-key-helpers) - [External collection refresh Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#external-collection-refresh-milvus-30) - [refreshExternalCollection](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#refreshexternalcollection) - [getRefreshExternalCollectionProgress](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#getrefreshexternalcollectionprogress) - [listRefreshExternalCollectionJobs](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#listrefreshexternalcollectionjobs) - [Snapshots Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#snapshots-milvus-30) - [createSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#createsnapshot) - [dropSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#dropsnapshot) - [listSnapshots](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#listsnapshots) - [describeSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#describesnapshot) - [restoreSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#restoresnapshot) - [getRestoreSnapshotState](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#getrestoresnapshotstate) - [exportSnapshot, getExportSnapshotState, restoreExternalSnapshot](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#exportsnapshot-getexportsnapshotstate-restoreexternalsnapshot) - [listRestoreSnapshotJobs](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#listrestoresnapshotjobs) - [pinSnapshotData](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#pinsnapshotdata) - [unpinSnapshotData](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#unpinsnapshotdata) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#related) - [Function-field backfill](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#function-field-backfill) Collection APIs manage schemas, collection lifecycle, load/release state, aliases, functions, compaction, external collections, and snapshots. ```typescript import { CollectionProperties, DataType, FunctionType, IndexType, MetricType, } from '@zilliz/milvus2-sdk-node'; ``` ## createCollection Create a collection. `MilvusClient#createCollection` supports both a quick-create form and explicit schema forms. ```typescript createCollection( data: CreateColReq | CreateColWithSchemaAndIndexParamsReq | CreateCollectionReq ): Promise ``` ### Quick-create parameters - `collection_name`: Collection name. - `dimension`: Vector dimension. - `primary_field_name?`: Primary key field name. Defaults to `id`. - `id_type?`: `DataType.Int64` or `DataType.VarChar`. - `vector_field_name?`: Vector field name. Defaults to `embedding`. - `metric_type?`: Metric type for the default index. - `enable_dynamic_field?` / `enableDynamicField?`: Enable dynamic field. Defaults to `true`. - `auto_id?`: Whether primary key auto-increments. - `consistency_level?`: Consistency level. - `index_params?`: Optional index params. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.createCollection({ collection_name: 'books', dimension: 768, metric_type: 'COSINE', }); ``` ### Explicit schema parameters - `collection_name`: Collection name. - `fields` or `schema`: Field schema array. - `shards_num?`: Number of shards. - `description?`: Collection description. - `consistency_level?`: Consistency level. - `num_partitions?`: Initial partition count. - `partition_key_field?`: Partition key field. - `clustering_key_field?`: Clustering key field. - `enable_dynamic_field?` / `enableDynamicField?`: Enable dynamic field. - `properties?`: Collection properties such as TTL or mmap settings. - `functions?`: Collection functions such as BM25 or text embedding. - `external_source?`, `external_spec?`, `file_resource_ids?`: External collection configuration. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.createCollection({ collection_name: 'books', fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true }, { name: 'title', data_type: DataType.VarChar, max_length: 512 }, { name: 'embedding', data_type: DataType.FloatVector, dim: 768 }, ], properties: { [CollectionProperties.TTL_SECONDS]: 86_400, }, }); ``` ## Schema mutation Milvus 3.0 Milvus 3.0 introduces collection schema alteration for adding and dropping fields and for atomically managing function output fields and indexes. The Node SDK exposes these operations through the following field and function methods. ### addCollectionField Add one field to an existing collection. ```typescript addCollectionField(data: AddCollectionFieldReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `field`: Field schema. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### addCollectionFields Add multiple fields by calling `addCollectionField` for each field. ```typescript addCollectionFields(data: AddCollectionFieldsReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `fields`: Field schema array. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### dropCollectionField Drop a field by name or field ID. ```typescript dropCollectionField(data: DropCollectionFieldReq): Promise ``` Provide exactly one field identifier: - `field_name`: Field name. - `field_id`: Positive numeric field ID returned by `describeCollection`. - `collection_name`: Collection name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ```typescript await client.dropCollectionField({ collection_name: 'books', field_name: 'legacy_category', }); ``` ### alterCollectionFieldProperties Modify field properties, such as `max_length` or `mmap.enabled`. ```typescript alterCollectionFieldProperties(data: AlterCollectionFieldPropertiesReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `field_name`: Field name. - `properties`: Properties to set. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.alterCollectionFieldProperties({ collection_name: 'books', field_name: 'title', properties: { max_length: 1024 }, }); ``` ## Collection inspection ### hasCollection Check if a collection exists. ```typescript hasCollection(data: HasCollectionReq): Promise ``` **Response**: `value` is `true` when the collection exists. ### showCollections List collections or loaded collections. ```typescript showCollections(data?: ShowCollectionsReq): Promise listCollections(data?: ShowCollectionsReq): Promise // alias list_collections(data?: ShowCollectionsReq): Promise // alias ``` **Parameters**: - `type?`: `ShowCollectionsType.All` or `ShowCollectionsType.Loaded`. - `collection_names?`: Collection names to check when using loaded status. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. **Response**: - `data[]`: Collection info with `name`, `id`, `timestamp`, and `loadedPercentage`. ### describeCollection Describe schema and collection metadata. ```typescript describeCollection(data: DescribeCollectionReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `cache?`: Return cached schema when `true`. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. **Response highlights**: - `schema.fields`: Field schema list. - `schema.functions`: Function schemas. - `collectionID`, `collection_name`, `consistency_level`. - `aliases`. - `properties`. - `anns_fields`, `scalar_fields`, `function_fields`: SDK-formatted field maps. ### batchDescribeCollections Describe multiple collections in one request. ```typescript batchDescribeCollections(data: BatchDescribeCollectionReq): Promise ``` **Parameters**: - `collection_names`: Collection names. - `collectionIDs?`: Collection IDs. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### getCollectionStatistics Get collection statistics. ```typescript getCollectionStatistics(data: GetCollectionStatisticsReq): Promise getCollectionStats(data: GetCollectionStatisticsReq): Promise // alias ``` **Response**: - `stats`: Raw key-value statistics. - `data.row_count`: Parsed row count. ## Collection properties ### alterCollectionProperties Modify collection properties. ```typescript alterCollectionProperties(data: AlterCollectionReq): Promise alterCollection(data: AlterCollectionReq): Promise // deprecated alias ``` **Parameters**: - `collection_name`: Collection name. - `properties`: Properties to set. - `delete_keys?`: Property keys to delete. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.alterCollectionProperties({ collection_name: 'books', properties: { [CollectionProperties.MMAP_ENABLED]: true }, }); ``` ### dropCollectionProperties Remove collection properties. ```typescript dropCollectionProperties(data: DropCollectionPropertiesReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `properties`: Property keys to remove. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ## Load and release ### loadCollectionAsync Start loading a collection without waiting for completion. ```typescript loadCollectionAsync(data: LoadCollectionReq): Promise ``` ### loadCollection Load a collection and wait until loading progress reaches 100%. ```typescript loadCollection(data: LoadCollectionReq): Promise loadCollectionSync(data: LoadCollectionReq): Promise // alias ``` **Parameters**: - `collection_name`: Collection name. - `replica_number?`: Replica count. - `resource_groups?`: Target resource groups. - `refresh?`: Refresh loaded data. - `load_fields?`: Fields to load. - `skip_load_dynamic_field?`: Skip dynamic field loading. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### refreshLoad Refresh a loaded collection to pick up schema or data changes. ```typescript refreshLoad(data: RefreshLoadReq): Promise ``` ### releaseCollection Release a collection from query nodes. ```typescript releaseCollection(data: ReleaseLoadCollectionReq): Promise ``` ### getLoadingProgress Get load progress for a collection or partitions. ```typescript getLoadingProgress(data: GetLoadingProgressReq): Promise ``` ### getLoadState Get collection or partition load state. ```typescript getLoadState(data: GetLoadStateReq): Promise ``` ## Rename, truncate, and drop ### renameCollection Rename a collection and optionally move it to another database. ```typescript renameCollection(data: RenameCollectionReq): Promise ``` **Parameters**: - `collection_name`: Current collection name. - `new_collection_name`: New collection name. - `new_db_name?`: Target database name. - `db_name?`: Current database name. - `timeout?`: Request timeout in milliseconds. ### truncateCollection Delete all rows while keeping the schema. ```typescript truncateCollection(data: DropCollectionReq): Promise<{ status: ResStatus }> ``` ### dropCollection Drop a collection and all its data. ```typescript dropCollection(data: DropCollectionReq): Promise drop_collection(data: DropCollectionReq): Promise // alias ``` ## Alias operations ### createAlias ```typescript createAlias(data: CreateAliasReq): Promise ``` **Parameters**: `collection_name`, `alias`, optional `db_name`, optional `timeout`. ### describeAlias ```typescript describeAlias(data: DescribeAliasReq): Promise ``` ### listAliases ```typescript listAliases(data: ListAliasesReq): Promise ``` ### alterAlias ```typescript alterAlias(data: AlterAliasReq): Promise ``` ### dropAlias ```typescript dropAlias(data: DropAliasReq): Promise ``` ## Function operations ### alterCollectionSchema Low-level schema alteration API for atomically adding a function output field, its function schema, and optional bound index metadata. ```typescript alterCollectionSchema( data: AlterCollectionSchemaReq ): Promise ``` **Parameters**: - `collection_name`: Collection name. - `field`: Function output field schema. - `function`: Function schema. - `index_name?`: Name of the bound index. - `extra_params?`: Bound index parameters. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### addFunctionField Convenience wrapper for adding a BM25 or MinHash function output field and its bound index in one schema alteration. ```typescript addFunctionField(data: AddFunctionFieldReq): Promise ``` The output field must be `SparseFloatVector` for BM25 and `BinaryVector` for MinHash. A non-`AUTOINDEX` `index_type` is required. ```typescript await client.addFunctionField({ collection_name: 'documents', field: { name: 'minhash_vector', data_type: DataType.BinaryVector, dim: 512, is_function_output: true, }, function: { name: 'body_minhash', type: FunctionType.MINHASH, input_field_names: ['body'], output_field_names: ['minhash_vector'], params: { num_hashes: 16, shingle_size: 3 }, }, index_name: 'minhash_index', extra_params: { index_type: IndexType.MINHASH_LSH, metric_type: MetricType.MHJACCARD, params: { mh_lsh_band: 8 }, }, }); ``` ### dropFunctionField Drop a function together with its output fields and bound indexes. ```typescript dropFunctionField(data: DropFunctionFieldReq): Promise ``` ```typescript await client.dropFunctionField({ collection_name: 'documents', function_name: 'body_minhash', }); ``` ### addCollectionFunction Milvus 3.0.6 rejects this legacy method. Use `addFunctionField` to add a BM25 or MinHash function, its output field, and its index. Define text embedding functions when creating the collection. ```typescript addCollectionFunction(data: AddCollectionFunctionReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `function`: Function schema. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### alterCollectionFunction Update supported settings on an existing function, such as a text embedding function’s description. Milvus 3.0.6 rejects BM25 function alterations. ```typescript alterCollectionFunction(data: AlterCollectionFunctionReq): Promise ``` ### dropCollectionFunction Milvus 3.0.6 rejects this legacy method. Use `dropFunctionField` to remove the function, its output field, and its bound index. ```typescript dropCollectionFunction(data: DropCollectionFunctionReq): Promise ``` ## Compaction and replicas ### compact Trigger compaction. ```typescript compact(data: CompactReq): Promise ``` ### getCompactionState ```typescript getCompactionState(data: GetCompactionStateReq): Promise ``` ### getCompactionStateWithPlans ```typescript getCompactionStateWithPlans(data: GetCompactionPlansReq): Promise ``` ### getReplicas Get collection replica information. ```typescript getReplicas(data: GetReplicaReq): Promise describeReplicas(data: GetReplicaReq): Promise // alias ``` ### Primary key helpers ```typescript getPkFieldName(data: DescribeCollectionReq, desc?: DescribeCollectionResponse): Promise getPkFieldType(data: DescribeCollectionReq, desc?: DescribeCollectionResponse): Promise getPkField(data: DescribeCollectionReq): Promise ``` ## External collection refresh Milvus 3.0 ### refreshExternalCollection Trigger a refresh job for an external collection. ```typescript refreshExternalCollection(data: RefreshExternalCollectionReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `external_source?`: New external source path. - `external_spec?`: New external spec configuration. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### getRefreshExternalCollectionProgress ```typescript getRefreshExternalCollectionProgress(data: GetRefreshExternalCollectionProgressReq): Promise ``` **Parameters**: `job_id`, optional `timeout`. ### listRefreshExternalCollectionJobs ```typescript listRefreshExternalCollectionJobs(data?: ListRefreshExternalCollectionJobsReq): Promise ``` **Parameters**: optional `db_name`, `collection_name`, and `timeout`. ## Snapshots Milvus 3.0 ### createSnapshot ```typescript createSnapshot(data: CreateSnapshotReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `snapshot_name`: Snapshot name. - `description?`: Snapshot description. - `compaction_protection_seconds?`: Protection duration. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### dropSnapshot ```typescript dropSnapshot(data: DropSnapshotReq): Promise ``` ### listSnapshots ```typescript listSnapshots(data: ListSnapshotsReq): Promise ``` ### describeSnapshot ```typescript describeSnapshot(data: DescribeSnapshotReq): Promise ``` ### restoreSnapshot Restore a snapshot into a target collection. ```typescript restoreSnapshot(data: RestoreSnapshotReq): Promise ``` **Parameters**: - `snapshot_name`: Snapshot name. - `source_collection_name`: Source collection. - `target_collection_name`: Target collection. - `source_db_name?`: Source database. - `target_db_name?`: Target database. - `timeout?`: Request timeout in milliseconds. ### getRestoreSnapshotState ```typescript getRestoreSnapshotState(data: GetRestoreSnapshotStateReq): Promise ``` ### exportSnapshot, getExportSnapshotState, restoreExternalSnapshot These methods require Milvus 3.0.6 or later. Export copies a snapshot into a standalone bundle. Export state provides the bundle’s metadata URI when the job completes. External restore creates a new collection and returns a job ID for `getRestoreSnapshotState()`. ```typescript exportSnapshot(data: ExportSnapshotReq): Promise getExportSnapshotState(data: GetExportSnapshotStateReq): Promise restoreExternalSnapshot(data: RestoreExternalSnapshotReq): Promise ``` ### listRestoreSnapshotJobs ```typescript listRestoreSnapshotJobs(data?: ListRestoreSnapshotJobsReq): Promise ``` ### pinSnapshotData Pin snapshot data to protect it from garbage collection while it is copied out. ```typescript pinSnapshotData(data: PinSnapshotDataReq): Promise ``` **Parameters**: `collection_name`, `snapshot_name`, optional `ttl_seconds`, `db_name`, and `timeout`. ### unpinSnapshotData Release a snapshot data pin. ```typescript unpinSnapshotData(data: UnpinSnapshotDataReq): Promise ``` **Parameters**: `pin_id`, optional `timeout`. ## Related - [API Reference overview](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - [Collection Management guide](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/) - [Data Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/) ## Function-field backfill In SDK 3.0.4+, `addFunctionField()` returns after the schema change is accepted. Milvus asynchronously backfills existing sealed segments through schema-bump compaction. The wrapper supports BM25 → SparseFloatVector and MINHASH → BinaryVector; provide an explicit bound `index_type` other than `AUTOINDEX`. ```typescript const stats = await client.getCollectionStatistics({ collection_name: 'documents', }); if (stats.status.error_code !== ErrorCode.SUCCESS) { throw new Error(stats.status.reason); } console.log({ consistent: stats.data.schema_version_consistent_segments, total: stats.data.schema_version_total_segments, }); ``` For an existing collection with sealed segments, poll these values with a timeout until `total > 0` and `consistent === total` after numeric conversion. Missing counters do not prove completion. Also check `getIndexState({ collection_name, index_name })` reaches `Finished` (stop on `Failed`) before loading and searching the new field. Empty collections need no historical backfill. --- # Data Operations Look up Milvus Node.js SDK methods for writes, queries, vector searches, deletes, iterators, compaction, and bulk import. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/data/ ## Section links - [insert](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#insert) - [upsert](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#upsert) - [deleteEntities](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#deleteentities) - [delete](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#delete) - [query](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#query) - [Query aggregation](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#query-aggregation) - [get](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#get) - [count](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#count) - [search](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#search) - [Simple search parameters](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#simple-search-parameters) - [Search aggregation](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#search-aggregation) - [Hybrid search](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#hybrid-search) - [searchIterator](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#searchiterator) - [queryIterator](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#queryiterator) - [Flush APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#flush-apis) - [flush](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#flush) - [flushSync](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#flushsync) - [getFlushState](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#getflushstate) - [flushAll](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#flushall) - [flushAllSync](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#flushallsync) - [getFlushAllState](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#getflushallstate) - [Compaction and segment APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#compaction-and-segment-apis) - [compact](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#compact) - [getCompactionState](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#getcompactionstate) - [getQuerySegmentInfo](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#getquerysegmentinfo) - [getPersistentSegmentInfo](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#getpersistentsegmentinfo) - [Load balancing](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#load-balancing) - [loadBalance](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#loadbalance) - [Bulk import APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#bulk-import-apis) - [bulkInsert](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#bulkinsert) - [listImportTasks](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#listimporttasks) - [getImportState](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#getimportstate) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#related) Data APIs write, read, search, delete, flush, compact, and bulk-import collection data. Most request types extend `collectionNameReq`, so they accept `collection_name`, optional `db_name`, optional `timeout`, and optional request tracing fields. ## insert Insert rows into a collection. ```typescript insert(data: InsertReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `data` or `fields_data`: Array of row objects. These two fields are aliases and are mutually exclusive. - `partition_name?`: Target partition. - `hash_keys?`: Hash keys generated from primary key values. - `transformers?`: Custom transformers for `Float16Vector` or `BFloat16Vector` insert data. - `skip_check_schema?`: Skip schema validation. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript const res = await client.insert({ collection_name: 'books', data: [ { id: 1, title: 'Vector databases', embedding: [0.1, 0.2, 0.3, 0.4], category: 'database', }, ], }); ``` **Response**: ```typescript interface MutationResult { status: ResStatus; succ_index: Number[]; err_index: Number[]; acknowledged: boolean; insert_cnt: string; delete_cnt: string; upsert_cnt: string; timestamp: string; IDs: StringArrayId | NumberArrayId; } ``` ## upsert Insert or update rows by primary key. ```typescript upsert(data: UpsertReq): Promise ``` In addition to `InsertReq` fields, `UpsertReq` accepts: - `partial_update?`: Update only provided fields. - `write_condition?`: Compare the incoming and stored integer versions. See [Conditional upsert](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/#conditional-upsert) for the condition and result fields. Milvus 3.0.7 - `field_ops?`: Per-field partial update operations. Providing `field_ops` automatically enables partial update behavior. Milvus 3.0 ```typescript type FieldPartialUpdateOp = { field_name: string; op: | FieldPartialUpdateOpType.REPLACE | FieldPartialUpdateOpType.ARRAY_APPEND | FieldPartialUpdateOpType.ARRAY_REMOVE | FieldPartialUpdateOpType.PATH_REPLACE | 'REPLACE' | 'ARRAY_APPEND' | 'ARRAY_REMOVE' | 'PATH_REPLACE'; path?: string; // Required for PATH_REPLACE on Milvus 3.0.6+ }; ``` Example: ```typescript import { FieldPartialUpdateOpType } from '@zilliz/milvus2-sdk-node'; await client.upsert({ collection_name: 'books', data: [{ id: 1, tags: ['database'], scores: [0.9] }], field_ops: [ { field_name: 'tags', op: FieldPartialUpdateOpType.ARRAY_APPEND }, { field_name: 'scores', op: 'ARRAY_APPEND' }, ], }); ``` ## deleteEntities Delete rows with an explicit boolean expression. This is the lower-level delete API. ```typescript deleteEntities(data: DeleteEntitiesReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `expr` or `filter`: Boolean expression. One is required. - `exprValues?`: Template values for filter expressions. - `partition_name?`: Partition name. - `consistency_level?`: Consistency level. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ## delete Delete rows by primary keys or by filter. ```typescript delete(data: DeleteReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `ids?`: Primary key values. The SDK converts these into the correct primary-key expression. - `filter?`: Filter expression. Takes precedence over `ids`. - `expr?`: Alias for filter expression. - `exprValues?`: Template values for filter expressions. - `partition_name?`: Partition name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Examples: ```typescript await client.delete({ collection_name: 'books', ids: [1, 2, 3], }); await client.delete({ collection_name: 'books', filter: 'category == "archived"', }); ``` ## query Query rows by primary key or scalar filter. ```typescript query(data: QueryReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `ids?`: Primary key values. Converted to a primary-key `in` expression. - `expr?` / `filter?`: Scalar filter expression. - `exprValues?`: Template values for filter expressions. - `output_fields?`: Fields to return. Defaults to `['*']`. - `partition_names?`: Partition names. - `offset?`: Number of rows to skip. - `limit?`: Number of rows to return. - `group_by_fields?`: Scalar fields used to group aggregation results. - `order_by_fields?`: Sort fields, such as `'price:asc'` or `[{ field: 'price', order: 'asc' }]`. - `order_by?`: Alias for `order_by_fields`. - `params?`: Additional query parameters forwarded to Milvus. - `consistency_level?`: Consistency level. - `transformers?`: Custom transformers for vector outputs. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript const res = await client.query({ collection_name: 'books', filter: 'category == "database"', output_fields: ['id', 'title', 'category'], limit: 10, order_by_fields: 'id:asc', }); ``` ### Query aggregation Milvus 3.0 Specify aggregation expressions in `output_fields`. Use `group_by_fields` to return one row per scalar group. Supported aggregation functions are `count`, `min`, `max`, `sum`, and `avg`. ```typescript const res = await client.query({ collection_name: 'sales', filter: 'price > 0', group_by_fields: ['category'], output_fields: [ 'category', 'count(price)', 'min(price)', 'max(price)', 'sum(price)', 'avg(price)', ], limit: 20, }); for (const row of res.data) { console.log(row.category, row['count(price)'], row['avg(price)']); } ``` Without `group_by_fields`, aggregation expressions return collection-level values. Response keys use the expressions supplied in `output_fields`. **Response**: ```typescript interface QueryResults { status: ResStatus; data: Record[]; } ``` ## get Get rows by primary key. This is a convenience wrapper around `query`. ```typescript get(data: GetReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `ids`: Primary key values. - `output_fields?`: Fields to return. - `partition_names?`: Partition names. - `offset?`: Number of rows to skip. - `limit?`: Number of rows to return. - `consistency_level?`: Consistency level. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ## count Count rows matching a filter. ```typescript count(data: CountReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `expr?`: Filter expression. Defaults to all rows when omitted. - `filter?`: Alias for `expr`. - `exprValues?`: Values for placeholders in the filter expression. - `partition_names?`: Partition names to count within. - `consistency_level?`: Query consistency level (`ConsistencyLevelEnum`). - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. - `client_request_id?` / `client-request-id?`: Request ID for tracing. **Response**: - `status`: Response status. - `data`: Count as a number, or `0` when the query fails. Check `status.error_code` before using `data`. When the server rejects the query, `count()` returns the original error status and reason with `data: 0`. ## search Perform vector, text, search-by-primary-key, or hybrid search. `hybridSearch` is an alias of `search` with `HybridSearchReq`. ```typescript search(params: T): Promise> hybridSearch(data: HybridSearchReq): Promise> // alias ``` ### Simple search parameters - `collection_name`: Collection name. - `data?` / `vector?`: Query vector, text, or array of query vectors/text. - `ids?`: Primary key IDs for Search By PK. Vector data is not required when `ids` is provided. - `anns_field?`: Vector field name. Required for multi-vector collections. - `partition_names?`: Partition names. - `output_fields?`: Fields to return. - `limit?` / `topk?`: Number of hits per query. - `offset?`: Result offset. - `filter?` / `expr?`: Scalar filter. - `exprValues?`: Template values for filter expressions. - `params?`: Search params such as `nprobe`, `ef`, or `radius`. - `metric_type?`: Distance metric. - `consistency_level?`: Consistency level. - `ignore_growing?`: Ignore growing segments. - `group_by_field?`, `group_size?`, `strict_group_size?`: Grouping controls. - `order_by_fields?`: Sort fields. - `hints?`: Search hints. - `round_decimal?`: Score rounding. - `transformers?`: Custom output transformers. - `rerank?`: Reranker configuration. - `highlighter?`: Text highlight configuration. - `search_aggregation?`: Bucket aggregation configuration. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript const res = await client.search({ collection_name: 'books', data: [[0.1, 0.2, 0.3, 0.4]], anns_field: 'embedding', limit: 5, filter: 'category == "database"', output_fields: ['title', 'category'], params: { ef: 64 }, }); ``` ### Search aggregation Milvus 3.0 `search_aggregation` groups search candidates into buckets and can calculate metrics, return sorted top hits, and recursively create nested buckets. ```typescript const res = await client.search({ collection_name: 'products', anns_field: 'embedding', data: [0.1, 0.2, 0.3, 0.4], limit: 100, filter: 'in_stock == true', output_fields: ['category', 'brand', 'price'], search_aggregation: { fields: ['category'], size: 5, metrics: { item_count: { op: 'count', field_name: '*' }, average_price: { op: 'avg', field_name: 'price' }, }, order: [{ key: 'average_price', direction: 'desc' }], top_hits: { size: 2, sort: [{ field_name: 'price', direction: 'asc' }], }, sub_aggregation: { fields: ['brand'], size: 3, }, }, }); console.log(res.agg_buckets); ``` ```typescript interface SearchAggregation { fields: string[]; size: number; metrics?: Record< string, { op: 'avg' | 'sum' | 'count' | 'min' | 'max'; field_name: string } >; order?: { key: string; direction: 'asc' | 'desc' }[]; top_hits?: { size: number; sort?: { field_name: string; direction: 'asc' | 'desc' }[]; }; sub_aggregation?: SearchAggregation; } ``` A single query vector returns `AggregationBucket[]`; multiple query vectors return `AggregationBucket[][]`. Aggregation searches return their grouped data through `agg_buckets` instead of regular hit rows. Search aggregation cannot be combined with hybrid search, highlighters, `group_by_field`, `group_by_fields`, or a positive offset. Search by primary key: ```typescript const res = await client.search({ collection_name: 'books', ids: [1, 2, 3], output_fields: ['title'], }); ``` ### Hybrid search ```typescript type HybridSearchReq = { collection_name: string; data: HybridSearchSingleReq[]; rerank?: RerankerObj | FunctionObject | FunctionScore; limit?: number; output_fields?: string[]; partition_names?: string[]; filter?: string; params?: Record; }; ``` Example: ```typescript const res = await client.hybridSearch({ collection_name: 'books', data: [ { anns_field: 'dense_embedding', data: [0.1, 0.2, 0.3, 0.4], params: { ef: 64 }, }, { anns_field: 'sparse_embedding', data: { 10: 0.8, 42: 0.3 }, }, ], rerank: { strategy: 'rrf', params: { k: 60 } }, limit: 10, output_fields: ['title'], }); ``` **Search response**: Milvus 3.0 Milvus 3.0 can return element-level offsets and grouped search metadata. The SDK exposes them as `offset` and `group_by_field_values` on each result row. ```typescript interface SearchResults { status: ResStatus; results: SearchResultData[] | SearchResultData[][]; recalls: number[]; session_ts: number; collection_name: string; all_search_count?: number; agg_buckets?: AggregationBucket[] | AggregationBucket[][]; } interface SearchResultData { [fieldName: string]: any; score: number; id: string; offset?: number | string; // Milvus 3.0 element-level result offset group_by_field_values?: Record; // Milvus 3.0 grouped result metadata highlight?: HighlightResult; } ``` ## searchIterator Iterate search results by batch. ```typescript searchIterator(data: SearchIteratorReq): Promise> ``` **Parameters**: - All relevant `SearchSimpleReq` fields except `offset`, `limit`, and `topk`. - `batchSize`: Number of items to return in each batch. Values above 16384 are capped. - `limit?`: Maximum number of items to iterate. Omit for no limit. - `external_filter_fn?`: Client-side row filter. Example: ```typescript const iterator = await client.searchIterator({ collection_name: 'books', data: [0.1, 0.2, 0.3, 0.4], batchSize: 100, limit: 1000, }); for await (const batch of iterator) { console.log(batch); } ``` ## queryIterator Iterate query results by batch. ```typescript queryIterator(data: QueryIteratorReq): Promise[]>> ``` **Parameters**: - All relevant `QueryReq` fields except `ids`, `offset`, and `limit`. - `batchSize`: Number of items to return in each batch. Values above 16384 are capped. - `limit?`: Maximum number of items to iterate. Omit for no limit. Example: ```typescript const iterator = await client.queryIterator({ collection_name: 'books', filter: 'category == "database"', output_fields: ['id', 'title'], batchSize: 100, }); for await (const rows of iterator) { console.log(rows); } ``` ## Flush APIs ### flush Flush specified collections asynchronously. ```typescript flush(data: FlushReq): Promise ``` **Parameters**: - `collection_names`: Collection names. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### flushSync Flush specified collections and wait for flush completion. ```typescript flushSync(data: FlushReq): Promise ``` ### getFlushState Check flush state by segment IDs or collection/timestamp. ```typescript getFlushState(data: GetFlushStateReq): Promise ``` **Parameters**: - `segmentIDs?`: Segment IDs returned by `flush`. - `flush_ts?`: Flush timestamp. - `collection_name?`: Collection name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### flushAll Flush all collections asynchronously. ```typescript flushAll(data?: FlushAllReq): Promise ``` **Response** includes `flush_all_tss`, `flush_all_msgs`, and `cluster_info`. ### flushAllSync Flush all collections and wait for completion. ```typescript flushAllSync(data?: FlushAllReq): Promise ``` ### getFlushAllState ```typescript getFlushAllState(data: GetFlushAllStateReq): Promise ``` Use `flush_all_tss` returned by `flushAll`. ## Compaction and segment APIs ### compact Trigger compaction for a collection. ```typescript compact(data: CompactReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `timetravel?`: Timestamp boundary. - `majorCompaction?`: Request major compaction. - `partition_id?`: Target partition ID. - `channel?`: Target DML channel. - `segment_ids?`: Target segment IDs. - `l0Compaction?`: Request L0 compaction. - `target_size?`: Target segment size in bytes. - `db_name?`: Database name. ### getCompactionState ```typescript getCompactionState(data: GetCompactionStateReq): Promise ``` **Parameters**: - `compactionID`: Compaction ID returned by `compact`. - `timeout?`: Request timeout in milliseconds. ### getQuerySegmentInfo Get growing segment information from query nodes. ```typescript getQuerySegmentInfo(data: GetQuerySegmentInfoReq): Promise ``` ### getPersistentSegmentInfo Get segment information from data nodes. ```typescript getPersistentSegmentInfo(data: GePersistentSegmentInfoReq): Promise ``` ## Load balancing ### loadBalance Perform load balancing from a source query node to destination query nodes. ```typescript loadBalance(data: LoadBalanceReq): Promise ``` **Parameters**: - `src_nodeID`: Source query node ID. - `dst_nodeIDs?`: Destination query node IDs. - `sealed_segmentIDs?`: Sealed segment IDs. - `collectionName?`: Collection name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ## Bulk import APIs ### bulkInsert Import data from files. ```typescript bulkInsert(data: ImportReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `files`: File paths. - `partition_name?`: Partition name. - `channel_names?`: Channel names. - `options?`: Import options as `KeyValuePair[]`. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. **Response**: - `tasks`: Import task IDs. ### listImportTasks ```typescript listImportTasks(data: ListImportTasksReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `limit?`: Max tasks returned. `0` lists all tasks. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### getImportState ```typescript getImportState(data: GetImportStateReq): Promise ``` **Parameters**: - `task`: Import task ID. - `timeout?`: Request timeout in milliseconds. **Response** includes `state`, `row_count`, `id_list`, `infos`, `collection_id`, and `segment_ids`. ## Related - [API Reference overview](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - [Insert & Update guide](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/) - [Query & Search guide](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/) - [Index Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/) --- # Index Operations Look up TypeScript methods for creating, describing, altering, and dropping vector and scalar indexes in Milvus. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/ ## Section links - [createIndex](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#createindex) - [describeIndex](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#describeindex) - [listIndexes](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#listindexes) - [getIndexState](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#getindexstate) - [getIndexBuildProgress](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#getindexbuildprogress) - [getIndexStatistics](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#getindexstatistics) - [alterIndexProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#alterindexproperties) - [dropIndexProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#dropindexproperties) - [dropIndex](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#dropindex) - [Common index and metric enums](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#common-index-and-metric-enums) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/indexes/#related) Index APIs create, inspect, and update vector or scalar indexes. Create indexes after collection creation and before loading/searching when you need explicit index configuration. ```typescript import { IndexType, MetricType } from '@zilliz/milvus2-sdk-node'; ``` ## createIndex Create one or more indexes. ```typescript createIndex(data: CreateIndexesReq): Promise type CreateIndexesReq = CreateIndexRequest[] | CreateIndexRequest; type CreateIndexRequest = CreateIndexReq | CreateIndexSimpleReq; ``` Simple request shape: ```typescript interface CreateIndexSimpleReq { collection_name: string; field_name: string; index_type: string; metric_type?: string; index_name?: string; params?: Record; db_name?: string; timeout?: number; } ``` Legacy request shape: ```typescript interface CreateIndexReq { collection_name: string; field_name: string; index_name?: string; extra_params?: { index_type?: string; metric_type: string; params?: string; }; db_name?: string; timeout?: number; } ``` Example: ```typescript await client.createIndex({ collection_name: 'books', field_name: 'embedding', index_name: 'embedding_index', index_type: IndexType.HNSW, metric_type: MetricType.COSINE, params: { M: 16, efConstruction: 200 }, }); ``` Create multiple indexes: ```typescript await client.createIndex([ { collection_name: 'books', field_name: 'embedding', index_type: IndexType.AUTOINDEX, metric_type: MetricType.COSINE, }, { collection_name: 'books', field_name: 'title', index_name: 'title_inverted', index_type: IndexType.INVERTED, }, ]); ``` ## describeIndex Describe indexes on a collection. Filter by field or index name when needed. ```typescript describeIndex(data: DescribeIndexReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `field_name?`: Field name. - `index_name?`: Index name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. **Response**: ```typescript interface DescribeIndexResponse { status: ResStatus; index_descriptions: IndexDescription[]; } interface IndexDescription { index_name: string; indexID: number; params: KeyValuePair[]; field_name: string; indexed_rows: string; total_rows: string; state: string; index_state_fail_reason: string; pending_index_rows: string; } ``` Example: ```typescript const res = await client.describeIndex({ collection_name: 'books', index_name: 'embedding_index', }); ``` ## listIndexes List index names for a collection. ```typescript listIndexes(data: DescribeIndexReq): Promise ``` **Response**: - `status`: Response status. - `indexes`: Index names. Example: ```typescript const { indexes } = await client.listIndexes({ collection_name: 'books' }); ``` ## getIndexState Get index build state. ```typescript getIndexState(data: GetIndexStateReq): Promise ``` **Parameters** are the same as `DescribeIndexReq`. **Response**: - `status`: Response status. - `state`: `IndexState`. > This API is deprecated in some Milvus versions. Prefer `describeIndex` or `getIndexStatistics` when available. ## getIndexBuildProgress Get indexed row count and total row count while an index is building. ```typescript getIndexBuildProgress(data: GetIndexBuildProgressReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `field_name?`: Field name. - `index_name?`: Index name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. **Response**: - `indexed_rows`: Number of indexed rows. - `total_rows`: Total row count. ## getIndexStatistics Get index statistics including index state and row counts. ```typescript getIndexStatistics(data: DescribeIndexReq): Promise ``` Use this when you need the full `IndexDescription[]` structure. ## alterIndexProperties Modify mutable index properties. ```typescript alterIndexProperties(data: AlterIndexReq): Promise alterIndex(data: AlterIndexReq): Promise // deprecated alias ``` **Parameters**: - `collection_name`: Collection name. - `index_name`: Index name. - `params`: Properties to update. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.alterIndexProperties({ collection_name: 'books', index_name: 'embedding_index', params: { 'mmap.enabled': true }, }); ``` ## dropIndexProperties Remove index properties. ```typescript dropIndexProperties(data: DropIndexPropertiesReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `index_name`: Index name. - `properties`: Property keys to remove. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.dropIndexProperties({ collection_name: 'books', index_name: 'embedding_index', properties: ['mmap.enabled'], }); ``` ## dropIndex Drop an index. ```typescript dropIndex(data: DropIndexReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `field_name?`: Field name. - `index_name?`: Index name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.dropIndex({ collection_name: 'books', index_name: 'embedding_index', }); ``` ## Common index and metric enums ```typescript enum IndexType { FLAT = 'FLAT', IVF_FLAT = 'IVF_FLAT', IVF_SQ8 = 'IVF_SQ8', IVF_PQ = 'IVF_PQ', HNSW = 'HNSW', DISKANN = 'DISKANN', AUTOINDEX = 'AUTOINDEX', SPARSE_INVERTED_INDEX = 'SPARSE_INVERTED_INDEX', SPARSE_WAND = 'SPARSE_WAND', INVERTED = 'INVERTED', BITMAP = 'BITMAP', MINHASH_LSH = 'MINHASH_LSH', RTREE = 'RTREE', } enum MetricType { L2 = 'L2', IP = 'IP', COSINE = 'COSINE', HAMMING = 'HAMMING', JACCARD = 'JACCARD', BM25 = 'BM25', MAX_SIM = 'MAX_SIM', } ``` ## Related - [API Reference overview](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - [Index Management guide](https://milvus-io.github.io/milvus-sdk-node/management/index-management/) - [Collection Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/) --- # Partition Operations Look up TypeScript methods for creating, listing, loading, releasing, and dropping Milvus collection partitions. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/ ## Section links - [createPartition](https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/#createpartition) - [hasPartition](https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/#haspartition) - [listPartitions](https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/#listpartitions) - [getPartitionStatistics](https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/#getpartitionstatistics) - [loadPartitions](https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/#loadpartitions) - [loadPartitionsSync](https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/#loadpartitionssync) - [releasePartitions](https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/#releasepartitions) - [dropPartition](https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/#droppartition) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/partitions/#related) Partition APIs manage collection partitions. Use partitions to organize data within a collection and optionally load or release only selected partitions. ## createPartition Create a partition in a collection. ```typescript createPartition(data: CreatePartitionReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `partition_name`: Partition name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.createPartition({ collection_name: 'books', partition_name: 'tenant_a', }); ``` ## hasPartition Check whether a partition exists. ```typescript hasPartition(data: HasPartitionReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `partition_name`: Partition name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. **Response**: - `status`: Response status. - `value`: `true` when the partition exists. Example: ```typescript const exists = await client.hasPartition({ collection_name: 'books', partition_name: 'tenant_a', }); ``` ## listPartitions List partitions in a collection. ```typescript listPartitions(data: ShowPartitionsReq): Promise showPartitions(data: ShowPartitionsReq): Promise // alias ``` **Parameters**: - `collection_name`: Collection name. - `type?`: `ShowPartitionsType.All` or `ShowPartitionsType.Loaded`. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. **Response**: - `partition_names`: Partition names. - `partitionIDs`: Partition IDs. - `data[]`: Formatted partition info with `name`, `id`, `timestamp`, and `loadedPercentage`. Example: ```typescript const partitions = await client.listPartitions({ collection_name: 'books' }); console.log(partitions.partition_names); ``` ## getPartitionStatistics Get partition statistics. ```typescript getPartitionStatistics(data: GetPartitionStatisticsReq): Promise getPartitionStats(data: GetPartitionStatisticsReq): Promise // alias ``` **Parameters**: - `collection_name`: Collection name. - `partition_name`: Partition name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. **Response**: - `stats`: Raw key-value statistics. - `data.row_count`: Parsed row count. Example: ```typescript const stats = await client.getPartitionStatistics({ collection_name: 'books', partition_name: 'tenant_a', }); ``` ## loadPartitions Load one or more partitions into query nodes. ```typescript loadPartitions(data: LoadPartitionsReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `partition_names`: Partition names to load. - `replica_number?`: Number of replicas. - `resource_groups?`: Resource groups to load into. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.loadPartitions({ collection_name: 'books', partition_names: ['tenant_a'], replica_number: 1, }); ``` ## loadPartitionsSync Load partitions and wait until loading progress reaches 100%. ```typescript loadPartitionsSync(data: LoadPartitionsReq): Promise ``` Throws if loading fails. ## releasePartitions Release partitions from query nodes. ```typescript releasePartitions(data: ReleasePartitionsReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `partition_names`: Partition names to release. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.releasePartitions({ collection_name: 'books', partition_names: ['tenant_a'], }); ``` ## dropPartition Drop a partition and all data in it. The default partition cannot be dropped. ```typescript dropPartition(data: DropPartitionReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `partition_name`: Partition name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.dropPartition({ collection_name: 'books', partition_name: 'tenant_a', }); ``` ## Related - [API Reference overview](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - [Partition Management guide](https://milvus-io.github.io/milvus-sdk-node/management/partition-management/) - [Collection Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/) --- # Database Operations Look up request fields and return types for creating, listing, describing, altering, and dropping Milvus databases in Node.js. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/databases/ ## Section links - [createDatabase](https://milvus-io.github.io/milvus-sdk-node/api-reference/databases/#createdatabase) - [listDatabases](https://milvus-io.github.io/milvus-sdk-node/api-reference/databases/#listdatabases) - [describeDatabase](https://milvus-io.github.io/milvus-sdk-node/api-reference/databases/#describedatabase) - [alterDatabaseProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/databases/#alterdatabaseproperties) - [dropDatabaseProperties](https://milvus-io.github.io/milvus-sdk-node/api-reference/databases/#dropdatabaseproperties) - [dropDatabase](https://milvus-io.github.io/milvus-sdk-node/api-reference/databases/#dropdatabase) - [Working with database context](https://milvus-io.github.io/milvus-sdk-node/api-reference/databases/#working-with-database-context) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/databases/#related) Database APIs manage Milvus databases and database-level properties. Most collection and data APIs accept `db_name`; you can also set the active database with [`client.use`](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/#use). ## createDatabase Create a database. ```typescript createDatabase(data: CreateDatabaseRequest): Promise ``` **Parameters**: - `db_name`: Database name. - `properties?`: Database properties. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.createDatabase({ db_name: 'analytics', properties: { owner: 'recommendation-team', }, }); ``` ## listDatabases List databases. ```typescript listDatabases(data?: ListDatabasesRequest): Promise ``` **Parameters**: - `timeout?`: Request timeout in milliseconds. **Response**: ```typescript interface ListDatabasesResponse { status: ResStatus; db_names: string[]; db_ids: string[]; created_timestamp: string[]; } ``` Example: ```typescript const databases = await client.listDatabases(); console.log(databases.db_names); ``` ## describeDatabase Describe database metadata and properties. ```typescript describeDatabase(data: DescribeDatabaseRequest): Promise ``` **Parameters**: - `db_name`: Database name. - `timeout?`: Request timeout in milliseconds. **Response**: ```typescript interface DescribeDatabaseResponse { status: ResStatus; db_name: string; dbID: number; created_timestamp: number; properties: KeyValuePair[]; } ``` Example: ```typescript const db = await client.describeDatabase({ db_name: 'analytics' }); ``` ## alterDatabaseProperties Modify database properties. ```typescript alterDatabaseProperties(data: AlterDatabaseRequest): Promise alterDatabase(data: AlterDatabaseRequest): Promise // alias ``` **Parameters**: - `db_name`: Database name. - `db_id?`: Database ID. - `properties`: Properties to set. - `delete_keys?`: Property keys to delete. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.alterDatabaseProperties({ db_name: 'analytics', properties: { description: 'Analytics workloads', }, }); ``` ## dropDatabaseProperties Remove database properties by key. ```typescript dropDatabaseProperties(data: DropDatabasePropertiesRequest): Promise ``` **Parameters**: - `db_name`: Database name. - `properties`: Property names to remove. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.dropDatabaseProperties({ db_name: 'analytics', properties: ['description'], }); ``` ## dropDatabase Drop a database. ```typescript dropDatabase(data: DropDatabasesRequest): Promise ``` **Parameters**: - `db_name`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.dropDatabase({ db_name: 'analytics' }); ``` ## Working with database context ```typescript await client.createDatabase({ db_name: 'analytics' }); await client.use({ db_name: 'analytics' }); await client.createCollection({ collection_name: 'events', dimension: 128, }); ``` Alternatively pass `db_name` per request: ```typescript await client.showCollections({ db_name: 'analytics' }); ``` ## Related - [API Reference overview](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - [Database Operations guide](https://milvus-io.github.io/milvus-sdk-node/operations/database-operations/) - [User & Role Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/) --- # User & Role Operations Look up TypeScript methods for managing Milvus users and passwords, assigning roles, and granting or revoking privileges. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/ ## Section links - [User lifecycle](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#user-lifecycle) - [createUser](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#createuser) - [updateUser](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#updateuser) - [deleteUser](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#deleteuser) - [listUsers](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#listusers) - [describeUser](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#describeuser) - [Role lifecycle](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#role-lifecycle) - [createRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#createrole) - [dropRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#droprole) - [listRoles](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#listroles) - [describeRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#describerole) - [hasRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#hasrole) - [dropAllRoles](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#dropallroles) - [User-role assignment](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#user-role-assignment) - [addUserToRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#addusertorole) - [removeUserFromRole](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#removeuserfromrole) - [Legacy privilege APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#legacy-privilege-apis) - [grantPrivilege](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#grantprivilege) - [revokePrivilege](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#revokeprivilege) - [selectGrant](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#selectgrant) - [listGrants](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#listgrants) - [Privilege groups](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#privilege-groups) - [createPrivilegeGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#createprivilegegroup) - [dropPrivilegeGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#dropprivilegegroup) - [listPrivilegeGroups](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#listprivilegegroups) - [addPrivilegesToGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#addprivilegestogroup) - [removePrivilegesFromGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#removeprivilegesfromgroup) - [RBAC v2 privilege APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#rbac-v2-privilege-apis) - [grantPrivilegeV2](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#grantprivilegev2) - [revokePrivilegeV2](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#revokeprivilegev2) - [RBAC backup and restore](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#rbac-backup-and-restore) - [backupRBAC](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#backuprbac) - [restoreRBAC](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#restorerbac) - [Common RBAC types](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#common-rbac-types) - [Minimal setup flow](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#minimal-setup-flow) - [HTTP client user APIs](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#http-client-user-apis) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#related) User and role APIs manage Milvus authentication and RBAC authorization. Most methods return `ResStatus` directly or a response object with a `status` field. Check `error_code` before relying on the returned data. ```typescript import { CollectionPrivileges, GlobalPrivileges, RbacObjects, UserPrivileges, } from '@zilliz/milvus2-sdk-node'; ``` ## User lifecycle ### createUser Create a credentialed Milvus user. ```typescript createUser(data: CreateUserReq): Promise ``` **Parameters**: - `username`: User name. - `password`: User password. The SDK base64-encodes it before sending it to Milvus. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.createUser({ username: 'readonly_user', password: 'strong-password', }); ``` ### updateUser Update a user’s password. ```typescript updateUser(data: UpdateUserReq): Promise updatePassword(data: UpdateUserReq): Promise // alias ``` **Parameters**: - `username`: User name. - `oldPassword`: Current password. - `newPassword`: New password. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.updateUser({ username: 'readonly_user', oldPassword: 'strong-password', newPassword: 'new-strong-password', }); ``` ### deleteUser Delete a Milvus user. ```typescript deleteUser(data: DeleteUserReq): Promise dropUser(data: DeleteUserReq): Promise // alias ``` **Parameters**: - `username`: User name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.deleteUser({ username: 'readonly_user' }); ``` ### listUsers List credentialed users. ```typescript listUsers(data?: ListUsersReq): Promise ``` **Response**: - `status`: Response status. - `usernames`: User names. Example: ```typescript const users = await client.listUsers(); console.log(users.usernames); ``` ### describeUser Describe a user and optionally include role information. ```typescript describeUser(data: SelectUserReq): Promise selectUser(data: SelectUserReq): Promise // alias ``` **Parameters**: - `username`: User name. - `includeRoleInfo?`: Include roles assigned to the user. Defaults to `true` in the SDK. - `timeout?`: Request timeout in milliseconds. **Response**: - `status`: Response status. - `results[].user.name`: User name. - `results[].roles[].name`: Role names when role info is included. Example: ```typescript const user = await client.describeUser({ username: 'readonly_user', includeRoleInfo: true, }); ``` ## Role lifecycle ### createRole Create a role. ```typescript createRole(data: CreateRoleReq): Promise ``` **Parameters**: - `roleName`: Role name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.createRole({ roleName: 'readonly_role' }); ``` ### dropRole Drop a role. ```typescript dropRole(data: DropRoleReq): Promise ``` **Parameters**: - `roleName`: Role name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.dropRole({ roleName: 'readonly_role' }); ``` ### listRoles List roles, optionally including assigned users. ```typescript listRoles(data?: listRoleReq): Promise ``` **Parameters**: - `includeUserInfo?`: Include users assigned to each role. Defaults to `true` in the SDK. - `timeout?`: Request timeout in milliseconds. **Response**: - `status`: Response status. - `results[].role.name`: Role name. - `results[].users[].name`: User names when user info is included. Example: ```typescript const roles = await client.listRoles({ includeUserInfo: true }); ``` ### describeRole Describe one role, optionally including assigned users and grants. ```typescript describeRole(data: SelectRoleReq): Promise selectRole(data: SelectRoleReq): Promise // alias ``` **Parameters**: - `roleName`: Role name. - `includeUserInfo?`: Include users assigned to the role. Defaults to `true` in the SDK. - `timeout?`: Request timeout in milliseconds. **Response**: - `status`: Response status. - `results[].role.name`: Role name. - `results[].users[].name`: User names when user info is included. - `results[].entities`: Grants attached to the role. Example: ```typescript const role = await client.describeRole({ roleName: 'readonly_role', includeUserInfo: true, }); ``` ### hasRole Check whether a role exists. ```typescript hasRole(data: HasRoleReq): Promise ``` **Parameters**: - `roleName`: Role name. - `timeout?`: Request timeout in milliseconds. **Response**: - `status`: Response status from `listRoles()`. - `hasRole`: Whether the role exists. Example: ```typescript const { hasRole } = await client.hasRole({ roleName: 'readonly_role' }); ``` ### dropAllRoles Drop every role after revoking grants for each role. ```typescript dropAllRoles(data?: GrpcTimeOut): Promise ``` Use this only in cleanup scripts or test environments. ## User-role assignment ### addUserToRole Assign a user to a role. ```typescript addUserToRole(data: AddUserToRoleReq): Promise grantRole(data: AddUserToRoleReq): Promise // alias ``` **Parameters**: - `username`: User name. - `roleName`: Role name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.addUserToRole({ username: 'readonly_user', roleName: 'readonly_role', }); ``` ### removeUserFromRole Remove a user from a role. ```typescript removeUserFromRole(data: RemoveUserFromRoleReq): Promise revokeRole(data: RemoveUserFromRoleReq): Promise // alias ``` **Parameters**: - `username`: User name. - `roleName`: Role name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.removeUserFromRole({ username: 'readonly_user', roleName: 'readonly_role', }); ``` ## Legacy privilege APIs These methods use the legacy `OperatePrivilege` request shape. For newer Milvus deployments, prefer [RBAC v2](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/#rbac-v2-privilege-apis) when possible. ### grantPrivilege Grant a privilege to a role. ```typescript grantPrivilege(data: OperateRolePrivilegeReq): Promise grantRolePrivilege(data: OperateRolePrivilegeReq): Promise // alias ``` **Parameters**: - `roleName`: Role name. - `object`: Object type, such as `RbacObjects.Collection`, `RbacObjects.Global`, or `RbacObjects.User`. - `objectName`: Object name. Use `'*'` for all matching objects when supported by Milvus. - `privilegeName`: Privilege name, such as `CollectionPrivileges.Search` or `GlobalPrivileges.CreateCollection`. - `db_name?`: Database name for the object. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.grantPrivilege({ roleName: 'readonly_role', object: RbacObjects.Collection, objectName: 'book_embeddings', privilegeName: CollectionPrivileges.Search, }); ``` ### revokePrivilege Revoke a privilege from a role. ```typescript revokePrivilege(data: OperateRolePrivilegeReq): Promise revokeRolePrivilege(data: OperateRolePrivilegeReq): Promise // alias ``` Example: ```typescript await client.revokePrivilege({ roleName: 'readonly_role', object: RbacObjects.Collection, objectName: 'book_embeddings', privilegeName: CollectionPrivileges.Search, }); ``` ### selectGrant Get grants for one role/object pair. ```typescript selectGrant(data: SelectGrantReq): Promise listGrant(data: SelectGrantReq): Promise // alias ``` **Parameters**: - `roleName`: Role name. - `object`: Object type. - `objectName`: Object name. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. ### listGrants List grants for a role. ```typescript listGrants(data: ListGrantsReq): Promise ``` **Parameters**: - `roleName`: Role name. - `db_name?`: Database name. Defaults to `'*'` in the SDK. - `timeout?`: Request timeout in milliseconds. **Grant response shape**: ```typescript type GrantEntity = { role: { name: string }; object: { name: RbacObjects }; object_name: string; grantor: { user: { name: string }; privilege: { name: PrivilegesTypes }; }; db_name: string; }; ``` ## Privilege groups Privilege groups let you define reusable sets of privilege names. ### createPrivilegeGroup ```typescript createPrivilegeGroup(data: CreatePrivilegeGroupReq): Promise ``` **Parameters**: - `group_name`: Privilege group name. - `timeout?`: Request timeout in milliseconds. ### dropPrivilegeGroup ```typescript dropPrivilegeGroup(data: DropPrivilegeGroupReq): Promise ``` **Parameters**: - `group_name`: Privilege group name. - `timeout?`: Request timeout in milliseconds. ### listPrivilegeGroups ```typescript listPrivilegeGroups(data?: GrpcTimeOut): Promise ``` **Response**: - `status`: Response status. - `privilege_groups[].group_name`: Privilege group name. - `privilege_groups[].privileges[].name`: Privilege names in the group. ### addPrivilegesToGroup ```typescript addPrivilegesToGroup(data: AddPrivilegesToGroupReq): Promise ``` **Parameters**: - `group_name`: Privilege group name. - `privileges`: Array of privilege names. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.addPrivilegesToGroup({ group_name: 'read_only_collection', privileges: [ CollectionPrivileges.Search, CollectionPrivileges.Query, GlobalPrivileges.DescribeCollection, ], }); ``` ### removePrivilegesFromGroup ```typescript removePrivilegesFromGroup(data: RemovePrivilegesFromGroupReq): Promise ``` **Parameters**: - `group_name`: Privilege group name. - `privileges`: Array of privilege names. - `timeout?`: Request timeout in milliseconds. ## RBAC v2 privilege APIs RBAC v2 grants privileges within an explicit database and collection scope. Use `'*'` for `db_name` or `collection_name` when you intentionally want a wildcard scope and your Milvus deployment supports it. ### grantPrivilegeV2 Grant a privilege to a role in a database/collection scope. ```typescript grantPrivilegeV2(data: GrantPrivilegeV2Request): Promise ``` **Parameters**: - `role`: Role name. - `privilege`: Privilege name. - `db_name`: Database name or `'*'`. - `collection_name`: Collection name or `'*'`. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.grantPrivilegeV2({ role: 'readonly_role', privilege: CollectionPrivileges.Search, db_name: 'default', collection_name: 'book_embeddings', }); ``` ### revokePrivilegeV2 Revoke a scoped privilege from a role. ```typescript revokePrivilegeV2(data: RevokePrivilegeV2Request): Promise ``` Example: ```typescript await client.revokePrivilegeV2({ role: 'readonly_role', privilege: CollectionPrivileges.Search, db_name: 'default', collection_name: 'book_embeddings', }); ``` ## RBAC backup and restore ### backupRBAC Back up RBAC metadata. ```typescript backupRBAC(data?: BackupRBACRequest): Promise ``` **Response**: - `status`: Response status. - `RBAC_meta`: Users, roles, grants, and privilege groups. ### restoreRBAC Restore RBAC metadata returned by `backupRBAC`. ```typescript restoreRBAC(data: RestoreRBACRequest): Promise ``` **Parameters**: - `RBAC_meta`: RBAC metadata returned by `backupRBAC`. - `timeout?`: Request timeout in milliseconds. ## Common RBAC types ```typescript type RoleEntity = { name: string }; type User = { name: string }; type PrivilegeEntity = { name: PrivilegesTypes }; type RBACMeta = { users: User[]; roles: RoleEntity[]; grants: GrantEntity[]; privilege_groups: PrivelegeGroup[]; }; ``` Common object types: ```typescript enum RbacObjects { Collection = 'Collection', Global = 'Global', User = 'User', } ``` Common privilege enums: - `CollectionPrivileges`: collection-scoped privileges such as `Load`, `Search`, `Query`, `Insert`, `Upsert`, `Delete`, and `CreatePartition`. - `GlobalPrivileges`: global privileges such as `CreateCollection`, `DropCollection`, `CreateDatabase`, and `CreateResourceGroup`. - `UserPrivileges`: user privileges such as `UpdateUser` and `SelectUser`. - `PrivilegesTypes`: union of collection, global, user, and custom privilege strings. ## Minimal setup flow ```typescript await client.createUser({ username: 'readonly_user', password: 'strong-password', }); await client.createRole({ roleName: 'readonly_role' }); await client.addUserToRole({ username: 'readonly_user', roleName: 'readonly_role', }); await client.grantPrivilegeV2({ role: 'readonly_role', privilege: CollectionPrivileges.Search, db_name: 'default', collection_name: 'book_embeddings', }); ``` ## HTTP client user APIs The HTTP client exposes a smaller user-management surface: ```typescript createUser(params: HttpUserCreateReq, options?: FetchOptions): Promise updateUserPassword(params: HttpUserUpdatePasswordReq, options?: FetchOptions): Promise dropUser(params: HttpUserBaseReq, options?: FetchOptions): Promise describeUser(params: HttpUserBaseReq, options?: FetchOptions): Promise> listUsers(options?: FetchOptions): Promise> grantRoleToUser(params: HttpUserRoleReq, options?: FetchOptions): Promise revokeRoleFromUser(params: HttpUserRoleReq, options?: FetchOptions): Promise ``` ## Related - [API Reference overview](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - [User & Role Management guide](https://milvus-io.github.io/milvus-sdk-node/management/user-role-management/) - [Types & Enums](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/) --- # Resource Group Operations Look up TypeScript methods for managing Milvus query-node resource groups, inspecting capacity, and transferring nodes or replicas. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/ ## Section links - [createResourceGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#createresourcegroup) - [listResourceGroups](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#listresourcegroups) - [describeResourceGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#describeresourcegroup) - [updateResourceGroups](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#updateresourcegroups) - [transferNode](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#transfernode) - [transferReplica](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#transferreplica) - [dropResourceGroup](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#dropresourcegroup) - [dropAllResourceGroups](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#dropallresourcegroups) - [updateReplicateConfiguration](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#updatereplicateconfiguration) - [getReplicateConfiguration](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#getreplicateconfiguration) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#related) - [Replication streams and WAL recovery](https://milvus-io.github.io/milvus-sdk-node/api-reference/resource-groups/#replication-streams-and-wal-recovery) Resource group APIs manage query-node resource groups and move nodes or loaded replicas between groups. These APIs are primarily useful for Milvus cluster deployments. ## createResourceGroup Create a resource group. ```typescript createResourceGroup(data: CreateResourceGroupReq): Promise ``` **Parameters**: - `resource_group`: Resource group name. - `config?`: Resource group configuration. - `timeout?`: Request timeout in milliseconds. ```typescript type ResourceGroupConfig = { requests?: { node_num: number }; limits?: { node_num: number }; transfer_from?: { resource_group: string }[]; transfer_to?: { resource_group: string }[]; node_filter?: { node_labels: KeyValuePair[] }; }; ``` Example: ```typescript await client.createResourceGroup({ resource_group: 'rg_search', config: { requests: { node_num: 2 }, limits: { node_num: 4 }, }, }); ``` ## listResourceGroups List resource group names. ```typescript listResourceGroups(data?: GrpcTimeOut): Promise ``` **Response**: - `status`: Response status. - `resource_groups`: Resource group names. Example: ```typescript const groups = await client.listResourceGroups(); console.log(groups.resource_groups); ``` ## describeResourceGroup Describe one resource group. ```typescript describeResourceGroup(data: DescribeResourceGroupsReq): Promise ``` **Parameters**: - `resource_group`: Resource group name. - `timeout?`: Request timeout in milliseconds. **Response**: ```typescript type ResourceGroup = { name: string; capacity: number; num_available_node: number; num_loaded_replica: { [collectionName: string]: number }; num_outgoing_node: { [collectionName: string]: number }; num_incoming_node: { [collectionName: string]: number }; config?: ResourceGroupConfig; nodes?: { node_id: number; address: string; hostname: string; }[]; }; ``` Example: ```typescript const group = await client.describeResourceGroup({ resource_group: 'rg_search', }); ``` ## updateResourceGroups Update multiple resource group configurations in one request. ```typescript updateResourceGroups(data: UpdateRresourceGroupReq): Promise ``` **Parameters**: - `resource_groups`: Map from resource group name to `ResourceGroupConfig`. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.updateResourceGroups({ resource_groups: { rg_search: { requests: { node_num: 2 }, limits: { node_num: 4 }, }, }, }); ``` ## transferNode Transfer query nodes between resource groups. ```typescript transferNode(data: TransferNodeReq): Promise ``` **Parameters**: - `source_resource_group`: Source resource group. - `target_resource_group`: Target resource group. - `num_node`: Number of nodes to transfer. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.transferNode({ source_resource_group: 'rg_default', target_resource_group: 'rg_search', num_node: 1, }); ``` ## transferReplica Transfer loaded replicas for a collection between resource groups. ```typescript transferReplica(data: TransferReplicaReq): Promise ``` **Parameters**: - `collection_name`: Collection name. - `source_resource_group`: Source resource group. - `target_resource_group`: Target resource group. - `num_replica`: Number of replicas to transfer. - `db_name?`: Database name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.transferReplica({ collection_name: 'books', source_resource_group: 'rg_default', target_resource_group: 'rg_search', num_replica: 1, }); ``` ## dropResourceGroup Drop a resource group. ```typescript dropResourceGroup(data: DropResourceGroupsReq): Promise ``` **Parameters**: - `resource_group`: Resource group name. - `timeout?`: Request timeout in milliseconds. Example: ```typescript await client.dropResourceGroup({ resource_group: 'rg_search' }); ``` ## dropAllResourceGroups Drop all non-default resource groups after transferring nodes back to the default resource group. ```typescript dropAllResourceGroups(): Promise ``` Use this only in cleanup scripts or test environments. ## updateReplicateConfiguration Update cross-cluster replication configuration. ```typescript updateReplicateConfiguration(data: UpdateReplicateConfigurationReq): Promise update_replicate_configuration(data: UpdateReplicateConfigurationReq): Promise // alias ``` **Parameters**: - `clusters`: Cluster connection definitions. Required. - `cross_cluster_topology?`: Source-to-target topology entries. - `force_promote?`: Force promote the current cluster to primary. - `timeout?`: Request timeout in milliseconds. ```typescript type ReplicateCluster = { cluster_id: string; connection_param: { uri: string; token?: string; }; pchannels?: string[]; }; type CrossClusterTopology = { source_cluster_id: string; target_cluster_id: string; }; ``` Example: ```typescript await client.updateReplicateConfiguration({ clusters: [ { cluster_id: 'primary', connection_param: { uri: 'primary.example.com:19530', token: process.env.PRIMARY_TOKEN, }, }, { cluster_id: 'secondary', connection_param: { uri: 'secondary.example.com:19530', token: process.env.SECONDARY_TOKEN, }, }, ], cross_cluster_topology: [ { source_cluster_id: 'primary', target_cluster_id: 'secondary', }, ], }); ``` ## getReplicateConfiguration Get the current cross-cluster replication configuration. ```typescript getReplicateConfiguration(data?: GetReplicateConfigurationReq): Promise get_replicate_configuration(data?: GetReplicateConfigurationReq): Promise // alias ``` **Parameters**: - `timeout?`: Request timeout in milliseconds. **Response**: ```typescript interface GetReplicateConfigurationResponse extends resStatusResponse { configuration: { clusters: ReplicateCluster[]; cross_cluster_topology?: CrossClusterTopology[]; }; } ``` Example: ```typescript const config = await client.getReplicateConfiguration(); console.log(config.configuration.clusters); ``` ## Related - [API Reference overview](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - [Resource Management guide](https://milvus-io.github.io/milvus-sdk-node/management/resource-management/) - [Collection Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/) ## Replication streams and WAL recovery Use `getReplicateInfo({ target_pchannel, source_cluster_id })` to read a live or salvage checkpoint. Either checkpoint may be `null`, including on a standalone primary without a matching salvage checkpoint. Use `createReplicateStream({ cluster_id })` to open a duplex gRPC stream to the target. Write `{ replicate_message: { source_cluster_id, message } }` and read `replicate_confirmed_message_info` acknowledgements. Call `end()` once there are no more messages to send. Each stream stays on the endpoint that opened it. Use `dumpMessages({ pchannel, start_message_id, start_timetick, end_timetick })` to read WAL messages from the old primary. Pass the salvage checkpoint’s message ID and time tick as the starting position. Messages carry a binary `payload` and string `properties`. Use decimal strings for large time ticks. Both streams support `for await...of` and `cancel()`. The SDK uses its configured timeout by default. Pass `timeout: 0` to stream without a deadline. Closing the SDK closes its active streams. These RPCs were verified on Milvus 3.0.6. --- # System Operations Look up the Milvus Node.js SDK methods for health checks, server versions, metrics, analyzer tests, and analyzer file resources. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/system/ ## Section links - [getVersion](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#getversion) - [checkHealth](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#checkhealth) - [Proxy administration](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#proxy-administration) - [Client telemetry administration](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#client-telemetry-administration) - [runAnalyzer](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#runanalyzer) - [computePhraseMatchSlop](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#computephrasematchslop) - [File resources](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#file-resources) - [addFileResource](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#addfileresource) - [listFileResources](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#listfileresources) - [removeFileResource](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#removefileresource) - [getMetric](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#getmetric) - [Connection helpers](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#connection-helpers) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#related) System APIs expose connection context, server status, analyzer testing, analyzer file resources, and server metrics. ## getVersion Get the connected Milvus server version. ```typescript getVersion(): Promise ``` **Response**: ```typescript interface GetVersionResponse { version: string; } ``` Example: ```typescript const version = await client.getVersion(); console.log(version.version); ``` ## checkHealth Check Milvus server health. ```typescript checkHealth(): Promise ``` **Response**: ```typescript interface CheckHealthResponse { isHealthy: boolean; reasons: []; } ``` Example: ```typescript const health = await client.checkHealth(); if (!health.isHealthy) { console.warn('Milvus is unhealthy:', health.reasons); } ``` ## Proxy administration - `allocTimestamp()` returns a Milvus hybrid timestamp as a decimal string with the default gRPC loader settings. - `getComponentStates()` returns the proxy role, node ID, and health state. - `registerLink()` returns status from the legacy proxy link registration RPC. Millvus 3.0.6 may omit the address. - `dummy({ request_type })` sends a JSON string to the legacy diagnostic RPC and returns the server’s JSON response string. These gRPC methods accept an optional timeout in milliseconds and were verified on Milvus 3.0.6. ## Client telemetry administration Use `getClientTelemetry({ client_id, database, include_metrics })` to query server-reported client telemetry. The default gRPC loader returns counters and heartbeat timestamps as decimal strings. Use `pushClientCommand()` to queue a command. Pass `target_client_id` or `target_database` to scope delivery, and pass the payload as bytes. Use the returned `command_id` with `deleteClientCommand()` to remove the command. Milvus supports persistent `push_config` commands. Milvus 3.0.6 requires a root connection for these methods when authorization is enabled. ## runAnalyzer Test a text analyzer/tokenizer without inserting data. ```typescript runAnalyzer(data: RunAnalyzerRequest): Promise ``` **Parameters**: - `text`: Text string or array of text strings to analyze. - `analyzer_params?`: Analyzer configuration for ad-hoc analysis. - `with_detail?`: Return detailed token data. - `with_hash?`: Return token hash values. - `db_name?`: Database name when using analyzers configured on a collection field. - `collection_name?`: Collection name when using analyzers configured on a collection field. - `field_name?`: Field name when using analyzers configured on a collection field. - `analyzer_names?`: Analyzer names configured on the field. **Response**: ```typescript type AnalyzerToken = { token: string; start_offset: number; end_offset: number; position: number; position_length: number; hash: number; }; interface RunAnalyzerResponse { status: ResStatus; results: { tokens: AnalyzerToken[] }[]; } ``` Example with ad-hoc analyzer params: ```typescript const analyzed = await client.runAnalyzer({ text: ['The quick brown fox', 'jumps over Milvus'], analyzer_params: { tokenizer: 'standard', filter: ['lowercase'], }, with_detail: true, }); ``` Example using a collection field analyzer: ```typescript const analyzed = await client.runAnalyzer({ text: 'vector database search', db_name: 'default', collection_name: 'books', field_name: 'title', analyzer_names: ['default'], with_detail: true, }); ``` ## computePhraseMatchSlop Measure how far phrase terms are separated in each input text using the specified analyzer. An omitted `analyzer_params` uses Milvus’s default analyzer. The response keeps the input order and returns decimal slop strings. A nonmatch has `is_match: false` and slop `'-1'`. ```typescript const result = await client.computePhraseMatchSlop({ analyzer_params: { type: 'standard' }, query_text: 'red fox', data_texts: ['red fox', 'red swift fox', 'a fox'], }); // result.is_match is [true, true, false] // result.slops is ['0', '1', '-1'] ``` ## File resources Milvus 3.0 Register server-visible files for analyzers that use custom dictionaries or other external text resources. The `path` is resolved by Milvus storage; it is not uploaded from the Node.js process. ### addFileResource ```typescript addFileResource(data: AddFileResourceReq): Promise ``` ```typescript await client.addFileResource({ name: 'product_dictionary', path: 'analyzer-resources/product-dictionary.txt', }); ``` ### listFileResources ```typescript listFileResources( data?: ListFileResourcesReq ): Promise ``` ```typescript const result = await client.listFileResources(); for (const resource of result.resources) { console.log(resource.id, resource.name, resource.path); } ``` ### removeFileResource ```typescript removeFileResource(data: RemoveFileResourceReq): Promise ``` ```typescript await client.removeFileResource({ name: 'product_dictionary' }); ``` File resource requests accept an optional `timeout`. Removing a resource does not delete the underlying object from storage. ## getMetric Get raw Milvus metrics. ```typescript getMetric(data: GetMetricsRequest): Promise ``` **Parameters**: - `request.metric_type`: `'system_info'`, `'system_statistics'`, or `'system_log'`. - `timeout?`: Request timeout in milliseconds. **Response**: - `status`: Response status. - `component_name`: Component that returned the metrics. - `response`: Parsed JSON metrics payload. Example: ```typescript const metrics = await client.getMetric({ request: { metric_type: 'system_info' }, }); console.log(metrics.component_name, metrics.response); ``` ## Connection helpers These are available on `MilvusClient` because it extends the underlying gRPC client: ```typescript use(data?: { db_name: string }): Promise useDatabase(data?: { db_name: string }): Promise // alias closeConnection(): Promise reconnectToPrimary(): Promise ``` See [MilvusClient](https://milvus-io.github.io/milvus-sdk-node/api-reference/client/) for details. ## Related - [API Reference overview](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - [Full-Text Search](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/) - [Troubleshooting](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/) - [Types & Enums](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/) --- # BulkWriter Look up BulkWriter constructors, schemas, append and flush methods, and storage adapters for JSON or Parquet bulk files. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/bulk-writer/ ## Section links - [Exports](https://milvus-io.github.io/milvus-sdk-node/api-reference/bulk-writer/#exports) - [BulkWriter](https://milvus-io.github.io/milvus-sdk-node/api-reference/bulk-writer/#bulkwriter) - [ColumnBuffer](https://milvus-io.github.io/milvus-sdk-node/api-reference/bulk-writer/#columnbuffer) - [Formatters and storage](https://milvus-io.github.io/milvus-sdk-node/api-reference/bulk-writer/#formatters-and-storage) - [VolumeManager](https://milvus-io.github.io/milvus-sdk-node/api-reference/bulk-writer/#volumemanager) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/bulk-writer/#related) BulkWriter APIs generate Milvus-compatible JSON or Parquet files on the client side. The generated file groups can be uploaded to object storage and imported with `MilvusClient#bulkInsert` or the HTTP import APIs. ## Exports ```typescript import { BulkWriter, ColumnBuffer, JsonFormatter, LocalStorage, ParquetFormatter, VolumeManager, } from '@zilliz/milvus2-sdk-node'; ``` The package also exports the related types: ```typescript type BulkWriterOptions; type BulkWriterSchema; type FlushEvent; type Formatter; type Storage; type VolumeManagerConfig; type VolumeCreateReq; type VolumeListReq; type VolumeNameReq; type VolumeApplyReq; type VolumeResponse; ``` ## BulkWriter ```typescript new BulkWriter(options: BulkWriterOptions) ``` ```typescript interface BulkWriterOptions { schema: BulkWriterSchema; storage?: Storage; format?: 'json' | 'parquet'; chunkSize?: number; localPath?: string; } interface BulkWriterSchema { fields: FieldType[]; enable_dynamic_field?: boolean; } ``` `format` defaults to `json`, `chunkSize` defaults to 128 MB, and `storage` defaults to `LocalStorage`. | Method | Description | | --- | --- | | `append(row)` | Validate and append one row. Auto-flushes when the buffered data reaches `chunkSize`. | | `commit()` | Flush the current buffer. Does nothing when the buffer is empty. | | `close()` | Flush remaining rows and return generated file groups as `string[][]`. | | `writeFrom(source)` | Append all rows from an `AsyncIterable` and then close the writer. | | Property | Type | Description | | --- | --- | --- | | `totalRowCount` | `number` | Total appended rows. | | `bufferRowCount` | `number` | Rows currently waiting in the buffer. | | `batchFiles` | `string[][]` | Generated file groups so far. | | Event | Payload | Description | | --- | --- | --- | | `flush` | `{ files, rowCount, chunkIndex }` | Emitted after one chunk is persisted. | Example: ```typescript const writer = new BulkWriter({ schema: { fields: [ { name: 'id', data_type: DataType.Int64, is_primary_key: true }, { name: 'vector', data_type: DataType.FloatVector, dim: 128 }, ], }, format: 'parquet', localPath: './bulk-output', }); writer.on('flush', (event) => { console.log(event.chunkIndex, event.files); }); await writer.append({ id: 1, vector: embedding }); const files = await writer.close(); ``` ## ColumnBuffer `ColumnBuffer` is exported for advanced formatter or storage integrations. Most applications should use `BulkWriter` directly. ```typescript new ColumnBuffer(schema: BulkWriterSchema) ``` | Method or property | Description | | --- | --- | | `append(row)` | Append one row and return the estimated byte size added to the buffer. | | `getColumn(name)` | Return one buffered field column. | | `getColumns()` | Return all buffered columns as a `Map`. | | `getRow(index)` | Reconstruct one row from buffered column data. | | `rowCount` | Number of buffered rows. | | `dynamicRows` | Dynamic `$meta` rows when `enable_dynamic_field` is enabled. | ## Formatters and storage `JsonFormatter` and `ParquetFormatter` implement the `Formatter` interface. ```typescript interface Formatter { readonly extension: string; persist( columns: Map, dynamicCol: Record[], rowCount: number, dir: string, schema: BulkWriterSchema ): Promise; } ``` `LocalStorage` implements the `Storage` interface and returns local file paths unchanged. ```typescript interface Storage { write(localPath: string, remotePath: string): Promise; } ``` Custom storage implementations can upload files and return their remote import paths. ```typescript const writer = new BulkWriter({ schema, storage: { async write(localPath, remotePath) { await uploadToS3(localPath, remotePath); return remotePath; }, }, }); ``` ## VolumeManager `VolumeManager` manages Zilliz Cloud volumes used by cloud import workflows. ```typescript new VolumeManager(config: VolumeManagerConfig) new VolumeManager(cloudEndpoint: string, apiKey: string, fetchImpl?: typeof fetch) ``` ```typescript interface VolumeManagerConfig { cloudEndpoint: string; apiKey: string; fetch?: typeof fetch; timeout?: number; } ``` | Method | Alias | Description | | --- | --- | --- | | `createVolume(data, options?)` | `create_volume` | Create a managed or external volume. | | `listVolumes(data, options?)` | `list_volumes` | List volumes in a project. | | `describeVolume(data, options?)` | `describe_volume` | Describe a volume by name. | | `deleteVolume(data, options?)` | `delete_volume` | Delete a volume by name. | | `applyVolume(data, options?)` | `apply_volume` | Apply a path to a volume. | ```typescript const volumes = new VolumeManager({ cloudEndpoint: 'https://api.cloud.zilliz.com', apiKey: process.env.ZILLIZ_CLOUD_API_KEY, }); await volumes.createVolume({ projectId: 'proj-123', regionId: 'aws-us-west-2', volumeName: 'imports', type: 'MANAGED', }); const list = await volumes.listVolumes({ projectId: 'proj-123', pageSize: 20, }); ``` ## Related - [Bulk Writer & Import guide](https://milvus-io.github.io/milvus-sdk-node/operations/bulk-writer/) - [Data Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/) - [HttpClient](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/) --- # Types & Enums Look up Milvus Node.js SDK data types, consistency levels, error codes, and common request and response shapes. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/ ## Section links - [Common response types](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#common-response-types) - [ResStatus](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#resstatus) - [ErrorCode](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#errorcode) - [KeyValuePair](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#keyvaluepair) - [GrpcTimeOut](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#grpctimeout) - [DataType enum](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#datatype-enum) - [Scalar and vector value types](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#scalar-and-vector-value-types) - [Field and schema types](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#field-and-schema-types) - [FieldType](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#fieldtype) - [FunctionObject](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#functionobject) - [Partial update enums Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#partial-update-enums-milvus-30) - [Search and query result types](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#search-and-query-result-types) - [SearchAggregation Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#searchaggregation-milvus-30) - [QueryResults](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#queryresults) - [SearchResults](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#searchresults) - [MutationResult](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#mutationresult) - [ConsistencyLevelEnum](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#consistencylevelenum) - [Index enums](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#index-enums) - [MetricType enum](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#metrictype-enum) - [Load, compaction, and import states](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#load-compaction-and-import-states) - [RBAC enums and privilege types](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#rbac-enums-and-privilege-types) - [Related](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#related) - [Membership-filter utilities (SDK 3.0.5)](https://milvus-io.github.io/milvus-sdk-node/api-reference/types-and-enums/#membership-filter-utilities-sdk-305) This page lists common SDK types and enums used across API requests and responses. ## Common response types ### ResStatus Most mutation and management APIs either return `ResStatus` directly or include it as `response.status`. ```typescript interface ResStatus { extra_info: Record; error_code: string | number; reason: string; code?: number; retriable: boolean; detail: string; } ``` Check `error_code` against `ErrorCode.SUCCESS` before using returned data: ```typescript const status = await client.dropCollection({ collection_name: 'books' }); if (status.error_code !== ErrorCode.SUCCESS) { throw new Error(status.reason); } ``` ### ErrorCode ```typescript enum ErrorCode { SUCCESS = 'Success', IndexNotExist = 'IndexNotExist', UnexpectedError = 'UnexpectedError', EmptyCollection = 'EmptyCollection', UpsertAutoIDTrue = 'UpsertAutoIDTrue', CollectionNotExists = 'CollectionNotExists', IllegalArgument = 'IllegalArgument', RateLimit = 'RateLimit', SchemaMismatch = 'SchemaMismatch', } ``` ### KeyValuePair ```typescript interface KeyValuePair { key: T; value: U; } ``` ### GrpcTimeOut Many gRPC requests extend this type. ```typescript interface GrpcTimeOut { timeout?: number; client_request_id?: string; 'client-request-id'?: string; } ``` ## DataType enum ```typescript enum DataType { None = 0, Bool = 1, Int8 = 2, Int16 = 3, Int32 = 4, Int64 = 5, Float = 10, Double = 11, VarChar = 21, Array = 22, JSON = 23, Geometry = 24, Text = 25, Timestamptz = 26, BinaryVector = 100, FloatVector = 101, Float16Vector = 102, BFloat16Vector = 103, SparseFloatVector = 104, Int8Vector = 105, ArrayOfVector = 106, Struct = 201, } ``` ## Scalar and vector value types ```typescript type Bool = boolean; type Int8 = number; type Int16 = number; type Int32 = number; type Int64 = number; type Float = number; type Double = number; type VarChar = string; type JSON = { [key: string]: any }; type Geometry = string; type Timestamptz = string; ``` Vector aliases: ```typescript type FloatVector = number[]; type Float16Vector = number[] | Uint8Array; type BFloat16Vector = number[] | Uint8Array; type BinaryVector = number[]; type Int8Vector = number[] | Int8Array; type SparseVectorArray = (number | undefined)[]; type SparseVectorDic = { [key: string]: number }; type SparseVectorCSR = { indices: number[]; values: number[] }; type SparseVectorCOO = { index: number; value: number }[]; type SparseFloatVector = | SparseVectorArray | SparseVectorDic | SparseVectorCSR | SparseVectorCOO; ``` Row data: ```typescript import type { Array } from '@zilliz/milvus2-sdk-node'; type FieldData = | Bool | Int8 | Int16 | Int32 | Int64 | Float | Double | VarChar | JSON | Geometry | Array | VectorTypes | null | undefined; interface RowData { [fieldName: string]: FieldData; } ``` ## Field and schema types ### FieldType Used by `createCollection`, `addCollectionField`, and `addCollectionFields`. Milvus 3.0 `external_field` maps a Milvus field to a source field when creating external collections. ```typescript type FieldType = { name: string; description?: string; data_type: DataType | keyof typeof DataTypeMap; element_type?: DataType | keyof typeof DataTypeMap; is_primary_key?: boolean; is_partition_key?: boolean; is_function_output?: boolean; is_clustering_key?: boolean; type_params?: Partial>; autoID?: boolean; default_value?: number | string; nullable?: boolean; external_field?: string; fields?: FieldType[]; } & Partial>; ``` Common `TypeParamKey` values include: - `dim` - `max_length` - `max_capacity` - `analyzer_params` - `enable_analyzer` - `enable_match` - `mmap.enabled` ### FunctionObject Used for BM25, text embedding, rerank, MinHash, and other function schemas. Milvus 3.0 Collection functions can be added to or dropped from existing collections through schema alteration APIs. ```typescript type FunctionObject = { name: string; description?: string; type: FunctionType; input_field_names: string[]; output_field_names?: string[]; params: Record; }; ``` ```typescript enum FunctionType { Unknown = 0, BM25 = 1, TEXTEMBEDDING = 2, RERANK = 3, MINHASH = 4, MOLFINGERPRINT = 5, } ``` `addFunctionField()` currently provides validated convenience wrappers for `FunctionType.BM25` and `FunctionType.MINHASH` schema evolution. ## Partial update enums Milvus 3.0 `FieldPartialUpdateOpType` is used by `upsert({ field_ops })` to control partial updates. `PATH_REPLACE` requires Milvus 3.0.6 or later. ```typescript enum FieldPartialUpdateOpType { REPLACE = 0, ARRAY_APPEND = 1, ARRAY_REMOVE = 2, PATH_REPLACE = 3, } ``` ## Search and query result types ### SearchAggregation Milvus 3.0 ```typescript type AggregationMetricOp = 'avg' | 'sum' | 'count' | 'min' | 'max'; type AggregationDirection = 'asc' | 'desc'; interface SearchAggregation { fields: string[]; size: number; metrics?: Record; order?: { key: string; direction: AggregationDirection }[]; top_hits?: { size: number; sort?: { field_name: string; direction: AggregationDirection; }[]; }; sub_aggregation?: SearchAggregation; } interface AggregationBucket { key: { field_id: string | number; field_name: string; value?: unknown }[]; count: string | number; metrics: Record; hits: Record[]; sub_groups: AggregationBucket[]; } ``` ### QueryResults ```typescript interface QueryResults { status: ResStatus; data: Record[]; } ``` ### SearchResults Milvus 3.0 `offset` represents element-level result offsets, and `group_by_field_values` carries grouped search metadata when Milvus returns it. ```typescript interface SearchResults< T extends SearchReq | SearchSimpleReq | HybridSearchReq, > { status: ResStatus; results: SearchResultData[] | SearchResultData[][]; recalls: number[]; session_ts: number; collection_name: string; all_search_count?: number; agg_buckets?: AggregationBucket[] | AggregationBucket[][]; } interface SearchResultData { [fieldName: string]: any; score: number; id: string; offset?: number | string; group_by_field_values?: Record; highlight?: HighlightResult; } ``` ### MutationResult Returned by `insert`, `upsert`, and `delete`. ```typescript interface MutationResult { status: ResStatus; succ_index: Number[]; err_index: Number[]; acknowledged: boolean; insert_cnt: string; delete_cnt: string; upsert_cnt: string; timestamp: string; IDs: StringArrayId | NumberArrayId; } ``` ## ConsistencyLevelEnum ```typescript enum ConsistencyLevelEnum { Strong = 0, Session = 1, Bounded = 2, Eventually = 3, Customized = 4, } ``` Many APIs also accept string equivalents such as `'Strong'`, `'Session'`, `'Bounded'`, and `'Eventually'`. ## Index enums ```typescript enum IndexState { IndexStateNone = 0, Unissued = 1, InProgress = 2, Finished = 3, Failed = 4, } enum IndexType { FLAT = 'FLAT', IVF_FLAT = 'IVF_FLAT', IVF_SQ8 = 'IVF_SQ8', IVF_PQ = 'IVF_PQ', HNSW = 'HNSW', DISKANN = 'DISKANN', AUTOINDEX = 'AUTOINDEX', SPARSE_INVERTED_INDEX = 'SPARSE_INVERTED_INDEX', SPARSE_WAND = 'SPARSE_WAND', STL_SORT = 'STL_SORT', TRIE = 'Trie', INVERTED = 'INVERTED', BITMAP = 'BITMAP', MINHASH_LSH = 'MINHASH_LSH', RTREE = 'RTREE', HNSW_SQ = 'HNSW_SQ', HNSW_PQ = 'HNSW_PQ', HNSW_PRQ = 'HNSW_PRQ', AISAQ = 'AISAQ', NGRAM = 'NGRAM', FMINDEX = 'FMINDEX', } ``` ## MetricType enum ```typescript enum MetricType { L2 = 'L2', IP = 'IP', COSINE = 'COSINE', HAMMING = 'HAMMING', JACCARD = 'JACCARD', TANIMOTO = 'TANIMOTO', SUBSTRUCTURE = 'SUBSTRUCTURE', SUPERSTRUCTURE = 'SUPERSTRUCTURE', BM25 = 'BM25', MHJACCARD = 'MHJACCARD', MAX_SIM = 'MAX_SIM', MAX_SIM_COSINE = 'MAX_SIM_COSINE', MAX_SIM_IP = 'MAX_SIM_IP', MAX_SIM_L2 = 'MAX_SIM_L2', DTW_COSINE = 'DTW_COSINE', DTW_IP = 'DTW_IP', } ``` ## Load, compaction, and import states ```typescript enum LoadState { LoadStateNotExist = 'LoadStateNotExist', LoadStateNotLoad = 'LoadStateNotLoad', LoadStateLoading = 'LoadStateLoading', LoadStateLoaded = 'LoadStateLoaded', } enum CompactionState { UndefiedState = 0, Executing = 1, Completed = 2, } enum ImportState { ImportPending = 'ImportPending', ImportFailed = 'ImportFailed', ImportStarted = 'ImportStarted', ImportPersisted = 'ImportPersisted', ImportCompleted = 'ImportCompleted', ImportFailedAndCleaned = 'ImportFailedAndCleaned', } ``` ## RBAC enums and privilege types ```typescript enum RbacObjects { Collection = 'Collection', Global = 'Global', User = 'User', } enum Roles { ADMIN = 'admin', PUBLIC = 'public', } type PrivilegesTypes = | CollectionPrivileges | UserPrivileges | GlobalPrivileges | string; ``` See [User & Role Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/users-roles/) for RBAC methods and examples. ## Related - [API Reference overview](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - [Data Types & Schemas guide](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/) - [Data Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/) ## Membership-filter utilities (SDK 3.0.5) Package-root exports include `buildBloomFilter`, `BloomFilterBuilder`, `estimateBloomFilterSize`, the three `BLOOM_FILTER_*_FPR` constants, `buildRoaringBitmap`, `RoaringBitmapBuilder`, and the `RoaringBitmapMember` type. See [Membership Filters](https://milvus-io.github.io/milvus-sdk-node/advanced/membership-filters/) for signatures, binary `exprValues` examples, integer precision rules and approximate versus exact matching. --- # Troubleshoot Milvus SDK Errors Diagnose Milvus Node.js SDK failures involving connections, authentication, schema validation, indexes, or search. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/ ## Section links - [Frequently Asked Questions](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#frequently-asked-questions) - [Which npm package should I use with Milvus 3.0?](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#npm-package-milvus-3) - [Why does my Milvus search return no results?](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#search-returns-no-results) - [Should SDK request fields use snake_case or camelCase?](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#snake-case-vs-camelcase) - [How do I preserve Int64 primary key precision in JavaScript?](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#int64-primary-key-precision) - [Should I set endpoint or baseURL in a serverless HttpClient?](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#serverless-endpoint-vs-baseurl) - [Common Errors and Solutions](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#common-errors-and-solutions) - [CollectionNotExists](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#collectionnotexists) - [IllegalArgument](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#illegalargument) - [Connection Errors](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#connection-errors) - [Authentication Errors](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#authentication-errors) - [Schema Mismatch](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#schema-mismatch) - [Connection Issues](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#connection-issues) - [Cannot Connect to Milvus](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#cannot-connect-to-milvus) - [SSL/TLS Connection Issues](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#ssltls-connection-issues) - [Performance Issues](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#performance-issues) - [Slow Search Performance](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#slow-search-performance) - [High Memory Usage](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#high-memory-usage) - [Data Consistency Issues](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#data-consistency-issues) - [Data Not Appearing After Insert](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#data-not-appearing-after-insert) - [Inconsistent Query Results](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#inconsistent-query-results) - [Debugging Tips](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#debugging-tips) - [Enable Debug Logging](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#enable-debug-logging) - [Enable Trace](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#enable-trace) - [Use TraceID for Request Tracking](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#use-traceid-for-request-tracking) - [Check Collection Schema](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#check-collection-schema) - [Verify Data Types](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#verify-data-types) - [Log Analysis](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#log-analysis) - [Understanding Logs](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#understanding-logs) - [Common Log Messages](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#common-log-messages) - [Getting Help](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#getting-help) - [Check Documentation](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#check-documentation) - [Community Resources](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#community-resources) - [Provide Information](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#provide-information) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/#next-steps) This guide helps you troubleshoot common issues when using the Milvus Node.js SDK. ## Frequently Asked Questions ### Which npm package should I use with Milvus 3.0? Install @zilliz/milvus2-sdk-node@3. The official Milvus Node.js SDK kept its package name for Milvus 3.0. SDK 3.x also supports core operations on compatible Milvus 2.x deployments and Zilliz Cloud. ### Why does my Milvus search return no results? Make sure the collection has an index and is loaded on query nodes. In the gRPC SDK, call loadCollection with the collection name and await it so loading can finish before you search. Then check that your filter matches rows, your vector targets the right field, and your consistency level makes recent inserts visible. ### Should SDK request fields use snake_case or camelCase? Use snake_case for gRPC MilvusClient request fields such as collection_name and output_fields. Use camelCase for the equivalent REST HttpClient fields, collectionName and outputFields. ### How do I preserve Int64 primary key precision in JavaScript? Use decimal strings for Int64 primary keys that may exceed Number.MAX_SAFE_INTEGER. Keep large IDs as strings end to end. The REST HttpClient defaults to acceptInt64: false, which requests precision-preserving string IDs from Milvus. ### Should I set endpoint or baseURL in a serverless HttpClient? Set endpoint to the cluster origin, for example https://your-cluster.example.com. HttpClient appends /v2 automatically. If you override baseURL, supply the complete versioned URL ending in /v2 or Milvus REST calls can return 404. ## Common Errors and Solutions ### CollectionNotExists **Error**: `Collection my_collection does not exist` **Solutions**: - Check collection name spelling - List collections to verify: `await client.listCollections()` - Ensure you’re using the correct database ### IllegalArgument **Error**: `Invalid argument` **Solutions**: - Check parameter types and values - Verify schema matches collection definition - Ensure required fields are provided ### Connection Errors **Error**: `Connection refused` or `ECONNREFUSED` **Solutions**: - Verify Milvus server is running - Check address and port: `localhost:19530` - Check firewall settings - Verify network connectivity ### Authentication Errors **Error**: `Authentication failed` **Solutions**: - Verify username and password - Check token validity (for Zilliz Cloud) - Ensure user has necessary permissions ### Schema Mismatch **Error**: `Schema mismatch` **Solutions**: - Verify field names match schema - Check data types match field definitions - Ensure vector dimensions are correct ## Connection Issues ### Cannot Connect to Milvus **Symptoms**: Connection timeout or refused **Solutions**: 1. **Check Milvus Status**: ```bash # Check if Milvus is running docker ps | grep milvus ``` 2. **Verify Address**: ```javascript // Ensure address is correct const client = new MilvusClient({ address: 'localhost:19530', // Check host and port }); ``` 3. **Check Network**: ```javascript // Test connectivity try { await client.connectPromise; console.log('Connected successfully'); } catch (error) { console.error('Connection failed:', error); } ``` ### SSL/TLS Connection Issues **Symptoms**: SSL handshake errors **Solutions**: 1. **Verify Certificate**: ```javascript const client = new MilvusClient({ address: 'milvus.example.com:443', ssl: true, tls: { rootCertPath: '/path/to/ca.pem', // Verify path serverName: 'milvus.example.com', }, }); ``` 2. **Skip Certificate Check** (development only): ```javascript const client = new MilvusClient({ address: 'milvus.example.com:443', ssl: true, tls: { skipCertCheck: true, // Not recommended for production }, }); ``` ## Performance Issues ### Slow Search Performance **Symptoms**: Search operations are slow **Solutions**: 1. **Check Index**: ```javascript const index = await client.describeIndex({ collection_name: 'my_collection', field_name: 'vector', }); const params = index.index_descriptions[0]?.params; console.log( 'Index type:', params?.find(({ key }) => key === 'index_type')?.value ); ``` 2. **Tune Search Parameters**: ```javascript // Increase nprobe for better recall (slower) const results = await client.search({ collection_name: 'my_collection', data: [ /* vector */ ], params: { nprobe: 128, // Increase from default }, limit: 10, }); ``` 3. **Ensure Collection is Loaded**: ```javascript const state = await client.getLoadState({ collection_name: 'my_collection', }); if (state.state !== 'LoadStateLoaded') { await client.loadCollectionSync({ collection_name: 'my_collection', }); } ``` ### High Memory Usage **Symptoms**: High memory consumption **Solutions**: 1. **Release Unused Collections**: ```javascript await client.releaseCollection({ collection_name: 'unused_collection', }); ``` 2. **Use Memory-Efficient Indexes**: ```javascript // Use IVF_SQ8 or IVF_PQ instead of HNSW await client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'IVF_SQ8', // More memory-efficient metric_type: 'L2', }); ``` ## Data Consistency Issues ### Data Not Appearing After Insert **Symptoms**: Inserted data not found in queries **Solutions**: 1. **Flush After Insert**: ```javascript await client.insert({ collection_name: 'my_collection', data: [ /* ... */ ], }); // Flush to persist data await client.flush({ collection_names: ['my_collection'], }); ``` 2. **Check Collection State**: ```javascript const state = await client.getLoadState({ collection_name: 'my_collection', }); console.log('Load state:', state.state); ``` ### Inconsistent Query Results **Symptoms**: Query results vary between calls **Solutions**: 1. **Check Consistency Level**: ```javascript const info = await client.describeCollection({ collection_name: 'my_collection', }); console.log('Consistency level:', info.consistency_level); ``` 2. **Use Strong Consistency**: ```javascript await client.createCollection({ collection_name: 'my_collection', fields: schema, consistency_level: 'Strong', }); ``` ## Debugging Tips ### Enable Debug Logging ```javascript const client = new MilvusClient({ address: 'localhost:19530', logLevel: 'debug', // Enable debug logging logPrefix: 'milvus-client', }); ``` ### Enable Trace ```javascript const client = new MilvusClient({ address: 'localhost:19530', trace: true, // Enable detailed tracing }); ``` ### Use TraceID for Request Tracking Add trace IDs to track specific requests: ```javascript // Add trace ID to track requests await client.listCollections({ client_request_id: 'debug-trace-123', // Track this specific request }); // All operations support trace IDs await client.listCollections({ 'client-request-id': 'list-trace-456', }); ``` This helps correlate logs and errors with specific requests. See [Request Tracing](https://milvus-io.github.io/milvus-sdk-node/advanced/advanced-features/#request-tracing-traceid) for more details. ### Check Collection Schema ```javascript const info = await client.describeCollection({ collection_name: 'my_collection', }); console.log('Schema:', JSON.stringify(info.schema, null, 2)); ``` ### Verify Data Types ```javascript // Check field types const info = await client.describeCollection({ collection_name: 'my_collection', }); info.schema.fields.forEach((field) => { console.log(`${field.name}: ${field.data_type}`); }); ``` ## Log Analysis ### Understanding Logs ```javascript // Enable logging const client = new MilvusClient({ address: 'localhost:19530', logLevel: 'info', }); // Logs will show: // - Connection status // - Request/response details // - Error messages ``` ### Common Log Messages - **Connection established**: `Connected to Milvus` - **Collection created**: `Collection created successfully` - **Index built**: `Index build completed` - **Search executed**: `Search completed` ## Getting Help ### Check Documentation - Review [API Reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - Check [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) - Read [Examples & Tutorials](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/) ### Community Resources - [GitHub Issues](https://github.com/milvus-io/milvus-sdk-node/issues) - [Milvus Community](https://milvus.io/community) - [Discord](https://discord.gg/milvus) ### Provide Information When reporting issues, include: 1. **SDK Version**: ```javascript console.log(MilvusClient.sdkInfo); ``` 2. **Milvus Version**: Check your Milvus server version 3. **Error Details**: Full error message and stack trace 4. **Code Sample**: Minimal reproducible example 5. **Environment**: Node.js version, OS, etc. ## Next Steps - Review [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) - Check [API Reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - Explore [Examples & Tutorials](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/) --- # Migration & Compatibility Check Milvus Node.js SDK and server compatibility, review breaking changes, and plan upgrades. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/ ## Section links - [Version Compatibility](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#version-compatibility) - [SDK and Milvus Compatibility](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#sdk-and-milvus-compatibility) - [Node.js Compatibility](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#nodejs-compatibility) - [Checking Versions](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#checking-versions) - [Check SDK Version](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#check-sdk-version) - [Check Milvus Version](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#check-milvus-version) - [Migration Guides](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#migration-guides) - [Upgrading SDK Version](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#upgrading-sdk-version) - [Upgrading Milvus Version](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#upgrading-milvus-version) - [Milvus 3.0 feature coverage Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#milvus-30-feature-coverage-milvus-30) - [SDK 3.0.6–3.0.9 additions](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#sdk-306309-additions) - [SDK 3.0.4–3.0.5 additions](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#sdk-304305-additions) - [Breaking Changes](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#breaking-changes) - [Version 3.0.x Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#version-30x-milvus-30) - [Version 2.6.x](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#version-26x) - [Version 2.5.x](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#version-25x) - [Version 2.4.x](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#version-24x) - [Compatibility Matrix](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#compatibility-matrix) - [Feature Compatibility](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#feature-compatibility) - [Upgrade Paths](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#upgrade-paths) - [From v2.6.x to v3.0.x Milvus 3.0](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#from-v26x-to-v30x-milvus-30) - [From v2.3.x to v2.6.x](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#from-v23x-to-v26x) - [From v2.4.x to v2.6.x](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#from-v24x-to-v26x) - [Deprecated Features](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#deprecated-features) - [Deprecated Methods](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#deprecated-methods) - [Migration Steps](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#migration-steps) - [Best Practices for Migration](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#best-practices-for-migration) - [Getting Help](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#getting-help) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/#next-steps) SDK **3.0.11** is tested with Milvus **3.0.6**. SDK 3.x supports core operations on compatible Milvus 2.x deployments and Zilliz Cloud. Check your server version before relying on features introduced in Milvus 3.0. ## Version Compatibility ### SDK and Milvus Compatibility | Milvus version | Node SDK version | Installation | | --- | --- | --- | | v3.0.0+ | 3.0.x (3.0.11 tested with Milvus 3.0.6) | `yarn add @zilliz/milvus2-sdk-node@3` | | v2.6.0+ | v2.6.x | `yarn add @zilliz/milvus2-sdk-node@2.6` | | v2.5.0+ | v2.5.x | `yarn add @zilliz/milvus2-sdk-node@2.5.12` | | v2.4.0+ | v2.4.9 | `yarn add @zilliz/milvus2-sdk-node@2.4.9` | | v2.3.0+ | v2.3.5 | `yarn add @zilliz/milvus2-sdk-node@2.3.5` | | v2.2.0+ | v2.3.5 | `yarn add @zilliz/milvus2-sdk-node@2.3.5` | ### Node.js Compatibility - **Minimum**: Node.js 18+ - **Recommended**: A currently supported Node.js LTS release ## Checking Versions ### Check SDK Version ```javascript import { MilvusClient } from '@zilliz/milvus2-sdk-node'; console.log('SDK Version:', MilvusClient.sdkInfo.version); console.log('Recommended Milvus:', MilvusClient.sdkInfo.recommendMilvus); ``` ### Check Milvus Version ```javascript // Use Milvus API to check server version const info = await client.getMetric({ request: { metric_type: 'system_info', }, }); ``` ## Migration Guides ### Upgrading SDK Version 1. **Check Compatibility**: - Verify your Milvus version supports the new SDK version - Review breaking changes in release notes 2. **Update Package**: ```bash yarn add @zilliz/milvus2-sdk-node@latest # or specific version yarn add @zilliz/milvus2-sdk-node@2.6 ``` 3. **Test Thoroughly**: - Test all critical operations - Verify data integrity - Check performance ### Upgrading Milvus Version 1. **Backup Data**: Always backup before upgrading 2. **Check SDK Compatibility**: Ensure SDK version supports new Milvus version 3. **Update Milvus**: Follow Milvus upgrade guide 4. **Update SDK**: Update SDK to compatible version 5. **Test**: Verify all operations work correctly ## Milvus 3.0 feature coverage Milvus 3.0 The following SDK features require a Milvus 3.0 server. They are marked with the `Milvus 3.0` tag in the relevant guides and API reference pages. | Area | SDK surface | Docs | | --- | --- | --- | | External collections | `external_source`, `external_spec`, `do_physical_backfill`, `file_resource_ids`, field-level `external_field`, `refreshExternalCollection()`, `getRefreshExternalCollectionProgress()`, `listRefreshExternalCollectionJobs()` | [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/), [Collection Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/) | | Collection snapshots | `createSnapshot()`, `dropSnapshot()`, `listSnapshots()`, `describeSnapshot()`, `restoreSnapshot()`, `getRestoreSnapshotState()`, `listRestoreSnapshotJobs()`, `pinSnapshotData()`, `unpinSnapshotData()` | [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/), [Collection Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/) | | Advanced StructArray | Struct child schemas, nullable rows, dynamic nullable fields, child-field indexes, `element_filter`, element-level query/search/iterator offsets | [Data Types & Schemas](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#structarray), [Query & Search](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#structarray-element-filters) | | Query aggregation | `group_by_fields`, aggregation expressions `count`, `min`, `max`, `sum`, and `avg` in `output_fields` | [Query & Search](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#query-aggregation), [Data Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#query-aggregation) | | Search aggregation | `search_aggregation`, bucket metrics, ordering, top hits, nested aggregation, typed `agg_buckets` | [Query & Search](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-aggregation), [Data Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#search-aggregation) | | Partial array upsert | `upsert({ field_ops })`, `FieldPartialUpdateOpType.REPLACE`, `ARRAY_APPEND`, `ARRAY_REMOVE` | [Insert & Update](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/), [Data Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/) | | Element-level result metadata | Query/search result `offset`; grouped search `group_by_field_values` | [Query & Search](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/), [Data Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/) | | Schema and function management | `addCollectionField()`, `addCollectionFields()`, `dropCollectionField()`, `alterCollectionSchema()`, `addFunctionField()`, `dropFunctionField()` | [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#dynamic-schema), [Collection Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/collections/#schema-mutation) | | MinHash function and index | `FunctionType.MINHASH`, `IndexType.MINHASH_LSH`, `MetricType.MHJACCARD`, atomic function-field/index creation | [Collection Management](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#add-a-function-output-field-and-index), [Index Management](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#minhash_lsh) | | Analyzer file resources | `addFileResource()`, `listFileResources()`, `removeFileResource()` | [Full-Text Search](https://milvus-io.github.io/milvus-sdk-node/advanced/full-text-search/#custom-dictionary-files), [System Operations](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#file-resources) | ## SDK 3.0.6–3.0.9 additions - SDK 3.0.6 aligns [membership filter expressions](https://milvus-io.github.io/milvus-sdk-node/advanced/membership-filters/) with Milvus. SDK 3.0.7 fixes core client behavior and moves CI to Milvus 3.0.6. SDK 3.0.8 adds StructArray support for nested Array sub-fields. - SDK 3.0.9 adds path replacement in partial upserts, function chains for gRPC search and query, and REST search aggregation alongside gRPC search aggregation. Use `exportSnapshot()`, `getExportSnapshotState()`, and `restoreExternalSnapshot()` for portable snapshots. - The public `MilvusClient` methods for replication and WAL on Milvus 3.0.6 are `updateReplicateConfiguration()`, `getReplicateConfiguration()`, `getReplicateInfo()`, `createReplicateStream()`, and `dumpMessages()`. The SDK also exposes `computePhraseMatchSlop()` and `batchUpdateManifest()`. - The [gRPC system reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/) documents the proxy APIs `allocTimestamp()`, `getComponentStates()`, `registerLink()`, and `dummy()` and the telemetry APIs `getClientTelemetry()`, `pushClientCommand()`, and `deleteClientCommand()`. - The [REST reference](https://milvus-io.github.io/milvus-sdk-node/rest-api/) covers all Milvus 3.0.6 v2 server routes. [`HttpClient`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/) exposes the canonical SDK operations for collection changes, external refresh, snapshots, imports, access control, resource groups, text analysis, and diagnostics. Use the atomic `addFunctionField()` and `dropFunctionField()` methods for function and output-field changes. ## SDK 3.0.4–3.0.5 additions See [Release Notes](https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/) for Text fields, asynchronous function-field backfill, membership-filter builders, additional index enums and public client telemetry. ## Breaking Changes ### Version 3.0.x Milvus 3.0 - SDK 3.x targets the Milvus 3.0 proto line while keeping the public package name `@zilliz/milvus2-sdk-node`. - Milvus 3.0-only APIs require a Milvus 3.0 server; older servers may return unimplemented or unknown-field errors. - Legacy replicate/CDC proto fields are deprecated upstream. Avoid building new integrations on them. ### Version 2.6.x - Enhanced type safety - Improved error handling - New index types support ### Version 2.5.x - Updated connection pooling - Improved retry mechanisms - Enhanced logging ### Version 2.4.x - Schema validation improvements - Better error messages - Performance optimizations ## Compatibility Matrix ### Feature Compatibility | Feature | Milvus 2.2 | Milvus 2.3 | Milvus 2.4 | Milvus 2.5 | Milvus 2.6 | Milvus 3.0 | | --- | --- | --- | --- | --- | --- | --- | | Basic CRUD | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Index Types | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Dynamic Schema | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | RBAC v2 | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | | Sparse Vectors | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | | Float16/BFloat16 | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | | External Collections | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Collection Snapshots | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Partial Array Upsert | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Element-Level Result Metadata | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Advanced StructArray | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Query Aggregation | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Search Aggregation | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Schema Field Drop | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | MinHash Function | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Analyzer File Resources | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ## Upgrade Paths ### From v2.6.x to v3.0.x Milvus 3.0 1. Upgrade Milvus to 3.0 following the Milvus server upgrade guide. 2. Update the Node SDK: ```bash yarn add @zilliz/milvus2-sdk-node@latest ``` 3. If you use new 3.0 APIs, ensure your deployment is actually connected to a Milvus 3.0 server. 4. Test collection management, write paths, and query/search result parsing before production rollout. ### From v2.3.x to v2.6.x 1. Update SDK: ```bash yarn add @zilliz/milvus2-sdk-node@2.6 ``` 2. Update code (if needed): - Review API changes - Update deprecated methods - Test thoroughly ### From v2.4.x to v2.6.x 1. Update SDK: ```bash yarn add @zilliz/milvus2-sdk-node@2.6 ``` 2. Test new features: - Try new index types - Test performance improvements ## Deprecated Features ### Deprecated Methods Some methods may be deprecated in newer versions: ```javascript // Old method (deprecated) await client.alterCollection({ collection_name: 'my_collection', properties: { 'collection.ttl.seconds': 7200 }, }); // New method await client.alterCollectionProperties({ collection_name: 'my_collection', properties: { 'collection.ttl.seconds': 7200 }, }); ``` ### Migration Steps 1. Check deprecation warnings 2. Update to new methods 3. Test functionality 4. Remove old code ## Best Practices for Migration 1. **Test in Development**: Always test upgrades in development first 2. **Gradual Rollout**: Roll out upgrades gradually in production 3. **Monitor**: Monitor for errors after upgrade 4. **Rollback Plan**: Have a rollback plan ready 5. **Documentation**: Keep track of changes and configurations ## Getting Help If you encounter issues during migration: 1. Check [Troubleshooting](https://milvus-io.github.io/milvus-sdk-node/reference/troubleshooting/) 2. Review [GitHub Issues](https://github.com/milvus-io/milvus-sdk-node/issues) 3. Consult [Milvus Documentation](https://milvus.io/docs) ## Next Steps - Review [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) - Check [API Reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - Explore [Examples & Tutorials](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/) --- # Release Notes Review Milvus Node.js SDK changes by version, including new features, fixes, and server compatibility notes. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/ ## Section links - [3.0.11](https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/#3011) - [3.0.10](https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/#3010) - [3.0.9](https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/#309) - [3.0.8](https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/#308) - [3.0.7](https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/#307) - [3.0.6](https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/#306) - [3.0.5](https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/#305) - [3.0.4 additions covered here](https://milvus-io.github.io/milvus-sdk-node/reference/release-notes/#304-additions-covered-here) These docs cover **SDK 3.0.11**, tested with **Milvus 3.0.6**. Check [Migration & Compatibility](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/) for server requirements. ## 3.0.11 - [`addCollectionField()`](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#structarray) accepts `parent[child]` paths to add nullable scalar, vector, and Array children to existing StructArray fields. Fixes [#672](https://github.com/milvus-io/milvus-sdk-node/issues/672). - StructArray schema descriptions preserve the parent capacity and distinguish child nullability from parent-row nullability. Inserts preserve missing and null child positions; `PATH_REPLACE` continues to update only the supplied child. - Nullable vector children preserve element validity on writes and reads across all five dense vector types. Whole-element `PATH_REPLACE` fills omitted nullable children with null, while child-level replacement preserves other children. - Added serialized-request and real-server regression coverage, plus a required StructArray test matrix for contributors and coding agents. The target server remains Milvus **3.0.6**. Adding StructArray children and using Array children require Milvus **3.0.6+**. [Full 3.0.11 changelog](https://github.com/milvus-io/milvus-sdk-node/compare/v3.0.10...v3.0.11) ## 3.0.10 - [`count()`](https://milvus-io.github.io/milvus-sdk-node/api-reference/data/#count) returns the original server error status with `data: 0` when a query fails, instead of throwing a `TypeError`. Check `status.error_code` before using the count. Fixes [#668](https://github.com/milvus-io/milvus-sdk-node/issues/668). - `flushSync()` handles streaming flush checkpoints when segment IDs are not yet available, preserves database and timeout options while polling, and returns server failures. - `HttpClient` invokes the built-in `fetch` with the global receiver required by edge runtimes. - Updated and verified documentation examples, search metadata, Markdown mirrors, and LLM documentation bundles. The target server remains Milvus **3.0.6**. These fixes introduce no new server version requirements. [Full 3.0.10 changelog](https://github.com/milvus-io/milvus-sdk-node/compare/v3.0.9...v3.0.10) ## 3.0.9 - [Function chains](https://milvus-io.github.io/milvus-sdk-node/advanced/function-chains/) extend gRPC search, hybrid search, and query. REST search and hybrid search support `functionChains`. - [Search aggregation](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-query/#search-aggregation) is available through gRPC and [HttpClient](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#search). REST also supports search by ID, grouping, ordering, and expression parameters for query and search. - Partial upserts can [replace individual field paths](https://milvus-io.github.io/milvus-sdk-node/operations/data-operations-insert/) through gRPC and REST. - Portable snapshot workflows use `exportSnapshot`, `getExportSnapshotState`, and `restoreExternalSnapshot`. Both clients support these methods. - `MilvusClient` adds replication configuration and checkpoint APIs, duplex `createReplicateStream`, and server-streaming `dumpMessages` for WAL messages. - `MilvusClient` adds `computePhraseMatchSlop`, `batchUpdateManifest`, and [proxy and telemetry administration](https://milvus-io.github.io/milvus-sdk-node/api-reference/system/#proxy-administration) RPCs. - [HttpClient](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/) adds collection schema changes and truncation, external refresh, snapshot jobs, manual import commit/abort, resource and privilege groups, role management, analyzers, file resources, segment metadata, and quota metrics for Milvus 3.0.6. The [REST reference](https://milvus-io.github.io/milvus-sdk-node/rest-api/) covers all 113 server routes, including compatibility aliases and the two legacy standalone function routes. [Full 3.0.9 changelog](https://github.com/milvus-io/milvus-sdk-node/compare/v3.0.8...v3.0.9) ## 3.0.8 - [StructArray schemas](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#structarray) support Array sub-fields. Partial upserts preserve the StructArray’s type and schema. - The SDK pins the Milvus 3.0.6 protobuf definitions. The consolidated SDK test suite runs on pull requests. [Full 3.0.8 changelog](https://github.com/milvus-io/milvus-sdk-node/compare/v3.0.7...v3.0.8) ## 3.0.7 - Fixed VarChar primary-key escaping, count query options, typed vector insertion with dynamic fields, and score formatting for exponential notation. - Fixed sparse vector serialization, gRPC pool shutdown, and several dependency issues. CI tests against Milvus 3.0.6. [Full 3.0.7 changelog](https://github.com/milvus-io/milvus-sdk-node/compare/v3.0.6...v3.0.7) ## 3.0.6 - Aligned the documented Bloom and Roaring expressions with [`membership_match`](https://milvus-io.github.io/milvus-sdk-node/advanced/membership-filters/). - Updated YAML dependencies. [Full 3.0.6 changelog](https://github.com/milvus-io/milvus-sdk-node/compare/v3.0.5...v3.0.6) ## 3.0.5 - [Bloom and Roaring filters](https://milvus-io.github.io/milvus-sdk-node/advanced/membership-filters/): build binary membership parameters locally with `buildBloomFilter`, `BloomFilterBuilder`, `buildRoaringBitmap` and `RoaringBitmapBuilder`. - [Client telemetry](https://milvus-io.github.io/milvus-sdk-node/advanced/client-telemetry/): configure collection and heartbeat reporting, inspect effective settings, and handle server commands. Telemetry is enabled by default. - [Index enums](https://milvus-io.github.io/milvus-sdk-node/management/index-management/#additional-index-enums-in-sdk-305): `HNSW_SQ`, `HNSW_PQ`, `HNSW_PRQ`, `AISAQ`, `NGRAM` and `FMINDEX` now have `IndexType` constants. This exposes names already accepted as strings; availability depends on the server. - Dependency updates: Parquet writer dependency updated to 1.8.9; js-yaml updated. Text embedding tests switched provider; this does not change the public SDK API. [Full 3.0.5 changelog](https://github.com/milvus-io/milvus-sdk-node/compare/v3.0.4...v3.0.5) ## 3.0.4 additions covered here - [Text fields](https://milvus-io.github.io/milvus-sdk-node/core-concepts/data-types-schemas/#text): `DataType.Text`, without VarChar’s `max_length` setting; requires StorageV3. - [Function-field backfill](https://milvus-io.github.io/milvus-sdk-node/management/collection-management/#function-field-backfill): adding a BM25 or MinHash output field starts asynchronous server backfill; monitor schema and index readiness. - External collection field additions preserve `external_field` mappings. [Full 3.0.4 changelog](https://github.com/milvus-io/milvus-sdk-node/compare/v3.0.3...v3.0.4) --- # Contributing Set up the Milvus Node.js SDK development environment, run tests, submit a signed-off pull request, and build the docs site. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/reference/contributing/ ## Section links - [Develop and submit a change](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#develop-and-submit-a-change) - [Code Structure](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#code-structure) - [Directory Structure](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#directory-structure) - [Key Files](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#key-files) - [Documentation](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#documentation) - [Update Documentation](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#update-documentation) - [Documentation Structure](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#documentation-structure) - [Reporting Issues](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#reporting-issues) - [Bug Reports](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#bug-reports) - [Feature Requests](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#feature-requests) - [Code of Conduct](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#code-of-conduct) - [Getting Help](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#getting-help) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#next-steps) - [Build and preview the documentation site](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/#build-and-preview-the-documentation-site) Thank you for your interest in contributing to the Milvus Node.js SDK! ## Develop and submit a change Use the [repository contribution guide](https://github.com/milvus-io/milvus-sdk-node/blob/main/CONTRIBUTING.md) for development setup, test commands, and the pull request process. It explains how to install the locked dependencies, initialize the pinned protobuf sources, and sign off each commit for DCO. For SDK changes, run the relevant tests under `test2/` and report the results in your pull request. The [test suite guide](https://github.com/milvus-io/milvus-sdk-node/blob/main/test2/README.md) covers unit tests, server-backed tests, the npm package lifecycle, and the coverage gate. ## Code Structure ### Directory Structure ```plaintext milvus-sdk-node/ ├── milvus/ # Main SDK code │ ├── grpc/ # gRPC client │ ├── http/ # HTTP client │ ├── types/ # TypeScript types │ └── utils/ # Utilities ├── test2/ # Tests ├── benchmarks/ # Manual performance benchmarks ├── examples/ # Examples └── docs/ # Documentation ``` ### Key Files - `milvus/MilvusClient.ts`: Main client class - `milvus/grpc/`: gRPC implementation - `milvus/http/`: HTTP implementation - `milvus/types/`: TypeScript type definitions ## Documentation ### Update Documentation When adding features: 1. Update relevant documentation files 2. Add code examples 3. Update API reference if needed ### Documentation Structure - `docs/src/content/docs/`: Documentation source files - Use MDX format - Include code examples ## Reporting Issues ### Bug Reports Include: - SDK version - Node.js version - Steps to reproduce - Expected vs actual behavior - Error messages/logs ### Feature Requests Include: - Use case description - Proposed solution - Benefits ## Code of Conduct Please follow the [Code of Conduct](https://github.com/milvus-io/milvus-sdk-node/blob/main/CODE_OF_CONDUCT.md). ## Getting Help - [GitHub Issues](https://github.com/milvus-io/milvus-sdk-node/issues) - [Discussions](https://github.com/milvus-io/milvus-sdk-node/discussions) - [Milvus Community](https://milvus.io/community) ## Next Steps - Read [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) - Check [API Reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - Explore [Examples & Tutorials](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/) ## Build and preview the documentation site Install the documentation dependencies separately from SDK dependencies: ```bash yarn --cwd docs install --frozen-lockfile npm run doc npm run doc:dev ``` The site uses Astro/Starlight and writes production output to `docs/out/`. Edit MDX under `docs/src/content/docs/`; `npm run doc` preserves these source files. For production preview, run `npm --prefix docs run preview` after building. Use Node.js 22.23.4 or newer for the current locked Astro version; the documentation toolchain can require a newer runtime than the SDK. The production build checks internal links and heading fragments against the generated pages and verifies canonical URLs, metadata, and the sitemap. When releasing, compare the published tag with the last documented version, update guides and API reference, add release notes, and synchronize README compatibility and `llms.txt`. Verify example imports against package exports. --- # Additional Resources Find official Milvus and Zilliz Cloud docs, Node.js SDK resources, examples, and community support. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/ ## Section links - [Official Documentation](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#official-documentation) - [Milvus Documentation](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#milvus-documentation) - [SDK Documentation](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#sdk-documentation) - [Community Resources](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#community-resources) - [Forums and Discussions](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#forums-and-discussions) - [Social Media](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#social-media) - [Related Tools](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#related-tools) - [Attu - GUI for Milvus](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#attu---gui-for-milvus) - [Feder - Index Visualization](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#feder---index-visualization) - [Learning Resources](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#learning-resources) - [Tutorials](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#tutorials) - [Blog Posts](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#blog-posts) - [Videos](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#videos) - [Support Channels](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#support-channels) - [GitHub](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#github) - [Discord](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#discord) - [Email](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#email) - [Examples and Code Samples](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#examples-and-code-samples) - [Official Examples](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#official-examples) - [Use Cases](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#use-cases) - [API References](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#api-references) - [Milvus API](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#milvus-api) - [SDK API](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#sdk-api) - [Version Information](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#version-information) - [SDK Versions](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#sdk-versions) - [Compatibility](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#compatibility) - [Contributing](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#contributing) - [How to Contribute](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#how-to-contribute) - [Code of Conduct](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#code-of-conduct) - [License](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#license) - [Stay Updated](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#stay-updated) - [Release Notifications](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#release-notifications) - [Changelog](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#changelog) - [Next Steps](https://milvus-io.github.io/milvus-sdk-node/reference/additional-resources/#next-steps) Useful resources for learning more about Milvus and the Node.js SDK. ## Official Documentation ### Milvus Documentation - [Milvus Official Website](https://milvus.io/) - [Milvus Documentation](https://milvus.io/docs) - [Milvus API Reference](https://milvus.io/api-reference) ### SDK Documentation - [Milvus Node.js SDK GitHub](https://github.com/milvus-io/milvus-sdk-node) - [NPM Package](https://www.npmjs.com/package/@zilliz/milvus2-sdk-node) ## Community Resources ### Forums and Discussions - [GitHub Discussions](https://github.com/milvus-io/milvus-sdk-node/discussions) - [Milvus Forum](https://milvus.io/community) - [Stack Overflow](https://stackoverflow.com/questions/tagged/milvus) ### Social Media - [Milvus Twitter](https://twitter.com/milvusio) - [Milvus LinkedIn](https://www.linkedin.com/company/milvus-io) ## Related Tools ### Attu - GUI for Milvus [Attu](https://github.com/zilliztech/attu) is a modern GUI for managing Milvus: - Visual collection management - Data browsing and editing - Query and search interface - Performance monitoring ### Feder - Index Visualization [Feder](https://github.com/zilliztech/feder) visualizes ANN indexes: - Index structure visualization - Performance analysis - Index optimization tools ## Learning Resources ### Tutorials - [Milvus Tutorials](https://milvus.io/tutorials) - [Vector Database Guide](https://milvus.io/learn) ### Blog Posts - [Milvus Blog](https://milvus.io/blog) - Technical articles and use cases ### Videos - [Milvus YouTube Channel](https://www.youtube.com/@milvusio) - Tutorial videos and webinars ## Support Channels ### GitHub - [Issues](https://github.com/milvus-io/milvus-sdk-node/issues): Report bugs and request features - [Pull Requests](https://github.com/milvus-io/milvus-sdk-node/pulls): Contribute code ### Discord - [Milvus Discord](https://discord.gg/milvus): Real-time community support ### Email - Contact support through official channels ## Examples and Code Samples ### Official Examples - [SDK Examples](https://github.com/milvus-io/milvus-sdk-node/tree/main/examples) - [Next.js Example](https://github.com/milvus-io/milvus-sdk-node/tree/main/examples/nextjs) - [LangChain Example](https://github.com/milvus-io/milvus-sdk-node/tree/main/examples/LangChain) ### Use Cases - [Milvus Use Cases](https://milvus.io/use-cases) - Real-world applications and examples ## API References ### Milvus API - [Milvus gRPC API](https://milvus.io/api-reference) - [Milvus REST API](https://milvus.io/api-reference/restful) ### SDK API - [Node.js SDK API Reference](https://milvus-io.github.io/milvus-sdk-node/api-reference/) - Complete method documentation ## Version Information ### SDK Versions - Check [NPM](https://www.npmjs.com/package/@zilliz/milvus2-sdk-node) for all versions - Review [Release Notes](https://github.com/milvus-io/milvus-sdk-node/releases) ### Compatibility - [Version Compatibility](https://milvus-io.github.io/milvus-sdk-node/reference/migration-compatibility/) - Compatibility matrix and migration guides ## Contributing ### How to Contribute - [Contributing Guide](https://milvus-io.github.io/milvus-sdk-node/reference/contributing/) - Development setup and guidelines ### Code of Conduct - [Code of Conduct](https://github.com/milvus-io/milvus-sdk-node/blob/main/CODE_OF_CONDUCT.md) ## License - [Apache 2.0 License](https://github.com/milvus-io/milvus-sdk-node/blob/main/LICENSE) ## Stay Updated ### Release Notifications - Watch the GitHub repository for releases - Subscribe to Milvus newsletter ### Changelog - Review [CHANGELOG](https://github.com/milvus-io/milvus-sdk-node/blob/main/CHANGELOG.md) for updates ## Next Steps - Explore [Getting Started](https://milvus-io.github.io/milvus-sdk-node/getting-started/getting-started/) - Read [Best Practices](https://milvus-io.github.io/milvus-sdk-node/advanced/best-practices/) - Check [Examples & Tutorials](https://milvus-io.github.io/milvus-sdk-node/getting-started/examples-tutorials/) --- # Milvus REST API Browse the Milvus REST v2 API and send requests directly to your cluster. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/ ## Section links - [Entities & search](https://milvus-io.github.io/milvus-sdk-node/rest-api/#entities) - [Collections](https://milvus-io.github.io/milvus-sdk-node/rest-api/#collections) - [Fields & functions](https://milvus-io.github.io/milvus-sdk-node/rest-api/#schema) - [Indexes](https://milvus-io.github.io/milvus-sdk-node/rest-api/#indexes) - [Partitions](https://milvus-io.github.io/milvus-sdk-node/rest-api/#partitions) - [Databases](https://milvus-io.github.io/milvus-sdk-node/rest-api/#databases) - [Collection aliases](https://milvus-io.github.io/milvus-sdk-node/rest-api/#aliases) - [Bulk import](https://milvus-io.github.io/milvus-sdk-node/rest-api/#import-jobs) - [External collections](https://milvus-io.github.io/milvus-sdk-node/rest-api/#external-collections) - [Collection snapshots](https://milvus-io.github.io/milvus-sdk-node/rest-api/#snapshots) - [Snapshot jobs](https://milvus-io.github.io/milvus-sdk-node/rest-api/#snapshot-jobs) - [Users](https://milvus-io.github.io/milvus-sdk-node/rest-api/#users) - [Roles & grants](https://milvus-io.github.io/milvus-sdk-node/rest-api/#roles) - [Privilege groups](https://milvus-io.github.io/milvus-sdk-node/rest-api/#privilege-groups) - [Resource groups](https://milvus-io.github.io/milvus-sdk-node/rest-api/#resource-groups) - [Text analysis & files](https://milvus-io.github.io/milvus-sdk-node/rest-api/#text-analysis) - [Diagnostics](https://milvus-io.github.io/milvus-sdk-node/rest-api/#diagnostics) Browse 113 operations in 17 categories for Milvus 3.0.7. Open an operation to inspect its parameters and send a request to your cluster. ## Entities & search - [Insert entities](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/insert/) `/v2/vectordb/entities/insert` - [Upsert entities](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/upsert/) `/v2/vectordb/entities/upsert` - [Get by ID](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/get/) `/v2/vectordb/entities/get` - [Query entities](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/query/) `/v2/vectordb/entities/query` - [Search vectors](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/search/) `/v2/vectordb/entities/search` - [Hybrid search](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/hybrid-search/) `/v2/vectordb/entities/hybrid_search` - [Advanced search (alias)](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/advanced-search/) `/v2/vectordb/entities/advanced_search` - [Delete entities](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/delete/) `/v2/vectordb/entities/delete` ## Collections - [List collections](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/list/) `/v2/vectordb/collections/list` - [Create collection](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/create/) `/v2/vectordb/collections/create` - [Check collection existence](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/has/) `/v2/vectordb/collections/has` - [Describe collection](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/describe/) `/v2/vectordb/collections/describe` - [Collection statistics](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-stats/) `/v2/vectordb/collections/get_stats` - [Load collection](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/load/) `/v2/vectordb/collections/load` - [Get load state](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-load-state/) `/v2/vectordb/collections/get_load_state` - [Refresh loaded data](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/refresh-load/) `/v2/vectordb/collections/refresh_load` - [Release collection](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/release/) `/v2/vectordb/collections/release` - [Rename collection](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/rename/) `/v2/vectordb/collections/rename` - [Set properties](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/alter-properties/) `/v2/vectordb/collections/alter_properties` - [Remove properties](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop-properties/) `/v2/vectordb/collections/drop_properties` - [Flush collection](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/flush/) `/v2/vectordb/collections/flush` - [Start compaction](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/compact/) `/v2/vectordb/collections/compact` - [Get compaction state](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-compaction-state/) `/v2/vectordb/collections/get_compaction_state` - [Truncate collection](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/truncate/) `/v2/vectordb/collections/truncate` - [Drop collection](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop/) `/v2/vectordb/collections/drop` ## Fields & functions - [Add field](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/add/) `/v2/vectordb/collections/fields/add` - [Add struct field](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/struct-fields/add/) `/v2/vectordb/collections/struct_fields/add` - [Set field properties](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/alter-properties/) `/v2/vectordb/collections/fields/alter_properties` - [Drop field](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/drop/) `/v2/vectordb/collections/fields/drop` - [Add function (legacy)](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function/) `/v2/vectordb/collections/add_function` - [Alter function](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/alter-function/) `/v2/vectordb/collections/alter_function` - [Drop function (legacy)](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function/) `/v2/vectordb/collections/drop_function` - [Add function and field](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function-field/) `/v2/vectordb/collections/add_function_field` - [Drop function and field](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function-field/) `/v2/vectordb/collections/drop_function_field` ## Indexes - [List indexes](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/list/) `/v2/vectordb/indexes/list` - [Create index](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/create/) `/v2/vectordb/indexes/create` - [Describe index](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/describe/) `/v2/vectordb/indexes/describe` - [Set index properties](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/alter-properties/) `/v2/vectordb/indexes/alter_properties` - [Remove index properties](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop-properties/) `/v2/vectordb/indexes/drop_properties` - [Drop index](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop/) `/v2/vectordb/indexes/drop` ## Partitions - [List partitions](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/list/) `/v2/vectordb/partitions/list` - [Create partition](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/create/) `/v2/vectordb/partitions/create` - [Check partition existence](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/has/) `/v2/vectordb/partitions/has` - [Partition statistics](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/get-stats/) `/v2/vectordb/partitions/get_stats` - [Load partitions](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/load/) `/v2/vectordb/partitions/load` - [Release partitions](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/release/) `/v2/vectordb/partitions/release` - [Drop partition](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/drop/) `/v2/vectordb/partitions/drop` ## Databases - [List databases](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/list/) `/v2/vectordb/databases/list` - [Create database](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/create/) `/v2/vectordb/databases/create` - [Describe database](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/describe/) `/v2/vectordb/databases/describe` - [Set database properties](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter-properties/) `/v2/vectordb/databases/alter_properties` - [Alter database](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter/) `/v2/vectordb/databases/alter` - [Remove database properties](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop-properties/) `/v2/vectordb/databases/drop_properties` - [Drop database](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop/) `/v2/vectordb/databases/drop` ## Collection aliases - [List aliases](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/list/) `/v2/vectordb/aliases/list` - [Create alias](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/create/) `/v2/vectordb/aliases/create` - [Describe alias](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/describe/) `/v2/vectordb/aliases/describe` - [Reassign alias](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/alter/) `/v2/vectordb/aliases/alter` - [Drop alias](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/drop/) `/v2/vectordb/aliases/drop` ## Bulk import - [Start import](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/create/) `/v2/vectordb/jobs/import/create` - [List import jobs](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/list/) `/v2/vectordb/jobs/import/list` - [Describe import job](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/describe/) `/v2/vectordb/jobs/import/describe` - [Get progress (legacy)](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/get-progress/) `/v2/vectordb/jobs/import/get_progress` - [Commit import](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/commit/) `/v2/vectordb/jobs/import/commit` - [Abort import](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/abort/) `/v2/vectordb/jobs/import/abort` ## External collections - [Refresh external collection](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/refresh/) `/v2/vectordb/jobs/external_collection/refresh` - [List refresh jobs](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/list/) `/v2/vectordb/jobs/external_collection/list` - [Describe refresh job](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/describe/) `/v2/vectordb/jobs/external_collection/describe` ## Collection snapshots - [Create snapshot](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/create/) `/v2/vectordb/snapshots/create` - [List snapshots](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/list/) `/v2/vectordb/snapshots/list` - [Describe snapshot](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/describe/) `/v2/vectordb/snapshots/describe` - [Restore snapshot](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/restore/) `/v2/vectordb/snapshots/restore` - [Pin snapshot data](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/pin/) `/v2/vectordb/snapshots/pin` - [Unpin snapshot data](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/unpin/) `/v2/vectordb/snapshots/unpin` - [Drop snapshot](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/drop/) `/v2/vectordb/snapshots/drop` ## Snapshot jobs - [List restore jobs](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/list/) `/v2/vectordb/jobs/snapshot/list` - [Describe restore job](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/describe/) `/v2/vectordb/jobs/snapshot/describe` - [Export snapshot](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/) `/v2/vectordb/jobs/snapshot/export` - [Describe export job](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/describe/) `/v2/vectordb/jobs/snapshot/export/describe` - [Restore external snapshot](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/restore-external/) `/v2/vectordb/jobs/snapshot/restore_external` ## Users - [List users](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/list/) `/v2/vectordb/users/list` - [Create user](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/create/) `/v2/vectordb/users/create` - [Describe user](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/describe/) `/v2/vectordb/users/describe` - [Update user](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/update-password/) `/v2/vectordb/users/update_password` - [Assign role](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/grant-role/) `/v2/vectordb/users/grant_role` - [Revoke role](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/revoke-role/) `/v2/vectordb/users/revoke_role` - [Drop user](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/drop/) `/v2/vectordb/users/drop` ## Roles & grants - [List roles](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/list/) `/v2/vectordb/roles/list` - [Create role](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/create/) `/v2/vectordb/roles/create` - [Describe role](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/describe/) `/v2/vectordb/roles/describe` - [Alter role](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/alter/) `/v2/vectordb/roles/alter` - [Grant privilege](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege-v2/) `/v2/vectordb/roles/grant_privilege_v2` - [Revoke privilege](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege-v2/) `/v2/vectordb/roles/revoke_privilege_v2` - [Grant on object (legacy)](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege/) `/v2/vectordb/roles/grant_privilege` - [Revoke on object (legacy)](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege/) `/v2/vectordb/roles/revoke_privilege` - [Drop role](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/drop/) `/v2/vectordb/roles/drop` ## Privilege groups - [List privilege groups](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/list/) `/v2/vectordb/privilege_groups/list` - [Create privilege group](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/create/) `/v2/vectordb/privilege_groups/create` - [Add privileges](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/add-privileges-to-group/) `/v2/vectordb/privilege_groups/add_privileges_to_group` - [Remove privileges](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/remove-privileges-from-group/) `/v2/vectordb/privilege_groups/remove_privileges_from_group` - [Drop privilege group](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/drop/) `/v2/vectordb/privilege_groups/drop` ## Resource groups - [List resource groups](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/list/) `/v2/vectordb/resource_groups/list` - [Create resource group](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/create/) `/v2/vectordb/resource_groups/create` - [Describe resource group](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/describe/) `/v2/vectordb/resource_groups/describe` - [Update resource groups](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/alter/) `/v2/vectordb/resource_groups/alter` - [Transfer replicas](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/transfer-replica/) `/v2/vectordb/resource_groups/transfer_replica` - [Drop resource group](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/drop/) `/v2/vectordb/resource_groups/drop` ## Text analysis & files - [Run text analyzer](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/common/run-analyzer/) `/v2/vectordb/common/run_analyzer` - [Register file resource](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/add/) `/v2/vectordb/file_resources/add` - [List file resources](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/list/) `/v2/vectordb/file_resources/list` - [Remove file resource](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/remove/) `/v2/vectordb/file_resources/remove` ## Diagnostics - [Describe segments](https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/segments/describe/) `/v2/vectordb/segments/describe` - [Describe quota metrics](https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/quotacenter/describe/) `/v2/vectordb/quotacenter/describe` --- # Insert entities Write rows to a collection. Each row must satisfy its schema, including vector dimensions. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/insert/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/insert/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/insert/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/insert/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/insert/#request-fields) `POST /v2/vectordb/entities/insert` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/entities/insert' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "data": [ { "id": 101, "title": "Invisible Cities", "vector": [ 0.1, 0.2, 0.3, 0.4 ] } ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "data": [ { "id": 101, "title": "Invisible Cities", "vector": [ 0.1, 0.2, 0.3, 0.4 ] } ] } ``` ## Sample response ```json { "code": 0, "data": { "insertCount": 1, "insertIds": [ 101 ] }, "cost": 0 } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionName` string Name of the partition. - `data` array of object (required) Array of entity objects keyed by field name. See [`HttpClient.insert`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#insert) for the Node.js SDK method. --- # Upsert entities Insert new rows or replace rows with matching primary keys. Use partialUpdate to update selected fields. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/upsert/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/upsert/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/upsert/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/upsert/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/upsert/#request-fields) `POST /v2/vectordb/entities/upsert` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/entities/upsert' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "data": [ { "id": 101, "title": "Invisible Cities", "vector": [ 0.1, 0.2, 0.3, 0.4 ] } ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "data": [ { "id": 101, "title": "Invisible Cities", "vector": [ 0.1, 0.2, 0.3, 0.4 ] } ] } ``` ## Sample response ```json { "code": 0, "data": { "upsertCount": 1, "upsertIds": [ 101 ] }, "cost": 0 } ``` ## Request fields - `writeCondition` object Compare an integer version field using gt or gte. onMissing accepts insert (default), skip or error. Requires Milvus 3.0.7+ on every proxy. - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionName` string Name of the partition. - `data` array of object (required) Array of entity objects keyed by field name. - `partialUpdate` boolean Update only the provided fields of existing entities. - `fieldOps` array of object Per-field operations for a partial upsert, such as appending array elements. See [`HttpClient.upsert`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#upsert) for the Node.js SDK method. --- # Get by ID Fetch one or more entities by primary key from a loaded collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/get/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/get/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/get/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/get/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/get/#request-fields) `POST /v2/vectordb/entities/get` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/entities/get' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "id": [ 101 ], "outputFields": [ "title" ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "id": [ 101 ], "outputFields": [ "title" ] } ``` ## Sample response ```json { "code": 0, "data": [ { "id": 101, "title": "Invisible Cities" } ], "cost": 0 } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionName` string Name of the partition. - `partitionNames` array of string Names of the partitions to target. - `outputFields` array of string Field names to include in the returned entities. - `id` JSON value (required) Primary key or array of primary keys, matching the collection schema. - `consistencyLevel` string Read consistency level, such as Strong, Session, or Bounded. See [`HttpClient.get`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#get) for the Node.js SDK method. --- # Query entities Read rows matching a scalar filter. Supply a limit when reading without a filter. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/query/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/query/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/query/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/query/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/query/#request-fields) `POST /v2/vectordb/entities/query` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/entities/query' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "outputFields": [ "title" ], "limit": 5 }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "outputFields": [ "title" ], "limit": 5 } ``` ## Sample response ```json { "code": 0, "data": [ { "id": 101, "title": "Invisible Cities" } ], "cost": 0 } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionNames` array of string Names of the partitions to target. - `outputFields` array of string Field names to include in the returned entities. - `filter` string Milvus scalar filter expression. - `limit` integer Maximum number of rows or hits per query input. - `offset` integer Number of matching results to skip. - `orderByFields` array of string Field ordering expressions for sorted results. - `groupByFields` array of string Fields used to group query results. - `exprParams` object Values for placeholders in a filter expression. - `consistencyLevel` string Read consistency level, such as Strong, Session, or Bounded. See [`HttpClient.query`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#query) for the Node.js SDK method. --- # Search vectors Find nearest neighbors in a loaded collection. Provide query data or existing primary keys and select a vector field when needed. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/search/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/search/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/search/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/search/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/search/#request-fields) `POST /v2/vectordb/entities/search` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/entities/search' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "data": [ [ 0.1, 0.2, 0.3, 0.4 ] ], "annsField": "vector", "limit": 5, "outputFields": [ "title" ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "data": [ [ 0.1, 0.2, 0.3, 0.4 ] ], "annsField": "vector", "limit": 5, "outputFields": [ "title" ] } ``` ## Sample response ```json { "code": 0, "data": [ { "id": 101, "title": "Invisible Cities", "distance": 0.98 } ], "cost": 0, "topks": [ 1 ] } ``` You can apply a dense vector field from the described schema to fill a sample vector with the correct dimension. Replace the sample with your embedding before sending. ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `data` array of JSON value Query inputs, such as an array of vectors. Supply data or ids. - `ids` array of JSON value Stored primary keys to search by, as an alternative to data. - `annsField` string Vector field to search. Specify it when the collection has multiple vector fields. - `partitionNames` array of string Names of the partitions to target. - `filter` string Milvus scalar filter expression. - `groupingField` string Scalar field used to group search hits. - `groupSize` integer Number of hits requested per group. - `strictGroupSize` boolean Require the specified number of hits in each result group. - `limit` integer Maximum number of rows or hits per query input. - `offset` integer Number of matching results to skip. - `outputFields` array of string Field names to include in the returned entities. - `searchParams` object Index-specific search parameters, including metric and search tuning options. - `consistencyLevel` string Read consistency level, such as Strong, Session, or Bounded. - `exprParams` object Values for placeholders in a filter expression. - `functionScore` object Scoring functions and parameters to apply to candidates. - `functionChains` array of object Ordered function chains to apply during search. - `searchAggregation` object Bucket aggregation and metric configuration for search hits. - `orderByFields` array of string Field ordering expressions for sorted results. - `params` object Additional operation parameters. See [`HttpClient.search`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#search) for the Node.js SDK method. --- # Hybrid search Combine multiple vector searches and rerank the candidates into one result list. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/hybrid-search/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/hybrid-search/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/hybrid-search/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/hybrid-search/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/hybrid-search/#request-fields) `POST /v2/vectordb/entities/hybrid_search` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/entities/hybrid_search' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "search": [ { "annsField": "vector", "data": [ [ 0.1, 0.2, 0.3, 0.4 ] ], "limit": 5 }, { "annsField": "vector", "data": [ [ 1, 0, 0, 0 ] ], "limit": 5 } ], "rerank": { "strategy": "rrf", "params": { "k": 60 } }, "limit": 3, "outputFields": [ "title" ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "search": [ { "annsField": "vector", "data": [ [ 0.1, 0.2, 0.3, 0.4 ] ], "limit": 5 }, { "annsField": "vector", "data": [ [ 1, 0, 0, 0 ] ], "limit": 5 } ], "rerank": { "strategy": "rrf", "params": { "k": 60 } }, "limit": 3, "outputFields": [ "title" ] } ``` ## Sample response ```json { "code": 0, "data": [ { "id": 101, "title": "Invisible Cities", "distance": 0.033 } ], "cost": 0, "topks": [ 1 ] } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionNames` array of string Names of the partitions to target. - `search` array of object Sub-searches with query data, vector field and limit. - `rerank` object Reranking strategy and parameters, such as reciprocal rank fusion (rrf). - `limit` integer Maximum number of rows or hits per query input. - `offset` integer Number of matching results to skip. - `groupingField` string Scalar field used to group search hits. - `groupSize` integer Number of hits requested per group. - `strictGroupSize` boolean Require the specified number of hits in each result group. - `outputFields` array of string Field names to include in the returned entities. - `consistencyLevel` string Read consistency level, such as Strong, Session, or Bounded. - `functionScore` object Scoring functions and parameters to apply to candidates. - `functionChains` array of object Ordered function chains to apply during search. See [`HttpClient.hybridSearch`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#hybridsearch) for the Node.js SDK method. --- # Advanced search (alias) Compatibility alias for hybrid search. New integrations can use the hybrid_search route. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/advanced-search/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/advanced-search/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/advanced-search/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/advanced-search/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/advanced-search/#request-fields) `POST /v2/vectordb/entities/advanced_search` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/entities/advanced_search' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "search": [ { "annsField": "vector", "data": [ [ 0.1, 0.2, 0.3, 0.4 ] ], "limit": 5 }, { "annsField": "vector", "data": [ [ 1, 0, 0, 0 ] ], "limit": 5 } ], "rerank": { "strategy": "rrf", "params": { "k": 60 } }, "limit": 3, "outputFields": [ "title" ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "search": [ { "annsField": "vector", "data": [ [ 0.1, 0.2, 0.3, 0.4 ] ], "limit": 5 }, { "annsField": "vector", "data": [ [ 1, 0, 0, 0 ] ], "limit": 5 } ], "rerank": { "strategy": "rrf", "params": { "k": 60 } }, "limit": 3, "outputFields": [ "title" ] } ``` ## Sample response ```json { "code": 0, "data": [ { "id": 101, "title": "Invisible Cities", "distance": 0.033 } ], "cost": 0, "topks": [ 1 ] } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionNames` array of string Names of the partitions to target. - `search` array of object Sub-searches with query data, vector field and limit. - `rerank` object Reranking strategy and parameters, such as reciprocal rank fusion (rrf). - `limit` integer Maximum number of rows or hits per query input. - `offset` integer Number of matching results to skip. - `groupingField` string Scalar field used to group search hits. - `groupSize` integer Number of hits requested per group. - `strictGroupSize` boolean Require the specified number of hits in each result group. - `outputFields` array of string Field names to include in the returned entities. - `consistencyLevel` string Read consistency level, such as Strong, Session, or Bounded. - `functionScore` object Scoring functions and parameters to apply to candidates. - `functionChains` array of object Ordered function chains to apply during search. See [`HttpClient.hybridSearch`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#hybridsearch) for the Node.js SDK method. --- # Delete entities Delete entities matching a scalar expression. A primary-key filter limits the deletion to specific rows. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/delete/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/delete/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/delete/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/delete/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/delete/#request-fields) `POST /v2/vectordb/entities/delete` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/entities/delete' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "filter": "id in [101]" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "filter": "id in [101]" } ``` ## Sample response ```json { "code": 0, "data": { "deleteCount": 1 } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionName` string Name of the partition. - `filter` string (required) Milvus scalar filter expression. - `exprParams` object Values for placeholders in a filter expression. See [`HttpClient.delete`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#delete) for the Node.js SDK method. --- # List collections List the names of collections in a database. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/list/#request-fields) `POST /v2/vectordb/collections/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default" }' ``` ## Default request ```json { "dbName": "default" } ``` ## Sample response ```json { "code": 0, "data": [ "books" ] } ``` Choose a returned collection to fill the Describe collection, Query, and Search requests. ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. See [`HttpClient.listCollections`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listcollections) for the Node.js SDK method. --- # Create collection Create a collection using a vector dimension for quick setup or an explicit schema for custom fields and functions. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/create/#request-fields) `POST /v2/vectordb/collections/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books_demo", "dimension": 4, "metricType": "COSINE", "primaryFieldName": "id", "vectorFieldName": "vector" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books_demo", "dimension": 4, "metricType": "COSINE", "primaryFieldName": "id", "vectorFieldName": "vector" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `dimension` integer Number of vector components for quick collection setup. Supply this or an explicit schema. - `idType` string Primary key type for quick setup, such as Int64 or VarChar. - `autoID` boolean Let the server generate primary keys. - `metricType` string Vector distance metric, such as COSINE, L2, or IP. - `vectorFieldType` string Vector data type for quick setup. Choose a type compatible with the metric. - `consistencyLevel` string Read consistency level, such as Strong, Session, or Bounded. - `primaryFieldName` string Primary key field name for quick setup. - `vectorFieldName` string Vector field name for quick setup. - `schema` object Explicit collection schema. Put externalSource and externalSpec inside schema for an external collection. - `indexParams` array of object Index definitions, including the target field, metric and index parameters. - `params` object Additional operation parameters. - `properties` object Map of property names to their new values. - `description` string Human-readable description. See [`HttpClient.createCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createcollection) for the Node.js SDK method. --- # Check collection existence Check whether a named collection exists in the database. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/has/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/has/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/has/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/has/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/has/#request-fields) `POST /v2/vectordb/collections/has` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/has' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": { "has": true } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.hasCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#hascollection) for the Node.js SDK method. --- # Describe collection Read field names, data types, indexes and load state for a collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/describe/#request-fields) `POST /v2/vectordb/collections/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": { "collectionName": "books", "collectionID": 123456789, "description": "Book catalog", "autoId": false, "fields": [ { "description": "", "primaryKey": true, "partitionKey": false, "clusteringKey": false, "autoId": false, "nullable": false, "id": 100, "name": "id", "type": "Int64" }, { "description": "", "primaryKey": false, "partitionKey": false, "clusteringKey": false, "autoId": false, "nullable": false, "id": 101, "name": "title", "type": "VarChar", "params": [ { "key": "max_length", "value": "256" } ] }, { "description": "", "primaryKey": false, "partitionKey": false, "clusteringKey": false, "autoId": false, "nullable": false, "id": 102, "name": "vector", "type": "FloatVector", "params": [ { "key": "dim", "value": "4" } ] } ], "structFields": [], "functions": [], "aliases": [ "current_books" ], "indexes": [ { "fieldName": "vector", "indexName": "vector_idx", "metricType": "COSINE" } ], "load": "LoadStateLoaded", "shardsNum": 1, "partitionsNum": 2, "consistencyLevel": "Bounded", "enableDynamicField": false, "externalSource": "", "externalSpec": "", "properties": [] }, "message": "" } ``` A successful response makes its schema available in [Query](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/query/) and [Search](https://milvus-io.github.io/milvus-sdk-node/rest-api/entities/search/). ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.describeCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describecollection) for the Node.js SDK method. --- # Collection statistics Read collection statistics, including the reported row count. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-stats/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-stats/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-stats/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-stats/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-stats/#request-fields) `POST /v2/vectordb/collections/get_stats` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/get_stats' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": { "rowCount": 1 } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.getCollectionStatistics`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getcollectionstatistics) for the Node.js SDK method. --- # Load collection Load collection data into query nodes so it can serve queries and vector searches. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/load/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/load/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/load/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/load/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/load/#request-fields) `POST /v2/vectordb/collections/load` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/load' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.loadCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#loadcollection) for the Node.js SDK method. --- # Get load state Check the loading state of a collection or its named partitions. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-load-state/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-load-state/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-load-state/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-load-state/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-load-state/#request-fields) `POST /v2/vectordb/collections/get_load_state` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/get_load_state' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": { "loadState": "LoadStateLoaded", "loadProgress": 100 }, "message": "" } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionNames` array of string Names of the partitions to target. See [`HttpClient.getCollectionLoadState`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getcollectionloadstate) for the Node.js SDK method. --- # Refresh loaded data Refresh a loaded collection to pick up changes in its data or indexes. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/refresh-load/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/refresh-load/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/refresh-load/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/refresh-load/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/refresh-load/#request-fields) `POST /v2/vectordb/collections/refresh_load` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/refresh_load' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.refreshLoad`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#refreshload) for the Node.js SDK method. --- # Release collection Release a collection from query-node memory. Load it again before searching. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/release/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/release/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/release/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/release/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/release/#request-fields) `POST /v2/vectordb/collections/release` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/release' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.releaseCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#releasecollection) for the Node.js SDK method. --- # Rename collection Change the collection name, optionally specifying a destination database. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/rename/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/rename/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/rename/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/rename/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/rename/#request-fields) `POST /v2/vectordb/collections/rename` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/rename' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "newCollectionName": "books_archive" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "newCollectionName": "books_archive" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `newCollectionName` string (required) New name of the collection. - `newDbName` string Destination database for a rename across databases. See [`HttpClient.renameCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#renamecollection) for the Node.js SDK method. --- # Set properties Set collection properties by key. Supplied values replace existing values for those keys. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/alter-properties/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/alter-properties/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/alter-properties/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/alter-properties/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/alter-properties/#request-fields) `POST /v2/vectordb/collections/alter_properties` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/alter_properties' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "properties": { "collection.ttl.seconds": "86400" } }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "properties": { "collection.ttl.seconds": "86400" } } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `properties` object Map of property names to their new values. See [`HttpClient.alterCollectionProperties`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#altercollectionproperties) for the Node.js SDK method. --- # Remove properties Remove the specified collection property keys. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop-properties/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop-properties/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop-properties/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop-properties/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop-properties/#request-fields) `POST /v2/vectordb/collections/drop_properties` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/drop_properties' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "propertyKeys": [ "collection.ttl.seconds" ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "propertyKeys": [ "collection.ttl.seconds" ] } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `propertyKeys` array of string Names of the properties to remove. See [`HttpClient.dropCollectionProperties`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropcollectionproperties) for the Node.js SDK method. --- # Flush collection Request a flush of data in the collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/flush/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/flush/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/flush/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/flush/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/flush/#request-fields) `POST /v2/vectordb/collections/flush` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/flush' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.flushCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#flushcollection) for the Node.js SDK method. --- # Start compaction Schedule compaction of collection segments and obtain a compaction job ID. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/compact/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/compact/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/compact/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/compact/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/compact/#request-fields) `POST /v2/vectordb/collections/compact` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/compact' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": { "compactionID": 123456789 } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `isClustering` boolean Request clustering compaction. See [`HttpClient.compactCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#compactcollection) for the Node.js SDK method. --- # Get compaction state Read the state of a previously submitted compaction job. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-compaction-state/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-compaction-state/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-compaction-state/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-compaction-state/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/get-compaction-state/#request-fields) `POST /v2/vectordb/collections/get_compaction_state` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/get_compaction_state' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "jobID": 123456789 }' ``` ## Default request ```json { "jobID": 123456789 } ``` ## Sample response ```json { "code": 0, "data": { "compactionID": 123456789, "state": "Completed", "executingPlanNumber": 0, "timeoutPlanNumber": 0, "completedPlanNumber": 1 } } ``` ## Request fields - `jobID` integer Unquoted int64 compaction ID. Paste the exact digits returned at submission. See [`HttpClient.getCompactionState`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getcompactionstate) for the Node.js SDK method. --- # Truncate collection Remove all entities while retaining the collection schema and indexes. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/truncate/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/truncate/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/truncate/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/truncate/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/truncate/#request-fields) `POST /v2/vectordb/collections/truncate` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/truncate' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.truncateCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#truncatecollection) for the Node.js SDK method. --- # Drop collection Permanently remove the named collection and its data. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/collections/drop/#request-fields) `POST /v2/vectordb/collections/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.dropCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropcollection) for the Node.js SDK method. --- # Add field Add a field to an existing collection using a field schema. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/add/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/add/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/add/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/add/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/add/#request-fields) `POST /v2/vectordb/collections/fields/add` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/fields/add' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "schema": { "fieldName": "category", "dataType": "VarChar", "nullable": true, "elementTypeParams": { "max_length": 128 } } }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "schema": { "fieldName": "category", "dataType": "VarChar", "nullable": true, "elementTypeParams": { "max_length": 128 } } } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `schema` object (required) Schema definition with field names, data types and type parameters. See [`HttpClient.addCollectionField`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addcollectionfield) for the Node.js SDK method. --- # Add struct field Add a struct-array field with its nested field definitions. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/struct-fields/add/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/struct-fields/add/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/struct-fields/add/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/struct-fields/add/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/struct-fields/add/#request-fields) `POST /v2/vectordb/collections/struct_fields/add` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/struct_fields/add' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "schema": { "fieldName": "editions", "dataType": "Array", "elementDataType": "Struct", "typeParams": { "max_capacity": "16" }, "nullable": true, "fields": [ { "fieldName": "year", "dataType": "Array", "elementDataType": "Int32", "elementTypeParams": { "max_capacity": "16" } } ] } }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "schema": { "fieldName": "editions", "dataType": "Array", "elementDataType": "Struct", "typeParams": { "max_capacity": "16" }, "nullable": true, "fields": [ { "fieldName": "year", "dataType": "Array", "elementDataType": "Int32", "elementTypeParams": { "max_capacity": "16" } } ] } } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `schema` object (required) Schema definition with field names, data types and type parameters. See [`HttpClient.addCollectionStructField`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addcollectionstructfield) for the Node.js SDK method. --- # Set field properties Change supported field parameters on an existing collection field. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/alter-properties/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/alter-properties/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/alter-properties/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/alter-properties/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/alter-properties/#request-fields) `POST /v2/vectordb/collections/fields/alter_properties` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/fields/alter_properties' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "fieldName": "title", "fieldParams": { "max_length": "256" } }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "fieldName": "title", "fieldParams": { "max_length": "256" } } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `fieldName` string (required) Name of the target field. - `fieldParams` object Updated field parameters as a key-value object. See [`HttpClient.alterCollectionFieldProperties`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#altercollectionfieldproperties) for the Node.js SDK method. --- # Drop field Remove a field by name or field ID. Existing data for the removed field is lost. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/fields/drop/#request-fields) `POST /v2/vectordb/collections/fields/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/fields/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "fieldName": "category" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "fieldName": "category" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `fieldName` string Field to remove; supply its name or its fieldId. - `fieldId` integer Numeric field ID, as an alternative to fieldName. See [`HttpClient.dropCollectionField`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropcollectionfield) for the Node.js SDK method. --- # Add function (legacy) Milvus 3.0.6 rejects this legacy route. Use add_function_field for BM25 or MinHash, or define a text embedding function when creating a collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function/#request-fields) `POST /v2/vectordb/collections/add_function` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/add_function' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "function": { "name": "title_bm25", "type": "BM25", "inputFieldNames": [ "title" ], "outputFieldNames": [ "title_sparse" ] } }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "function": { "name": "title_bm25", "type": "BM25", "inputFieldNames": [ "title" ], "outputFieldNames": [ "title_sparse" ] } } ``` ## Sample response ```json { "code": 1100, "message": "AddCollectionFunction RPC is no longer supported; add BM25/MinHash via add_function_field, and define a TextEmbedding function at collection creation: invalid parameter" } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `function` object (required) Function definition with name, type, inputFieldNames and outputFieldNames. For new SDK code, use [`HttpClient.addFunctionField`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addfunctionfield) to manage the function together with its output field and index. --- # Alter function Update a supported function, such as an existing text embedding function. Milvus 3.0.6 rejects alterations to BM25 functions. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/alter-function/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/alter-function/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/alter-function/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/alter-function/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/alter-function/#request-fields) `POST /v2/vectordb/collections/alter_function` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/alter_function' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books_with_embeddings", "functionName": "title_embedding", "function": { "name": "title_embedding", "description": "Book title embeddings", "type": "TextEmbedding", "inputFieldNames": [ "title" ], "outputFieldNames": [ "title_dense" ], "params": { "provider": "openai", "model_name": "text-embedding-3-small" } } }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books_with_embeddings", "functionName": "title_embedding", "function": { "name": "title_embedding", "description": "Book title embeddings", "type": "TextEmbedding", "inputFieldNames": [ "title" ], "outputFieldNames": [ "title_dense" ], "params": { "provider": "openai", "model_name": "text-embedding-3-small" } } } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `functionName` string (required) Name of the collection function. - `function` object (required) Function definition with name, type, inputFieldNames and outputFieldNames. See [`HttpClient.alterCollectionFunction`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#altercollectionfunction) for the Node.js SDK method. --- # Drop function (legacy) Milvus 3.0.6 rejects this legacy route. Use drop_function_field to remove the function and its output field. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function/#request-fields) `POST /v2/vectordb/collections/drop_function` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/drop_function' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "FunctionName": "title_bm25" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "FunctionName": "title_bm25" } ``` ## Sample response ```json { "code": 1100, "message": "DropCollectionFunction RPC is no longer supported; drop a function via drop_function_field: invalid parameter" } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `FunctionName` string (required) Name of the collection function to remove. For new SDK code, use [`HttpClient.dropFunctionField`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropfunctionfield) to manage the function together with its output field and index. --- # Add function and field Add a function with its output field and optional index configuration. The input field must already exist and have its analyzer enabled for BM25. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function-field/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function-field/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function-field/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function-field/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/add-function-field/#request-fields) `POST /v2/vectordb/collections/add_function_field` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/add_function_field' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "function": { "name": "title_bm25", "type": "BM25", "inputFieldNames": [ "title" ], "outputFieldNames": [ "title_sparse" ] }, "outputField": { "fieldName": "title_sparse", "dataType": "SparseFloatVector" }, "indexParams": { "fieldName": "title_sparse", "indexType": "SPARSE_INVERTED_INDEX", "metricType": "BM25" } }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "function": { "name": "title_bm25", "type": "BM25", "inputFieldNames": [ "title" ], "outputFieldNames": [ "title_sparse" ] }, "outputField": { "fieldName": "title_sparse", "dataType": "SparseFloatVector" }, "indexParams": { "fieldName": "title_sparse", "indexType": "SPARSE_INVERTED_INDEX", "metricType": "BM25" } } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `function` object (required) Function definition with name, type, inputFieldNames and outputFieldNames. - `outputField` object (required) Schema of the field created for the function output. - `indexParams` object Index definition for the new output field. See [`HttpClient.addFunctionField`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addfunctionfield) for the Node.js SDK method. --- # Drop function and field Remove a function together with its output field. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function-field/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function-field/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function-field/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function-field/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/schema/drop-function-field/#request-fields) `POST /v2/vectordb/collections/drop_function_field` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/collections/drop_function_field' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "functionName": "title_bm25" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "functionName": "title_bm25" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `functionName` string (required) Name of the collection function. See [`HttpClient.dropFunctionField`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropfunctionfield) for the Node.js SDK method. --- # List indexes List index names for a collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/list/#request-fields) `POST /v2/vectordb/indexes/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/indexes/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": [ "vector_idx" ] } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.listIndexes`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listindexes) for the Node.js SDK method. --- # Create index Build an index on a field. Vector indexes require a compatible metric. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/create/#request-fields) `POST /v2/vectordb/indexes/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/indexes/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "indexParams": [ { "fieldName": "vector", "indexName": "vector_idx", "metricType": "COSINE", "params": { "index_type": "AUTOINDEX" } } ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "indexParams": [ { "fieldName": "vector", "indexName": "vector_idx", "metricType": "COSINE", "params": { "index_type": "AUTOINDEX" } } ] } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `indexParams` array of object (required) Index definitions, including the target field, metric and index parameters. See [`HttpClient.createIndex`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createindex) for the Node.js SDK method. --- # Describe index Inspect index configuration and build state. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/describe/#request-fields) `POST /v2/vectordb/indexes/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/indexes/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "indexName": "vector_idx" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "indexName": "vector_idx" } ``` ## Sample response ```json { "code": 0, "data": [ { "indexName": "vector_idx", "fieldName": "vector", "indexState": "Finished", "totalRows": 1, "pendingRows": 0, "indexedRows": 1, "failReason": "", "indexParams": [ { "key": "index_type", "value": "AUTOINDEX" }, { "key": "metric_type", "value": "COSINE" } ] } ] } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `indexName` string (required) Name of the index on the collection. - `timestamp` integer Timestamp for the index description, when needed. See [`HttpClient.describeIndex`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describeindex) for the Node.js SDK method. --- # Set index properties Update supported properties on a named index. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/alter-properties/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/alter-properties/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/alter-properties/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/alter-properties/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/alter-properties/#request-fields) `POST /v2/vectordb/indexes/alter_properties` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/indexes/alter_properties' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "indexName": "vector_idx", "properties": { "mmap.enabled": "true" } }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "indexName": "vector_idx", "properties": { "mmap.enabled": "true" } } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `indexName` string (required) Name of the index on the collection. - `properties` object Map of property names to their new values. See [`HttpClient.alterIndexProperties`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alterindexproperties) for the Node.js SDK method. --- # Remove index properties Remove specified keys from index properties. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop-properties/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop-properties/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop-properties/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop-properties/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop-properties/#request-fields) `POST /v2/vectordb/indexes/drop_properties` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/indexes/drop_properties' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "indexName": "vector_idx", "propertyKeys": [ "mmap.enabled" ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "indexName": "vector_idx", "propertyKeys": [ "mmap.enabled" ] } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `indexName` string (required) Name of the index on the collection. - `propertyKeys` array of string Names of the properties to remove. See [`HttpClient.dropIndexProperties`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropindexproperties) for the Node.js SDK method. --- # Drop index Remove a named index from a collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/indexes/drop/#request-fields) `POST /v2/vectordb/indexes/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/indexes/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "indexName": "vector_idx" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "indexName": "vector_idx" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `indexName` string (required) Name of the index on the collection. - `timestamp` integer Timestamp for the index description, when needed. See [`HttpClient.dropIndex`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropindex) for the Node.js SDK method. --- # List partitions List partitions in a collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/list/#request-fields) `POST /v2/vectordb/partitions/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/partitions/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": [ "_default", "fiction" ] } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.listPartitions`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listpartitions) for the Node.js SDK method. --- # Create partition Create a named partition in a collection that supports manual partitions. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/create/#request-fields) `POST /v2/vectordb/partitions/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/partitions/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "partitionName": "fiction" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "partitionName": "fiction" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionName` string (required) Name of the partition. See [`HttpClient.createPartition`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createpartition) for the Node.js SDK method. --- # Check partition existence Check whether the named partition exists in a collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/has/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/has/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/has/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/has/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/has/#request-fields) `POST /v2/vectordb/partitions/has` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/partitions/has' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "partitionName": "fiction" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "partitionName": "fiction" } ``` ## Sample response ```json { "code": 0, "data": { "has": true } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionName` string (required) Name of the partition. See [`HttpClient.hasPartition`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#haspartition) for the Node.js SDK method. --- # Partition statistics Read statistics for the specified partition. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/get-stats/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/get-stats/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/get-stats/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/get-stats/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/get-stats/#request-fields) `POST /v2/vectordb/partitions/get_stats` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/partitions/get_stats' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "partitionName": "fiction" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "partitionName": "fiction" } ``` ## Sample response ```json { "code": 0, "data": { "rowCount": 1 } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionName` string (required) Name of the partition. See [`HttpClient.getPartitionStatistics`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getpartitionstatistics) for the Node.js SDK method. --- # Load partitions Load the specified partitions so their data can serve read requests. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/load/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/load/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/load/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/load/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/load/#request-fields) `POST /v2/vectordb/partitions/load` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/partitions/load' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "partitionNames": [ "fiction" ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "partitionNames": [ "fiction" ] } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionNames` array of string (required) Names of the partitions to target. See [`HttpClient.loadPartitions`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#loadpartitions) for the Node.js SDK method. --- # Release partitions Release the specified partitions from query-node memory. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/release/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/release/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/release/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/release/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/release/#request-fields) `POST /v2/vectordb/partitions/release` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/partitions/release' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "partitionNames": [ "fiction" ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "partitionNames": [ "fiction" ] } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionNames` array of string (required) Names of the partitions to target. See [`HttpClient.releasePartitions`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#releasepartitions) for the Node.js SDK method. --- # Drop partition Remove a partition and the entities stored in it. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/partitions/drop/#request-fields) `POST /v2/vectordb/partitions/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/partitions/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "partitionName": "fiction" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "partitionName": "fiction" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionName` string (required) Name of the partition. See [`HttpClient.dropPartition`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#droppartition) for the Node.js SDK method. --- # List databases List the databases visible to the caller. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/list/#request-fields) `POST /v2/vectordb/databases/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/databases/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{}' ``` ## Default request ```json {} ``` ## Sample response ```json { "code": 0, "data": [ "default", "library" ] } ``` ## Request fields This operation accepts an empty JSON object. See [`HttpClient.listDatabases`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listdatabases) for the Node.js SDK method. --- # Create database Create a database, optionally supplying its properties. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/create/#request-fields) `POST /v2/vectordb/databases/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/databases/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "library" }' ``` ## Default request ```json { "dbName": "library" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string (required) Database name. Operations on collections use default when omitted. - `properties` object Map of property names to their new values. See [`HttpClient.createDatabase`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createdatabase) for the Node.js SDK method. --- # Describe database Read properties and metadata for a database. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/describe/#request-fields) `POST /v2/vectordb/databases/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/databases/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "library" }' ``` ## Default request ```json { "dbName": "library" } ``` ## Sample response ```json { "code": 0, "data": { "dbName": "library", "dbID": 123456788, "properties": [ { "key": "database.replica.number", "value": "1" } ] } } ``` ## Request fields - `dbName` string (required) Database name. Operations on collections use default when omitted. See [`HttpClient.describeDatabase`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describedatabase) for the Node.js SDK method. --- # Set database properties Set or replace database property values. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter-properties/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter-properties/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter-properties/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter-properties/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter-properties/#request-fields) `POST /v2/vectordb/databases/alter_properties` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/databases/alter_properties' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "library", "properties": { "database.replica.number": "1" } }' ``` ## Default request ```json { "dbName": "library", "properties": { "database.replica.number": "1" } } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string (required) Database name. Operations on collections use default when omitted. - `properties` object Map of property names to their new values. See [`HttpClient.alterDatabaseProperties`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alterdatabaseproperties) for the Node.js SDK method. --- # Alter database Alternative route for updating database properties. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/alter/#request-fields) `POST /v2/vectordb/databases/alter` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/databases/alter' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "library", "properties": { "database.replica.number": "1" } }' ``` ## Default request ```json { "dbName": "library", "properties": { "database.replica.number": "1" } } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string (required) Database name. Operations on collections use default when omitted. - `properties` object Map of property names to their new values. See [`HttpClient.alterDatabaseProperties`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alterdatabaseproperties) for the Node.js SDK method. --- # Remove database properties Remove the specified database property keys. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop-properties/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop-properties/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop-properties/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop-properties/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop-properties/#request-fields) `POST /v2/vectordb/databases/drop_properties` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/databases/drop_properties' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "library", "propertyKeys": [ "database.replica.number" ] }' ``` ## Default request ```json { "dbName": "library", "propertyKeys": [ "database.replica.number" ] } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string (required) Database name. Operations on collections use default when omitted. - `propertyKeys` array of string Names of the properties to remove. See [`HttpClient.dropDatabaseProperties`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropdatabaseproperties) for the Node.js SDK method. --- # Drop database Remove an empty database after its collections have been removed. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/databases/drop/#request-fields) `POST /v2/vectordb/databases/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/databases/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "library" }' ``` ## Default request ```json { "dbName": "library" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string (required) Database name. Operations on collections use default when omitted. See [`HttpClient.dropDatabase`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropdatabase) for the Node.js SDK method. --- # List aliases List collection aliases, optionally filtering by collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/list/#request-fields) `POST /v2/vectordb/aliases/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/aliases/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default" }' ``` ## Default request ```json { "dbName": "default" } ``` ## Sample response ```json { "code": 0, "data": [ "current_books" ] } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string Name of the collection. See [`HttpClient.listAliases`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listaliases) for the Node.js SDK method. --- # Create alias Associate a new alias with a collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/create/#request-fields) `POST /v2/vectordb/aliases/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/aliases/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "aliasName": "current_books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "aliasName": "current_books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `aliasName` string (required) Alias used to address a collection. See [`HttpClient.createAlias`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createalias) for the Node.js SDK method. --- # Describe alias Look up the collection associated with an alias. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/describe/#request-fields) `POST /v2/vectordb/aliases/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/aliases/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "aliasName": "current_books" }' ``` ## Default request ```json { "dbName": "default", "aliasName": "current_books" } ``` ## Sample response ```json { "code": 0, "data": { "dbName": "default", "collectionName": "books", "aliasName": "current_books" } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `aliasName` string (required) Alias used to address a collection. See [`HttpClient.describeAlias`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describealias) for the Node.js SDK method. --- # Reassign alias Point an existing alias at another collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/alter/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/alter/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/alter/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/alter/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/alter/#request-fields) `POST /v2/vectordb/aliases/alter` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/aliases/alter' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "aliasName": "current_books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "aliasName": "current_books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `aliasName` string (required) Alias used to address a collection. See [`HttpClient.alterAlias`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alteralias) for the Node.js SDK method. --- # Drop alias Remove an alias while retaining its underlying collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/aliases/drop/#request-fields) `POST /v2/vectordb/aliases/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/aliases/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "aliasName": "current_books" }' ``` ## Default request ```json { "dbName": "default", "aliasName": "current_books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `aliasName` string (required) Alias used to address a collection. See [`HttpClient.dropAlias`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropalias) for the Node.js SDK method. --- # Start import Submit files already accessible to Milvus for import into a collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/create/#request-fields) `POST /v2/vectordb/jobs/import/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/import/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "files": [ [ "imports/books.parquet" ] ] }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "files": [ [ "imports/books.parquet" ] ] } ``` ## Sample response ```json { "code": 0, "data": { "jobId": "123456789" } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `partitionName` string Name of the partition. - `files` array of array of string (required) Groups of import file paths accessible to Milvus in object storage. - `options` object Import options as string key-value pairs. See [`HttpClient.createImportJobs`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createimportjobs) for the Node.js SDK method. --- # List import jobs List import jobs, optionally filtering by collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/list/#request-fields) `POST /v2/vectordb/jobs/import/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/import/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default" }' ``` ## Default request ```json { "dbName": "default" } ``` ## Sample response ```json { "code": 0, "data": { "records": [ { "jobId": "123456789", "collectionName": "books", "state": "Completed", "progress": 100 } ] } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string Name of the collection. See [`HttpClient.listImportJobs`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listimportjobs) for the Node.js SDK method. --- # Describe import job Read job state, progress, and any reported failure reason. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/describe/#request-fields) `POST /v2/vectordb/jobs/import/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/import/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "jobId": "123456789" }' ``` ## Default request ```json { "jobId": "123456789" } ``` ## Sample response ```json { "code": 0, "data": { "jobId": "123456789", "collectionName": "books", "state": "Completed", "progress": 100, "createTime": "2026-11-19T12:00:00Z", "completeTime": "2026-11-19T12:01:00Z", "importedRows": 1, "totalRows": 1, "fileSize": 4096, "details": [ { "fileName": "imports/books.parquet", "fileSize": 4096, "progress": 100, "completeTime": "2026-11-19T12:01:00Z", "state": "Completed", "importedRows": 1, "totalRows": 1 } ] } } ``` ## Request fields - `jobId` string (required) Job ID returned when the job was submitted. See [`HttpClient.getImportJobProgress`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getimportjobprogress) for the Node.js SDK method. --- # Get progress (legacy) Legacy route for reading import progress. Prefer the describe route for new integrations. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/get-progress/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/get-progress/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/get-progress/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/get-progress/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/get-progress/#request-fields) `POST /v2/vectordb/jobs/import/get_progress` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/import/get_progress' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "jobId": "123456789" }' ``` ## Default request ```json { "jobId": "123456789" } ``` ## Sample response ```json { "code": 0, "data": { "jobId": "123456789", "collectionName": "books", "state": "Completed", "progress": 100, "createTime": "2026-11-19T12:00:00Z", "completeTime": "2026-11-19T12:01:00Z", "importedRows": 1, "totalRows": 1, "fileSize": 4096, "details": [ { "fileName": "imports/books.parquet", "fileSize": 4096, "progress": 100, "completeTime": "2026-11-19T12:01:00Z", "state": "Completed", "importedRows": 1, "totalRows": 1 } ] } } ``` ## Request fields - `jobId` string (required) Job ID returned when the job was submitted. See [`HttpClient.getImportJobProgress`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getimportjobprogress) for the Node.js SDK method. --- # Commit import Commit an import started with auto_commit set to false after its state reaches Uncommitted. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/commit/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/commit/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/commit/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/commit/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/commit/#request-fields) `POST /v2/vectordb/jobs/import/commit` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/import/commit' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "jobId": "123456789" }' ``` ## Default request ```json { "jobId": "123456789" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `jobId` string (required) Job ID returned when the job was submitted. See [`HttpClient.commitImportJob`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#commitimportjob) for the Node.js SDK method. --- # Abort import Abort an import job using its job ID. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/abort/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/abort/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/abort/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/abort/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/import-jobs/abort/#request-fields) `POST /v2/vectordb/jobs/import/abort` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/import/abort' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "jobId": "123456789" }' ``` ## Default request ```json { "jobId": "123456789" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `jobId` string (required) Job ID returned when the job was submitted. See [`HttpClient.abortImportJob`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#abortimportjob) for the Node.js SDK method. --- # Refresh external collection Submit a refresh of an external collection from its configured or supplied data source. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/refresh/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/refresh/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/refresh/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/refresh/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/refresh/#request-fields) `POST /v2/vectordb/jobs/external_collection/refresh` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/external_collection/refresh' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": { "jobId": 123456789 } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `externalSource` string URI identifying the external data source. - `externalSpec` string Serialized JSON specifying the external storage format and options. See [`HttpClient.refreshExternalCollection`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#refreshexternalcollection) for the Node.js SDK method. --- # List refresh jobs List external collection refresh jobs. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/list/#request-fields) `POST /v2/vectordb/jobs/external_collection/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/external_collection/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default" }' ``` ## Default request ```json { "dbName": "default" } ``` ## Sample response ```json { "code": 0, "data": { "records": [ { "jobId": 123456789, "collectionName": "books", "state": "RefreshCompleted", "progress": 100, "externalSource": "s3://example-bucket/books/", "externalSpec": "{\"format\":\"parquet\"}", "startTime": 1795099200000, "endTime": 1795099202000 } ] } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string Name of the collection. See [`HttpClient.listRefreshExternalCollectionJobs`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listrefreshexternalcollectionjobs) for the Node.js SDK method. --- # Describe refresh job Inspect refresh progress using the unquoted integer job ID returned at submission. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/external-collections/describe/#request-fields) `POST /v2/vectordb/jobs/external_collection/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/external_collection/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "jobId": 123456789 }' ``` ## Default request ```json { "jobId": 123456789 } ``` ## Sample response ```json { "code": 0, "data": { "jobId": 123456789, "collectionName": "books", "state": "RefreshCompleted", "progress": 100, "externalSource": "s3://example-bucket/books/", "externalSpec": "{\"format\":\"parquet\"}", "startTime": 1795099200000, "endTime": 1795099202000 } } ``` ## Request fields - `jobId` integer (required) Unquoted int64 job ID. Paste the exact digits returned by the refresh request. See [`HttpClient.getRefreshExternalCollectionProgress`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getrefreshexternalcollectionprogress) for the Node.js SDK method. --- # Create snapshot Capture a snapshot of a collection for later restoration. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/create/#request-fields) `POST /v2/vectordb/snapshots/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/snapshots/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "snapshotName": "books_backup" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "snapshotName": "books_backup" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `snapshotName` string (required) Name of the collection snapshot. - `description` string Human-readable description. - `compactionProtectionSeconds` integer Compaction protection period in seconds. See [`HttpClient.createSnapshot`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createsnapshot) for the Node.js SDK method. --- # List snapshots List the snapshots associated with a collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/list/#request-fields) `POST /v2/vectordb/snapshots/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/snapshots/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": [ "books_backup" ], "snapshotSummaries": [ { "name": "books_backup", "description": "Backup before migration", "createTs": 470574484684800000, "createUtcTs": 1795099200000 } ] } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. See [`HttpClient.listSnapshots`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listsnapshots) for the Node.js SDK method. --- # Describe snapshot Read metadata for a specific collection snapshot. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/describe/#request-fields) `POST /v2/vectordb/snapshots/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/snapshots/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "snapshotName": "books_backup" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "snapshotName": "books_backup" } ``` ## Sample response ```json { "code": 0, "data": { "snapshotName": "books_backup", "description": "Backup before migration", "collectionName": "books", "partitionNames": [ "_default", "fiction" ], "createTs": 470574484684800000, "s3Location": "s3://example-bucket/snapshots/books_backup/" } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `snapshotName` string (required) Name of the collection snapshot. See [`HttpClient.describeSnapshot`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describesnapshot) for the Node.js SDK method. --- # Restore snapshot Start a restore from a named collection snapshot into a target collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/restore/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/restore/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/restore/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/restore/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/restore/#request-fields) `POST /v2/vectordb/snapshots/restore` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/snapshots/restore' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "sourceCollectionName": "books", "targetCollectionName": "books_restored", "snapshotName": "books_backup", "sourceDbName": "default", "targetDbName": "default" }' ``` ## Default request ```json { "sourceCollectionName": "books", "targetCollectionName": "books_restored", "snapshotName": "books_backup", "sourceDbName": "default", "targetDbName": "default" } ``` ## Sample response ```json { "code": 0, "data": { "jobId": 123456789 } } ``` ## Request fields - `sourceDbName` string Database holding the source snapshot. - `sourceCollectionName` string (required) Collection holding the source snapshot. - `targetDbName` string Database for the restored collection. - `targetCollectionName` string (required) Collection name to use for the restored data. - `snapshotName` string (required) Name of the collection snapshot. See [`HttpClient.restoreSnapshot`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#restoresnapshot) for the Node.js SDK method. --- # Pin snapshot data Pin snapshot data against reclamation and obtain a pin ID. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/pin/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/pin/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/pin/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/pin/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/pin/#request-fields) `POST /v2/vectordb/snapshots/pin` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/snapshots/pin' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "snapshotName": "books_backup", "ttlSeconds": 3600 }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "snapshotName": "books_backup", "ttlSeconds": 3600 } ``` ## Sample response ```json { "code": 0, "data": { "pinId": 123456789 } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `snapshotName` string (required) Name of the collection snapshot. - `ttlSeconds` integer Pin lifetime in seconds. See [`HttpClient.pinSnapshotData`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#pinsnapshotdata) for the Node.js SDK method. --- # Unpin snapshot data Release a previously acquired snapshot pin using its ID. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/unpin/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/unpin/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/unpin/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/unpin/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/unpin/#request-fields) `POST /v2/vectordb/snapshots/unpin` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/snapshots/unpin' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "pinId": "123456789" }' ``` ## Default request ```json { "pinId": "123456789" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `pinId` string (required) Pin identifier returned when snapshot data was pinned. See [`HttpClient.unpinSnapshotData`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#unpinsnapshotdata) for the Node.js SDK method. --- # Drop snapshot Delete a named collection snapshot. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshots/drop/#request-fields) `POST /v2/vectordb/snapshots/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/snapshots/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "snapshotName": "books_backup" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "snapshotName": "books_backup" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `snapshotName` string (required) Name of the collection snapshot. See [`HttpClient.dropSnapshot`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropsnapshot) for the Node.js SDK method. --- # List restore jobs List snapshot restore jobs, optionally filtering by collection. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/list/#request-fields) `POST /v2/vectordb/jobs/snapshot/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/snapshot/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default" }' ``` ## Default request ```json { "dbName": "default" } ``` ## Sample response ```json { "code": 0, "data": { "records": [ { "jobId": 123456789, "snapshotName": "books_backup", "dbName": "default", "collectionName": "books_restored", "progress": 100, "reason": "", "startTime": 1795099200000, "timeCost": 2000, "state": "RestoreSnapshotCompleted" } ] } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string Name of the collection. See [`HttpClient.listRestoreSnapshotJobs`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listrestoresnapshotjobs) for the Node.js SDK method. --- # Describe restore job Read the state of a snapshot restore job. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/describe/#request-fields) `POST /v2/vectordb/jobs/snapshot/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/snapshot/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "jobId": "123456789" }' ``` ## Default request ```json { "jobId": "123456789" } ``` ## Sample response ```json { "code": 0, "data": { "jobId": 123456789, "snapshotName": "books_backup", "dbName": "default", "collectionName": "books_restored", "progress": 100, "reason": "", "startTime": 1795099200000, "timeCost": 2000, "state": "RestoreSnapshotCompleted" } } ``` ## Request fields - `jobId` string (required) Job ID returned when the job was submitted. See [`HttpClient.getRestoreSnapshotState`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getrestoresnapshotstate) for the Node.js SDK method. --- # Export snapshot Start exporting a named snapshot to the target S3 location. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/#request-fields) `POST /v2/vectordb/jobs/snapshot/export` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/snapshot/export' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionName": "books", "snapshotName": "books_backup", "targetS3Path": "s3://example-bucket/snapshots/books/" }' ``` ## Default request ```json { "dbName": "default", "collectionName": "books", "snapshotName": "books_backup", "targetS3Path": "s3://example-bucket/snapshots/books/" } ``` ## Sample response ```json { "code": 0, "data": { "jobId": 123456789 } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string (required) Name of the collection. - `snapshotName` string (required) Name of the collection snapshot. - `targetS3Path` string (required) Object storage destination for the exported snapshot. - `externalSpec` string Serialized JSON specifying the external storage format and options. See [`HttpClient.exportSnapshot`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#exportsnapshot) for the Node.js SDK method. --- # Describe export job Read the state of a snapshot export job. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/export/describe/#request-fields) `POST /v2/vectordb/jobs/snapshot/export/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/snapshot/export/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "jobId": "123456789" }' ``` ## Default request ```json { "jobId": "123456789" } ``` ## Sample response ```json { "code": 0, "data": { "jobId": 123456789, "snapshotName": "books_backup", "dbName": "default", "collectionName": "books", "progress": 100, "reason": "", "startTime": 1795099200000, "timeCost": 2000, "state": "ExportSnapshotCompleted", "totalFiles": 1, "copiedFiles": 1, "totalBytes": 4096, "snapshotMetadataURI": "s3://example-bucket/snapshots/books/manifest.json" } } ``` ## Request fields - `jobId` string (required) Job ID returned when the job was submitted. See [`HttpClient.getExportSnapshotState`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getexportsnapshotstate) for the Node.js SDK method. --- # Restore external snapshot Start a restore using snapshot metadata in external storage. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/restore-external/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/restore-external/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/restore-external/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/restore-external/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/snapshot-jobs/restore-external/#request-fields) `POST /v2/vectordb/jobs/snapshot/restore_external` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/jobs/snapshot/restore_external' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "targetCollectionName": "books_restored", "snapshotMetadataURI": "s3://example-bucket/snapshots/books/manifest.json" }' ``` ## Default request ```json { "dbName": "default", "targetCollectionName": "books_restored", "snapshotMetadataURI": "s3://example-bucket/snapshots/books/manifest.json" } ``` ## Sample response ```json { "code": 0, "data": { "jobId": 123456789 } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `targetCollectionName` string (required) Collection name to use for the restored data. - `snapshotMetadataURI` string (required) URI of the exported snapshot metadata. - `externalSpec` string Serialized JSON specifying the external storage format and options. See [`HttpClient.restoreExternalSnapshot`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#restoreexternalsnapshot) for the Node.js SDK method. --- # List users List users in the Milvus instance. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/users/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/list/#request-fields) `POST /v2/vectordb/users/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/users/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default" }' ``` ## Default request ```json { "dbName": "default" } ``` ## Sample response ```json { "code": 0, "data": [ "root", "catalog_user" ] } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. See [`HttpClient.listUsers`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listusers) for the Node.js SDK method. --- # Create user Create a Milvus user with a password. Replace the example value before submitting. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/users/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/create/#request-fields) `POST /v2/vectordb/users/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/users/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "userName": "catalog_user", "password": "" }' ``` ## Default request ```json { "userName": "catalog_user", "password": "" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `userName` string (required) Milvus user name. - `password` string (required) User password. Use the current password for a password change. - `description` string Human-readable description. See [`HttpClient.createUser`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createuser) for the Node.js SDK method. --- # Describe user Read information about a user and their role memberships. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/users/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/describe/#request-fields) `POST /v2/vectordb/users/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/users/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "userName": "catalog_user" }' ``` ## Default request ```json { "userName": "catalog_user" } ``` ## Sample response ```json { "code": 0, "data": [ "catalog_reader" ], "description": "" } ``` ## Request fields - `userName` string (required) Milvus user name. See [`HttpClient.describeUser`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describeuser) for the Node.js SDK method. --- # Update user Update a user password or description. For a password change supply the current and new passwords. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/users/update-password/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/update-password/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/update-password/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/update-password/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/update-password/#request-fields) `POST /v2/vectordb/users/update_password` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/users/update_password' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "userName": "catalog_user", "password": "", "newPassword": "" }' ``` ## Default request ```json { "userName": "catalog_user", "password": "", "newPassword": "" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `userName` string (required) Milvus user name. - `password` string User password. Use the current password for a password change. - `newPassword` string New password for the account. - `description` string Human-readable description. See [`HttpClient.updateUserPassword`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#updateuserpassword) for the Node.js SDK method. --- # Assign role Assign a role to a user. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/users/grant-role/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/grant-role/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/grant-role/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/grant-role/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/grant-role/#request-fields) `POST /v2/vectordb/users/grant_role` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/users/grant_role' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "userName": "catalog_user", "roleName": "catalog_reader" }' ``` ## Default request ```json { "userName": "catalog_user", "roleName": "catalog_reader" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `userName` string (required) Milvus user name. - `roleName` string (required) Milvus role name. See [`HttpClient.grantRoleToUser`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#grantroletouser) for the Node.js SDK method. --- # Revoke role Remove a role assignment from a user. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/users/revoke-role/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/revoke-role/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/revoke-role/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/revoke-role/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/revoke-role/#request-fields) `POST /v2/vectordb/users/revoke_role` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/users/revoke_role' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "userName": "catalog_user", "roleName": "catalog_reader" }' ``` ## Default request ```json { "userName": "catalog_user", "roleName": "catalog_reader" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `userName` string (required) Milvus user name. - `roleName` string (required) Milvus role name. See [`HttpClient.revokeRoleFromUser`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#revokerolefromuser) for the Node.js SDK method. --- # Drop user Remove a user account from the instance. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/users/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/users/drop/#request-fields) `POST /v2/vectordb/users/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/users/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "userName": "catalog_user" }' ``` ## Default request ```json { "userName": "catalog_user" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `userName` string (required) Milvus user name. See [`HttpClient.dropUser`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropuser) for the Node.js SDK method. --- # List roles List roles in the Milvus instance. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/list/#request-fields) `POST /v2/vectordb/roles/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/roles/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default" }' ``` ## Default request ```json { "dbName": "default" } ``` ## Sample response ```json { "code": 0, "data": [ "admin", "public", "catalog_reader" ] } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. See [`HttpClient.listRoles`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listroles) for the Node.js SDK method. --- # Create role Create a role for grouping privileges. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/create/#request-fields) `POST /v2/vectordb/roles/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/roles/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "roleName": "catalog_reader" }' ``` ## Default request ```json { "dbName": "default", "roleName": "catalog_reader" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `roleName` string (required) Milvus role name. - `description` string Human-readable description. See [`HttpClient.createRole`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createrole) for the Node.js SDK method. --- # Describe role Inspect a role and the privileges granted to it. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/describe/#request-fields) `POST /v2/vectordb/roles/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/roles/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "roleName": "catalog_reader" }' ``` ## Default request ```json { "dbName": "default", "roleName": "catalog_reader" } ``` ## Sample response ```json { "code": 0, "data": [ { "objectType": "Collection", "objectName": "books", "privilege": "Search", "dbName": "default", "grantor": "root" } ], "description": "Read access for the catalog application" } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `roleName` string (required) Milvus role name. - `description` string Human-readable description. See [`HttpClient.describeRole`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describerole) for the Node.js SDK method. --- # Alter role Update the description of a role. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/alter/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/alter/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/alter/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/alter/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/alter/#request-fields) `POST /v2/vectordb/roles/alter` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/roles/alter' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "roleName": "catalog_reader", "description": "Read access for the catalog application" }' ``` ## Default request ```json { "dbName": "default", "roleName": "catalog_reader", "description": "Read access for the catalog application" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `roleName` string (required) Milvus role name. - `description` string Human-readable description. See [`HttpClient.alterRole`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#alterrole) for the Node.js SDK method. --- # Grant privilege Grant a privilege or privilege group to a role at the specified scope. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege-v2/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege-v2/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege-v2/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege-v2/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege-v2/#request-fields) `POST /v2/vectordb/roles/grant_privilege_v2` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/roles/grant_privilege_v2' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "roleName": "catalog_reader", "privilege": "Search", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "roleName": "catalog_reader", "privilege": "Search", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `roleName` string (required) Milvus role name. - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string Name of the collection. - `privilege` string (required) Name of the privilege to grant or revoke. See [`HttpClient.grantPrivilegeV2`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#grantprivilegev2) for the Node.js SDK method. --- # Revoke privilege Revoke a privilege or privilege group from a role at the specified scope. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege-v2/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege-v2/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege-v2/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege-v2/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege-v2/#request-fields) `POST /v2/vectordb/roles/revoke_privilege_v2` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/roles/revoke_privilege_v2' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "roleName": "catalog_reader", "privilege": "Search", "collectionName": "books" }' ``` ## Default request ```json { "dbName": "default", "roleName": "catalog_reader", "privilege": "Search", "collectionName": "books" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `roleName` string (required) Milvus role name. - `dbName` string Database name. Operations on collections use default when omitted. - `collectionName` string Name of the collection. - `privilege` string (required) Name of the privilege to grant or revoke. See [`HttpClient.revokePrivilegeV2`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#revokeprivilegev2) for the Node.js SDK method. --- # Grant on object (legacy) Grant a privilege using an object type and object name. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/grant-privilege/#request-fields) `POST /v2/vectordb/roles/grant_privilege` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/roles/grant_privilege' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "roleName": "catalog_reader", "objectType": "Collection", "objectName": "books", "privilege": "Search" }' ``` ## Default request ```json { "dbName": "default", "roleName": "catalog_reader", "objectType": "Collection", "objectName": "books", "privilege": "Search" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `roleName` string (required) Milvus role name. - `objectType` string (required) Object type to which the grant applies, such as Collection. - `objectName` string (required) Object name within the grant scope. - `privilege` string (required) Name of the privilege to grant or revoke. - `dbName` string Database name. Operations on collections use default when omitted. See [`HttpClient.grantPrivilegeToRole`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#grantprivilegetorole) for the Node.js SDK method. --- # Revoke on object (legacy) Revoke a privilege using an object type and object name. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/revoke-privilege/#request-fields) `POST /v2/vectordb/roles/revoke_privilege` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/roles/revoke_privilege' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "roleName": "catalog_reader", "objectType": "Collection", "objectName": "books", "privilege": "Search" }' ``` ## Default request ```json { "dbName": "default", "roleName": "catalog_reader", "objectType": "Collection", "objectName": "books", "privilege": "Search" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `roleName` string (required) Milvus role name. - `objectType` string (required) Object type to which the grant applies, such as Collection. - `objectName` string (required) Object name within the grant scope. - `privilege` string (required) Name of the privilege to grant or revoke. - `dbName` string Database name. Operations on collections use default when omitted. See [`HttpClient.revokePrivilegeFromRole`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#revokeprivilegefromrole) for the Node.js SDK method. --- # Drop role Remove a role from the instance. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/roles/drop/#request-fields) `POST /v2/vectordb/roles/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/roles/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "roleName": "catalog_reader" }' ``` ## Default request ```json { "dbName": "default", "roleName": "catalog_reader" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `roleName` string (required) Milvus role name. - `description` string Human-readable description. See [`HttpClient.dropRole`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#droprole) for the Node.js SDK method. --- # List privilege groups List privilege groups and their privileges. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/list/#request-fields) `POST /v2/vectordb/privilege_groups/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/privilege_groups/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default" }' ``` ## Default request ```json { "dbName": "default" } ``` ## Sample response ```json { "code": 0, "data": { "privilegeGroups": [ { "privilegeGroupName": "catalog_reads", "privileges": "Search,Query" } ] } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. See [`HttpClient.listPrivilegeGroups`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listprivilegegroups) for the Node.js SDK method. --- # Create privilege group Create a custom group of privileges. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/create/#request-fields) `POST /v2/vectordb/privilege_groups/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/privilege_groups/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "privilegeGroupName": "catalog_reads" }' ``` ## Default request ```json { "privilegeGroupName": "catalog_reads" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `privilegeGroupName` string (required) Name of the custom privilege group. - `privileges` array of string Privilege names to add or remove. See [`HttpClient.createPrivilegeGroup`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createprivilegegroup) for the Node.js SDK method. --- # Add privileges Add one or more privileges to a custom privilege group. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/add-privileges-to-group/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/add-privileges-to-group/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/add-privileges-to-group/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/add-privileges-to-group/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/add-privileges-to-group/#request-fields) `POST /v2/vectordb/privilege_groups/add_privileges_to_group` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/privilege_groups/add_privileges_to_group' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "privilegeGroupName": "catalog_reads", "privileges": [ "Search", "Query" ] }' ``` ## Default request ```json { "privilegeGroupName": "catalog_reads", "privileges": [ "Search", "Query" ] } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `privilegeGroupName` string (required) Name of the custom privilege group. - `privileges` array of string Privilege names to add or remove. See [`HttpClient.addPrivilegesToGroup`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addprivilegestogroup) for the Node.js SDK method. --- # Remove privileges Remove the specified privileges from a custom privilege group. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/remove-privileges-from-group/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/remove-privileges-from-group/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/remove-privileges-from-group/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/remove-privileges-from-group/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/remove-privileges-from-group/#request-fields) `POST /v2/vectordb/privilege_groups/remove_privileges_from_group` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/privilege_groups/remove_privileges_from_group' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "privilegeGroupName": "catalog_reads", "privileges": [ "Query" ] }' ``` ## Default request ```json { "privilegeGroupName": "catalog_reads", "privileges": [ "Query" ] } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `privilegeGroupName` string (required) Name of the custom privilege group. - `privileges` array of string Privilege names to add or remove. See [`HttpClient.removePrivilegesFromGroup`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#removeprivilegesfromgroup) for the Node.js SDK method. --- # Drop privilege group Delete a custom privilege group. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/privilege-groups/drop/#request-fields) `POST /v2/vectordb/privilege_groups/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/privilege_groups/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "privilegeGroupName": "catalog_reads" }' ``` ## Default request ```json { "privilegeGroupName": "catalog_reads" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `privilegeGroupName` string (required) Name of the custom privilege group. - `privileges` array of string Privilege names to add or remove. See [`HttpClient.dropPrivilegeGroup`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropprivilegegroup) for the Node.js SDK method. --- # List resource groups List query-node resource groups. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/list/#request-fields) `POST /v2/vectordb/resource_groups/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/resource_groups/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{}' ``` ## Default request ```json {} ``` ## Sample response ```json { "code": 0, "data": [ "__default_resource_group", "catalog_queries" ] } ``` ## Request fields This operation accepts an empty JSON object. See [`HttpClient.listResourceGroups`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listresourcegroups) for the Node.js SDK method. --- # Create resource group Create a resource group with an optional query-node allocation configuration. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/create/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/create/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/create/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/create/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/create/#request-fields) `POST /v2/vectordb/resource_groups/create` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/resource_groups/create' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "name": "catalog_queries" }' ``` ## Default request ```json { "name": "catalog_queries" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `name` string (required) Resource name. - `config` object Resource group node allocation, with requests and limits. See [`HttpClient.createResourceGroup`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#createresourcegroup) for the Node.js SDK method. --- # Describe resource group Inspect the configuration and capacity of a resource group. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/describe/#request-fields) `POST /v2/vectordb/resource_groups/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/resource_groups/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "name": "catalog_queries" }' ``` ## Default request ```json { "name": "catalog_queries" } ``` ## Sample response ```json { "resource_group": { "name": "catalog_queries", "capacity": 1, "num_available_node": 1, "num_loaded_replica": { "books": 1 }, "config": { "requests": { "node_num": 1 }, "limits": { "node_num": 1 } }, "nodes": [ { "node_id": 12, "address": "query-node-1:21123", "hostname": "query-node-1" } ] } } ``` ## Request fields - `name` string (required) Resource name. - `config` object Resource group node allocation, with requests and limits. See [`HttpClient.describeResourceGroup`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#describeresourcegroup) for the Node.js SDK method. --- # Update resource groups Change the requested node counts and limits for one or more resource groups. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/alter/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/alter/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/alter/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/alter/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/alter/#request-fields) `POST /v2/vectordb/resource_groups/alter` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/resource_groups/alter' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "resource_groups": { "catalog_queries": { "requests": { "node_num": 1 }, "limits": { "node_num": 1 } } } }' ``` ## Default request ```json { "resource_groups": { "catalog_queries": { "requests": { "node_num": 1 }, "limits": { "node_num": 1 } } } } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `resource_groups` object (required) Map from resource group name to node allocation configuration. See [`HttpClient.updateResourceGroups`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#updateresourcegroups) for the Node.js SDK method. --- # Transfer replicas Move collection replicas between resource groups. The collection must be in the default database and the target group must have available query nodes. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/transfer-replica/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/transfer-replica/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/transfer-replica/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/transfer-replica/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/transfer-replica/#request-fields) `POST /v2/vectordb/resource_groups/transfer_replica` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/resource_groups/transfer_replica' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "sourceRgName": "__default_resource_group", "targetRgName": "catalog_queries", "collectionName": "books", "replicaNum": 1 }' ``` ## Default request ```json { "sourceRgName": "__default_resource_group", "targetRgName": "catalog_queries", "collectionName": "books", "replicaNum": 1 } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `sourceRgName` string (required) Resource group that currently owns the replicas. - `targetRgName` string (required) Resource group that should receive the replicas. - `collectionName` string (required) Name of the collection. - `replicaNum` integer (required) Number of collection replicas to transfer. See [`HttpClient.transferReplica`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#transferreplica) for the Node.js SDK method. --- # Drop resource group Remove a resource group. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/drop/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/drop/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/drop/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/drop/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/resource-groups/drop/#request-fields) `POST /v2/vectordb/resource_groups/drop` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/resource_groups/drop' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "name": "catalog_queries" }' ``` ## Default request ```json { "name": "catalog_queries" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `name` string (required) Resource name. - `config` object Resource group node allocation, with requests and limits. See [`HttpClient.dropResourceGroup`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#dropresourcegroup) for the Node.js SDK method. --- # Run text analyzer Tokenize text using an analyzer configuration or an analyzer-enabled collection field. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/common/run-analyzer/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/common/run-analyzer/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/common/run-analyzer/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/common/run-analyzer/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/common/run-analyzer/#request-fields) `POST /v2/vectordb/common/run_analyzer` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/common/run_analyzer' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "text": [ "Vector search with Milvus" ], "analyzerParams": "{\"tokenizer\":\"standard\"}" }' ``` ## Default request ```json { "dbName": "default", "text": [ "Vector search with Milvus" ], "analyzerParams": "{\"tokenizer\":\"standard\"}" } ``` ## Sample response ```json { "code": 0, "data": { "results": [ { "tokens": [ { "token": "Vector" }, { "token": "search" }, { "token": "with" }, { "token": "Milvus" } ] } ] } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `analyzerParams` string Analyzer configuration encoded as a JSON string. - `text` array of string (required) Input strings to tokenize. - `withDetail` boolean Include detailed token information. - `withHash` boolean Include token hash values. - `collectionName` string Name of the collection. - `fieldName` string Name of the target field. - `analyzerNames` array of string Names of the analyzers to apply. See [`HttpClient.runAnalyzer`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#runanalyzer) for the Node.js SDK method. --- # Register file resource Register a server-accessible file for use by text analyzers. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/add/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/add/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/add/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/add/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/add/#request-fields) `POST /v2/vectordb/file_resources/add` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/file_resources/add' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "name": "dictionary", "path": "s3://example-bucket/analyzers/dictionary.txt" }' ``` ## Default request ```json { "name": "dictionary", "path": "s3://example-bucket/analyzers/dictionary.txt" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `name` string (required) Resource name. - `path` string (required) Server-accessible location of the file resource. See [`HttpClient.addFileResource`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#addfileresource) for the Node.js SDK method. --- # List file resources List registered analyzer file resources. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/list/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/list/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/list/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/list/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/list/#request-fields) `POST /v2/vectordb/file_resources/list` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/file_resources/list' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{}' ``` ## Default request ```json {} ``` ## Sample response ```json { "code": 0, "data": [ { "id": "123456789", "name": "dictionary", "path": "s3://example-bucket/analyzers/dictionary.txt" } ] } ``` ## Request fields This operation accepts an empty JSON object. See [`HttpClient.listFileResources`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#listfileresources) for the Node.js SDK method. --- # Remove file resource Unregister a named file resource. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/remove/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/remove/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/remove/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/remove/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/text-analysis/file-resources/remove/#request-fields) `POST /v2/vectordb/file_resources/remove` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/file_resources/remove' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "name": "dictionary" }' ``` ## Default request ```json { "name": "dictionary" } ``` ## Sample response ```json { "code": 0, "data": {} } ``` ## Request fields - `name` string (required) Resource name. See [`HttpClient.removeFileResource`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#removefileresource) for the Node.js SDK method. --- # Describe segments Inspect segment information for a collection ID or specific segment IDs. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/segments/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/segments/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/segments/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/segments/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/segments/describe/#request-fields) `POST /v2/vectordb/segments/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/segments/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{ "dbName": "default", "collectionID": 123456789, "segmentIDs": [ 123456791 ] }' ``` ## Default request ```json { "dbName": "default", "collectionID": 123456789, "segmentIDs": [ 123456791 ] } ``` ## Sample response ```json { "code": 0, "data": { "segmentInfos": [ { "segmentID": 123456791, "collectionID": 123456789, "partitionID": 123456790, "vChannel": "by-dev-rootcoord-dml_0_123456789v0", "numRows": 1, "state": 4, "level": 2, "isSorted": true, "insertLogs": [ { "fieldID": 100, "logIDs": [ 123456792 ] } ], "deltaLogs": [], "statsLogs": [ { "fieldID": 100, "logIDs": [ 123456793 ] } ] } ] } } ``` ## Request fields - `dbName` string Database name. Operations on collections use default when omitted. - `collectionID` integer Internal collection ID from the collection description. - `segmentIDs` array of integer List of internal segment IDs. See [`HttpClient.getSegmentsInfo`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getsegmentsinfo) for the Node.js SDK method. --- # Describe quota metrics Read quota metrics from the Milvus quota center. SDK: `@zilliz/milvus2-sdk-node@3.0.11` · Tested with Milvus 3.0.7 Canonical documentation: https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/quotacenter/describe/ ## Section links - [cURL command](https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/quotacenter/describe/#curl-command) - [Default request](https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/quotacenter/describe/#default-request) - [Sample response](https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/quotacenter/describe/#sample-response) - [Request fields](https://milvus-io.github.io/milvus-sdk-node/rest-api/diagnostics/quotacenter/describe/#request-fields) `POST /v2/vectordb/quotacenter/describe` Replace `https://your-cluster.example.com` with your Milvus endpoint. Set `MILVUS_TOKEN` for authentication or omit the Authorization header on an unauthenticated cluster. ## cURL command ```bash curl --request POST --url 'https://your-cluster.example.com/v2/vectordb/quotacenter/describe' \ --header 'Content-Type: application/json' \ --header "Authorization: Bearer ${MILVUS_TOKEN}" \ --data-raw '{}' ``` ## Default request ```json {} ``` ## Sample response ```json { "code": 0, "data": "{\"QueryNodeMetrics\":{},\"DataNodeMetrics\":{},\"ProxyMetrics\":{},\"DataCoordMetrics\":null}" } ``` ## Request fields This operation accepts an empty JSON object. See [`HttpClient.getQuotaMetrics`](https://milvus-io.github.io/milvus-sdk-node/api-reference/http-client/#getquotametrics) for the Node.js SDK method.