Skip to content
Vector & metadata

Using Milvus in PEACH

Create a collection, insert vectors with metadata and find similar items, from a notebook, a task or an endpoint.

New to vectors? Start with Understanding vector embeddings. For keyword search and reranking, see Milvus: BM25, hybrid search and reranking.

Install and connect

First install the correct version of pymilvus, any 2.3.x version should suffice:

pip install pymilvus==2.3.5

Now let's create a Milvus client in order to connect to Milvus. Depending on the parameter env, you either connect to the development or the production environment of Milvus, see DEV/PROD environments.

from pipe_algorithms_lib.milvus_utils import MilvusClient

mc = MilvusClient(
    user='ltlrt',  # codops of your organisation
    env='dev',  # Milvus environment, can be either 'dev' or 'prod'.
)

Create a collection

Then, let's create schema for our embeddings collection. Milvus allows us to add fields in addition to just vector fields, so we can later query data not just based on vector similarity, but also to filter items based on other metadata fields (common fields could be category, publication_date, language, etc). We should also create required indexes, to get the most optimal querying performance. You need to ensure that this code is executed once, as we don't want to create new collection for each task execution:

from pymilvus import DataType, FieldSchema

COLLECTION_NAME = 'my_collection'

mc.create_collection(
    collection_name=COLLECTION_NAME,
    dimension=768,
    extra_fields=[
        FieldSchema(name='publication_date', dtype=DataType.INT64),
        FieldSchema(name='language', dtype=DataType.VARCHAR, max_length=16),
        FieldSchema(name='category', dtype=DataType.VARCHAR, max_length=255),
    ],
    indexes={
        'vec': {
            'metric_type': 'IP',
            'index_type': 'HNSW',
            'M': 32,
            'efConstruction': 128,
        },
        'publication_date': None,
        'language': None,
        'category': None,
    }
)

Here we create scalar indexes for all non-vector fields (if we plan to query based on them, but we can always add them later separately) and a vector field index. We use an HNSW index type with some reasonable hyperparameters, but don't hesitate to tune parameters as appropriate. You can read more on different vector index types and their hyperparameters here.

Insert documents

You can now insert documents into the collection, using the Milvus client from above:

from random import random
from datetime import datetime

# normally comes as output from an embedding model, but let's use a random vector for now
vector = [random() for _ in range(768)]

document = {
    'id': 'my_document_42',
    'vec': vector,
    'publication_date': int(datetime(2024, 3, 1, 12, 0, 0).timestamp()),
    'language': 'en',
    'category': 'sports',
}

# here we simply insert a single document. If you have many documents to index - better to send them in larger batches
documents_to_index = [document]

mc.index(
    collection_name=COLLECTION_NAME,
    data=documents_to_index,
    normalize=True,  # whether to normalize input vectors. Usually required if using Cosine Similarity
    upsert=True,  # if upserting - then we override data by `id` to avoid duplicates
    flush=True,  # enabling flushing would make insert slower but we can be sure that data is now queryable
    timeout=5,
)

Retrieve documents by id

If we want to retrieve some documents (to get some metadata for a current item quickly or to get vectors for clustering, for example):

document = mc.get_documents(COLLECTION_NAME, ['my_document_42'], output_fields=['id', 'language', 'vec'])

# document -> {
#   'id': 'my_document_42',
#   'language': 'en',
#   'vec': [-0.041, 0.214, 0.012, -0.112, ...]
# }

Query similar documents

And the most important step is actually querying the data, for find the most similar items to a given vector (useful to use some meaningful embeddings encoder and to have more items in the collection):

filter_expr = 'language == "en" and publication_date >= 1704067200'

recs = mc.retrieve_similar(
    COLLECTION_NAME,
    ids=['my_document_42'],  # if you pass multiple IDs - it finds mean vector from all the input vectors and finds similar to it
    size=10,
    filter_expr=filter_expr,
)

# alternatively, you can pass query vector instead of `ids`, if you want to find similar vectors without inserting current document into the database
recs = mc.retrieve_similar(
    COLLECTION_NAME,
    query_vectors=[vector],
    size=10,
    filter_expr=filter_expr,
)

# If the collection contained other documents:
# recs -> [
#   {'id': 'my_document_42', 'distance': 0.99999},
#   {'id': 'my_document_73', 'distance': 0.86124},
#   {'id': 'my_document_14', 'distance': 0.74124},
#   ...
# ]

Quantization

If you are dealing with a large dataset (millions of embeddings) or trying to squeeze some miliseconds of inference latency - you can consider applying quantization. It's a technique where we take each dimension of an embedding and cast into smaller data type, for example float32 into int8 or even bool. This way we can gain performance improvement searching for similar vectors and at the same time get massive savings in storage. Whilst rather counterintuitive, often taking only direction of the vector (i.e. positive or negative, assuming [-1.0, 1.0] range), we can maintain very high recall, while being able to compress data 32 times! For that we need to do [0.0, 1.0] normalization and cast to 0 or 1 according to selected threshold (typically 0.5 should be a good starting point).

An complete example on how to create Milvus binary index, convert an embedding into encoded binary embedding, insert it into Milvus:

import numpy as np
from pymilvus import FieldSchema, DataType

from pipe_algorithms_lib.milvus_utils import MilvusClient


mc = MilvusClient(user='dedlr', env='dev')

COLLECTION_NAME = 'my_binary_collection'
NUM_DIMS = 768
THRESHOLD = 0.5

mc.create_collection(
    collection_name=COLLECTION_NAME,
    dimension=NUM_DIMS,
    vec_dtype=DataType.BINARY_VECTOR,
)

# already normalized, but you might need to apply normalization separately
random_vector = np.random.rand(NUM_DIMS)
binary_vector = np.where(random_vector > THRESHOLD, 1, 0)
binary_encoded_vector = bytes(np.packbits(binary_vector, axis=-1).tolist())

document = {
    'id': '42',
    'vec': binary_encoded_vector,
}
res = mc.index(COLLECTION_NAME, normalize=False, data=[document])

Then to query this binary collection we also need to provide properly encoded vector:

def revert_to_binary_vector(binary_encoded_vector):
    np_array = np.frombuffer(binary_encoded_vector, dtype=np.uint8)
    binary_vector = np.unpackbits(np_array) 
    return binary_vector


collection = mc.get_collection(COLLECTION_NAME)
vec = revert_to_binary_vector(get_vectors(COLLECTION_NAME, ['42'])[0][0])
binary_vector = bytes(np.packbits(vec, axis=-1).tolist())

res = collection.search([binary_vector], 'vec', param={"metric_type": "HAMMING"}, limit=10)[0]

Using binary quantization helps us to improve inference performance usually around 20% and decrease storage cost by 32x! However first best to start without quantization and only when your collection is large enough - to experiment whether you get good results with binary quantized embeddings!

Next steps