Skip to main content

wmilvus

PyPI version Python versions License

wmilvus is an enterprise-grade, type-safe Milvus Vector Database client wrapper for Python designed with high-level Pydantic ORM model mapping, vector search, multi-collection routing, async support, and audit trail features.

Key Features

  • Pydantic Model Declarations — Define collections as standard Pydantic models with vector annotations (FieldVector, MetricType, IndexType). FieldVector automatically defaults to default_factory=list to prevent missing field validation errors during deserialization.
  • Explicit Schema Generation & Auto-Migration — Every attribute defined in your Pydantic model (str, int, float, bool, list[str], list[int], dict, datetime) is automatically mapped to dedicated Milvus columns (VARCHAR, INT64, DOUBLE, BOOL, ARRAY, JSON) rather than falling into generic dynamic fields ($meta). Existing collections automatically evolve by auto-adding missing columns (add_collection_field) upon client initialization.
  • Collection Lifecycle & Dropping (drop, drop_collection) — Conveniently drop collections from Milvus via db[Model].drop() or db.drop_collection(Model) across synchronous and asynchronous clients.
  • Automatic Vector Retrieval & Preservation — Query methods (get_by_field, filter_by) automatically include vector fields by default (include_vector=True). Calling update() with an empty vector automatically preserves the pre-existing vector from Milvus, eliminating dimension mismatch crashes on partial or metadata-only updates.
  • Dynamic Vector Fields & Auto-ID — Native payload generation supporting custom vector attribute names (embedding, face_vec, etc.) and automated INT64 primary key generation without requiring manual IDs.
  • Universal Primary Key Support — Full compatibility with both auto-increment integer (INT64) and string (VARCHAR) primary keys across all CRUD, filtering, and search routines.
  • Collection Partitioning & Multi-Tenancy — Route insertions, queries, and searches to specific Milvus partitions (partition_name / partition_names).
  • High-Scale Streaming Iterators (iter_all) — Memory-efficient batch streaming across millions of vectors using native Milvus query iterators.
  • Typed Filter Query Builder (filter_by) — Declarative keyword querying with comparison operators (age__gte=18, status__in=[1, 2], frames_ids__contains='f1', dni='00000000P').
  • Vector Similarity & Range Search — KNN similarity search (search_similar), similarity distance scores (search_similar_with_scores), and similarity range threshold search (search_range) with customizable search index parameters (search_params).
  • Batch & Expression Deletion — Flexible record removal via single ID (delete), batch IDs (delete_batch), or scalar filter expressions (delete_by_expr).
  • Multi-Vector & Hybrid Search Rankers — Dense + scalar hybrid search with direct support for Milvus rerankers (RRFRanker, WeightedRanker).
  • High-Performance Non-Blocking Writes & Explicit Flushing — In adherence to official Milvus architecture best practices, automatic forced flush() calls after every insert, insert_batch, and update have been removed (auto_flush=False by default). This eliminates severe I/O latency bottlenecks, query node memory saturation, and tiny segment fragmentation caused by sealing growing segments prematurely. If immediate read-after-write consistency is needed, Milvus's native consistency_level="Strong" or "Session" is recommended. Manual flushing is available via db.flush() or db[Model].flush() when required administratively.
  • Bulk Vector Ingestion — High-performance chunked bulk insertion (insert_batch) with automatic payload chunking and ID propagation.
  • Async Client Support (AsyncWMilvus) — Full non-blocking async mirror with async with context manager for FastAPI and asyncio applications.
  • Schema Verification & Dimension Mismatch Detection — Verification of Pydantic model vector dimensions against active Milvus collection schemas with explicit warning logging when existing server collections deviate from declared dimensions.
  • Optional Vector Fields & Scalar-Only Collections — Collections do not strictly require vector fields. Pure scalar or metadata models (e.g., users, categories, configurations, relational entities) can be defined without any vector fields. WMilvus transparently satisfies Milvus's internal vector requirement under the hood with lightweight synthetic dummy vectors, enabling full type-safe CRUD, filtering, streaming, and multi-table querying without imposing vectors on your models.
  • Single & Multi-Collection ORM Routing — Automatic collection creation and full multi-table query support: call db.get_all() across all registered collections simultaneously, scope queries by model class (db.get_all(Model) or db[Model].get_all()), or access repositories directly by attribute (db.modelname).
  • Enterprise Ghost Audit Log (_forensic_audit_log) — Global audit trail tracking INSERT, UPDATE, SOFT_DELETE, and HARD_DELETE operations for models inheriting from ForensicModel with safe JSON ISO-8601 datetime serialization.
  • Automated Collection Memory Loading — Transparent auto-loading (load_collection) into memory for pre-existing or offline Milvus collections upon connection.
  • Flexible Client Instantiation — Versatile initialization supporting WMilvus(uri, models=[...]), WMilvus(models=[...], uri=...), and config dictionaries without rigid positional restrictions.
  • SQLite Vector Backup & Import (wsqlite) — Native ORM-based backup export (export_to_sqlite) and restoration (import_from_sqlite) powered by wsqlite.
  • Dockerized Test Runner & Coverage — Out-of-the-box support for isolated container testing (run_tests_docker.sh) and HTML coverage reports (run_coverage.sh).

Key Technologies and Libraries

Component Technology
Language Python 3.9+
Vector Engine Milvus 2.3+
SDK Core pymilvus 2.3+
Backup Storage wsqlite 1.5+
Data Validation Pydantic 2.x
Numerical Core NumPy
Logging Loguru
CLI Framework Click
Packaging & Build setuptools>=61.0, wheel
Testing Framework pytest, pytest-cov

Quick Start

from typing import List
from pydantic import BaseModel
from wmilvus import FieldVector, MetricType, WMilvus


class UserFace(BaseModel):
    id: str
    name: str
    face_embedding: List[float] = FieldVector(dim=128, metric_type=MetricType.COSINE)


# Context Manager Usage
with WMilvus(UserFace, uri="http://localhost:19530") as db:
    # 1. Insert Pydantic record
    user = UserFace(id="u_001", name="William Rodriguez", face_embedding=[0.1] * 128)
    db.insert(user)

    # 2. Vector Similarity Search returning typed Pydantic instances
    matches = db.search_similar(vector=[0.1] * 128, top_k=5)
    print(f"Top match: {matches[0].name}")

    # 3. Vector Search with Similarity Scores
    matches_with_scores = db.search_similar_with_scores(vector=[0.1] * 128, top_k=5)
    print(f"Score: {matches_with_scores[0].distance:.4f}")

Async Quick Start

import asyncio
from wmilvus import AsyncWMilvus, FieldVector, MetricType
from pydantic import BaseModel


class Telemetry(BaseModel):
    id: str
    vector: List[float] = FieldVector(dim=4, metric_type=MetricType.COSINE)


async def main():
    async with AsyncWMilvus(Telemetry, uri="http://localhost:19530") as db:
        await db.insert(Telemetry(id="t1", vector=[0.5, 0.5, 0.0, 0.0]))
        results = await db.search_similar(vector=[0.5, 0.5, 0.1, 0.0], top_k=1)
        print(results[0].id)


asyncio.run(main())

Write Performance & Consistency

By default in wmilvus>=0.4.6, automatic flush() calls during insert(), insert_batch(), and update() are disabled (auto_flush=False). Calling flush() after every write is strongly discouraged by official Milvus documentation because it forcibly seals growing segments in memory, writes tiny files to storage, and triggers expensive background compactions.

  • Immediate Visibility / Read-After-Write Consistency: If your application or tests require immediate visibility of newly inserted entities without incurring I/O penalties, use Milvus's native consistency_level="Strong" or "Session":
    db = WMilvus(UserFace, uri="http://localhost:19530", consistency_level="Strong")
    
  • Manual Administrative Flush: When necessary (e.g., before stopping an instance or following an offline migration), trigger a flush explicitly:
    # Flush all registered collections
    db.flush()
    
    # Flush a single collection
    db[UserFace].flush()
    
    # Asynchronous flush
    await async_db.flush()
    
  • Per-operation Auto-Flush: If you explicitly want a specific write operation to trigger a flush:
    db.insert(user, auto_flush=True)
    db.insert_batch(users, auto_flush=True)
    db.update("u_001", user, auto_flush=True)
    

Organized Examples

The repository includes organized example scripts in examples/:

Running Tests

Execute unit tests inside an isolated Docker container:

./run_tests_docker.sh

Calculate code coverage locally:

./run_coverage.sh

Metadata

Release files for wmilvus 0.4.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for wmilvus 0.4.6
File Size Uploaded Provenance Actions
wmilvus-0.4.6.tar.gz 39.6 kB Without provenance Details for wmilvus-0.4.6.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for wmilvus 0.4.6
File Interpreter ABI Platform Actions
wmilvus-0.4.6-py3-none-any.whl Python 3 none any Details for wmilvus-0.4.6-py3-none-any.whl

Total release size: 65.9 kB

Release files / wmilvus-0.4.6.tar.gz

Download URL wmilvus-0.4.6.tar.gz
Size 39.6 kB
Tags Source
SHA-256 checksum
How to use checksums
49445a59dd7ada4dc76fe1922b1e817b194a61122ddb79db30e4f828111149a3
BLAKE2b-256 checksum
How to use checksums
f80cabe86164d550043729c507d7f5d071480aa9b75bb5debeda9674e503606b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.5

Release files / wmilvus-0.4.6-py3-none-any.whl

Download URL wmilvus-0.4.6-py3-none-any.whl
Size 26.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9d7dc1967220e76d2bb885dca6df590c9292e2786ed654d3bacf4be72b66b0fd
BLAKE2b-256 checksum
How to use checksums
2e7ff9b10f5edf39803ad9442bcaa88bde96e7fc496a2ce3fcfb43fa8fca6d11
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.5

Security for wmilvus 0.4.6

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page