Milvus Code Examples and Tutorials
This guide provides comprehensive examples and tutorials for common use cases.
Basic CRUD Operations
Section titled “Basic CRUD Operations”Complete Example
Section titled “Complete Example”import { MilvusClient, DataType } from '@zilliz/milvus2-sdk-node';
const client = new MilvusClient({ address: 'localhost:19530',});
await client.connectPromise;
// Create collectionconst 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 dataconst 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 indexawait client.createIndex({ collection_name: 'my_collection', field_name: 'vector', index_type: 'HNSW', metric_type: 'L2',});
// Load collectionawait client.loadCollectionSync({ collection_name: 'my_collection',});
// Searchconst 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);
// Queryconst queryResults = await client.query({ collection_name: 'my_collection', expr: 'text == "Hello Milvus"', output_fields: ['id', 'text'],});
console.log('Query results:', queryResults.data);
// Deleteconst deleteResult = await client.delete({ collection_name: 'my_collection', ids: [ids[0]],});console.log('Deleted rows:', deleteResult.delete_cnt);
// Drop collectionawait client.dropCollection({ collection_name: 'my_collection',});await client.closeConnection();Vector Similarity Search
Section titled “Vector Similarity Search”Image Search Example
Section titled “Image Search Example”import { MilvusClient, DataType } from '@zilliz/milvus2-sdk-node';
const client = new MilvusClient({ address: 'localhost:19530',});
await client.connectPromise;
// Create collection for image embeddingsawait 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 embeddingsawait 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 indexawait client.createIndex({ collection_name: 'image_collection', field_name: 'image_embedding', index_type: 'HNSW', metric_type: 'COSINE',});
// Load and searchawait 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
Section titled “Hybrid Search”Multi-Vector Search
Section titled “Multi-Vector Search”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 fieldsawait 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 vectorsawait 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 collectionawait client.loadCollectionSync({ collection_name: 'hybrid_collection',});
// Hybrid searchconst 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
Section titled “Dynamic Schema Usage”Flexible Schema Example
Section titled “Flexible Schema Example”// Create collection with dynamic fields enabledawait 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 fieldsawait 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
Section titled “Partition Key Usage”Time-Based Partitioning
Section titled “Time-Based Partitioning”// Create collection with partition keyawait 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
Section titled “Multi-Database Setup”Database Management Example
Section titled “Database Management Example”// Create databaseawait client.createDatabase({ db_name: 'production_db',});
// Create client for specific databaseconst prodClient = new MilvusClient({ address: 'localhost:19530', database: 'production_db',});
// Create collection in production databaseawait 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 databasesconst 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
Section titled “Authentication Examples”Basic Authentication
Section titled “Basic Authentication”const client = new MilvusClient({ address: 'localhost:19530', username: 'root', password: 'Milvus',});
await client.connectPromise;Token Authentication (Zilliz Cloud)
Section titled “Token Authentication (Zilliz Cloud)”const client = new MilvusClient({ address: 'your-endpoint.zillizcloud.com:443', token: 'your-api-key', ssl: true,});
await client.connectPromise;Next.js Integration
Section titled “Next.js Integration”API Route Example
Section titled “API Route Example”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
Section titled “LangChain Integration”LangChain.js Example
Section titled “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.
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
Section titled “Cloud Deployment”Zilliz Cloud Example
Section titled “Zilliz Cloud Example”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
Section titled “Error Handling Pattern”Comprehensive Error Handling
Section titled “Comprehensive Error Handling”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; }}
// Usageawait safeOperation(() => client.createCollection({ collection_name: 'my_collection', fields: schema, }));Next Steps
Section titled “Next Steps”- Explore Best Practices
- Check out API Reference
- Read Troubleshooting