Use Apache Beam and Milvus to enrich data

Run in Google Colab View source on GitHub

This notebook shows how to enrich data by using the Apache Beam enrichment transform with Milvus. The enrichment transform is an Apache Beam turnkey transform that lets you enrich data by using a key-value lookup. This transform has the following features:

  • The transform has a built-in Apache Beam handler that interacts with Milvus data during enrichment.
  • The enrichment transform uses client-side throttling to rate limit the requests. The default retry strategy uses exponential backoff. You can configure rate limiting to suit your use case.

This notebook demonstrates the following search engine optimization use case:

A specialized technical search engine company wants to improve its query result relevance by dynamically enriching search results with semantically related content. The example uses a vector database of technical articles and documentation stored in Milvus to enrich incoming user queries. The enriched data is then used to provide users with more comprehensive and contextually relevant search results, especially for complex technical topics.

Before you begin

Set up your environment and download dependencies.

Install Apache Beam

To use the enrichment transform with the built-in Milvus handler, install the Apache Beam SDK version 2.67.0 or later.

# Disable tokenizers parallelism to prevent deadlocks when forking processes
# This avoids the "huggingface/tokenizers: The current process just got forked" warning.
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# The Apache Beam test dependencies are included here for the TestContainers
# Milvus standalone DB container that will be used later in the demo.
pip install rich sentence_transformers llama_index --quiet
pip install apache_beam[milvus,gcp,test,interactive] --quiet
# Standard library imports
from collections import defaultdict
from dataclasses import asdict
from math import ceil
from typing import Any, Dict, List
import tempfile
import uuid
import shutil

# Third-party imports
import numpy as np
import pandas as pd
from pymilvus import (
    DataType, 
    CollectionSchema, 
    FieldSchema, 
    Function, 
    FunctionType, 
    MilvusClient, 
    RRFRanker
)
from pymilvus.milvus_client import IndexParams
from rich import print_json
from sentence_transformers import SentenceTransformer
from torch import cuda
from llama_index.core.text_splitter import SentenceSplitter

# Apache Beam imports
import apache_beam as beam
from apache_beam.ml.rag.types import Chunk, Content, Embedding
from apache_beam.ml.rag.chunking.base import ChunkingTransformProvider
from apache_beam.ml.rag.embeddings.huggingface import HuggingfaceTextEmbeddings
from apache_beam.ml.rag.enrichment.milvus_search_it_test import MilvusEnrichmentTestHelper
from apache_beam.ml.rag.enrichment.milvus_search import (
    HybridSearchParameters, 
    KeywordSearchMetrics, 
    KeywordSearchParameters,
    MilvusCollectionLoadParameters, 
    MilvusConnectionParameters, 
    MilvusSearchEnrichmentHandler,
    MilvusSearchParameters, 
    SearchStrategy, 
    VectorSearchMetrics, 
    VectorSearchParameters
)
from apache_beam.ml.transforms.base import MLTransform
from apache_beam.ml.transforms.embeddings import huggingface
from apache_beam.runners.interactive import interactive_beam as ib
from apache_beam.transforms.enrichment import Enrichment
/home/dev/beam/sdks/python/.venv/lib/python3.9/site-packages/pydantic/_internal/_generate_schema.py:2249: UnsupportedFieldAttributeWarning: The 'validate_default' attribute with value True was provided to the `Field()` function, which has no effect in the context it was used. 'validate_default' is field-specific metadata, and can only be attached to a model field using `Annotated` metadata or by assignment. This may have happened because an `Annotated` type alias using the `type` statement was used, or if the `Field()` function was attached to a single member of a union type.
  warnings.warn(

Collect Data

This content has been paraphrased from publicly available information on the internet using a large language model (OpenAI’s GPT-4) and is provided for informational purposes only.

The third data point, related to Google Beam, was intentionally included to illustrate the importance of metadata filtering (filtered search) in Milvus—such as when a user searches for the term “Beam.” without it the vector database retrieval engine may confuse between Apache Beam and Google Beam.

corpus = [
  {
    "id": "1",
    "title": "Apache Beam: Unified Model for Batch and Streaming Data",
    "keywords": ["Apache Beam", "stream processing", "batch processing", "data pipelines", "SDK"],
    "tags": ["Data Engineering", "Open Source", "Streaming", "Batch", "Big Data"],
    "content": (
      "Apache Beam is an open-source framework that provides a consistent programming model for both batch and streaming data processing. "
      "Developed originally by Google, it allows developers to write pipelines that can run on multiple engines, such as Apache Flink, Spark, and Google Cloud Dataflow. "
      "Beam uses abstractions like PCollections (data containers) and PTransforms (operations) to define the flow of data. "
      "The framework promotes portability through its runner architecture, letting the same pipeline execute on different backends. "
      "Support for multiple SDKs, including Java and Python, makes it accessible for a broad audience. "
      "Key features include support for event time, windowing, triggers, and stateful processing, which are essential for handling real-time data effectively. "
      "Beam is ideal for building ETL jobs, real-time analytics, and machine learning data pipelines. "
      "It helps teams focus on logic rather than infrastructure, offering flexibility and scalability in handling unbounded and bounded data sources. "
      "Apache Beam also supports a wide range of connectors for both input and output, including Kafka, BigQuery, and JDBC-based systems. "
      "This makes it easy to integrate Beam into existing data ecosystems. Developers can build reusable transforms and modularize pipeline logic, improving maintainability and testing. "
      "The concept of runners enables developers to write once and run anywhere, which is particularly appealing for organizations that want to avoid vendor lock-in. "
      "The Beam model is based on a unified programming model that decouples pipeline logic from execution. "
      "This makes it easier to reason about time and state in both batch and streaming pipelines. "
      "Advanced features like late data handling, watermarks, and session windowing allow for more accurate and meaningful processing of real-world data. "
      "Beam also integrates with orchestration tools and monitoring systems, allowing for production-grade deployments. "
      "Community support and contributions have grown significantly, making Beam a stable and evolving ecosystem. "
      "Many cloud providers offer native support for Beam pipelines, and it's increasingly a core component in modern data platform architectures."
    )
  },
  {
    "id": "2",
    "title": "Google Cloud Dataflow: Run Apache Beam in the Cloud",
    "keywords": ["Google Cloud", "Dataflow", "Apache Beam", "serverless", "stream and batch"],
    "tags": ["Cloud Computing", "Data Pipelines", "Google Cloud", "Serverless", "Enterprise"],
    "content": (
      "Google Cloud Dataflow is a fully managed service that runs Apache Beam pipelines in the cloud. "
      "It abstracts away infrastructure management and handles dynamic scaling, load balancing, and fault tolerance. "
      "Developers can focus on writing data logic using the Beam SDK and deploy it easily to Google Cloud. "
      "Dataflow supports both batch and stream processing and integrates seamlessly with other Google services like BigQuery, Pub/Sub, and Cloud Storage. "
      "Its autoscaling capabilities allow it to adapt to changing data volumes, optimizing for cost and performance. "
      "Features like monitoring dashboards, job templates, and built-in logging make it suitable for both development and production use. "
      "With support for event time processing, stateful functions, and windowing, Dataflow is well-suited for real-time analytics and data transformation tasks. "
      "It’s a key component for architects building scalable, cloud-native data platforms. "
      "Dataflow also offers templates for common ETL tasks, helping teams get started quickly with minimal setup. "
      "Its integration with Cloud Functions and Cloud Composer enables event-driven and orchestrated workflows. "
      "Security and compliance are built-in with IAM roles, encryption at rest and in transit, and audit logging, making it suitable for enterprise environments. "
      "For developers, Dataflow provides local testing capabilities and a unified logging system through Cloud Logging. "
      "It also supports SQL-based pipeline definitions using BigQuery, which lowers the barrier to entry for analysts and data engineers. "
      "Dataflow’s streaming engine significantly improves performance and reduces costs by decoupling compute and state management. "
      "In summary, Google Cloud Dataflow not only simplifies the deployment of Apache Beam pipelines but also enhances them with cloud-native features. "
      "Its managed runtime, high availability, and integration with the broader Google Cloud ecosystem make it a powerful tool for modern data processing."
    )
  },
  {
    "id": "3",
    "title": "Google Beam: 3D Communication Powered by AI",
    "keywords": ["Google Beam", "Project Starline", "3D video", "AI communication", "real-time meetings"],
    "tags": ["AI", "Communication", "3D Technology", "Remote Work", "Enterprise Tech"],
    "content": (
      "Google Beam is an innovative video communication platform that builds on the research of Project Starline. It uses AI, 3D imaging, and light field rendering to create immersive, lifelike video calls. "
      "Designed to replicate in-person interaction, Beam allows users to see life-sized, three-dimensional representations of each other without the need for headsets. "
      "This breakthrough makes remote conversations feel natural—capturing facial expressions, eye contact, and subtle gestures that traditional video conferencing often misses. "
      "Beam reduces meeting fatigue and enhances engagement, making it ideal for enterprise collaboration, interviews, and virtual presence scenarios. "
      "Powered by Google AI, Beam represents a significant leap in communication technology. "
      "Major companies like Salesforce, Deloitte, and NEC are already exploring its impact on digital collaboration. "
      "Google is partnering with HP to build and distribute Beam hardware, designed to work with existing productivity and video tools. "
      "Currently in limited early access for enterprise partners, Google Beam aims to redefine virtual meetings by bridging the gap between digital and physical presence. "
      "It’s a promising step toward more human and effective remote interactions."
    )
  }
]

Exploratory Data Analysis (EDA)

Average Words/Tokens per Doc

# The second video may skew the average tokens results since it is a youtube short video.
contents = [c['content'] for c in corpus]
content_lengths = [len(content.split(" ")) for content in contents]
df = pd.DataFrame(content_lengths, columns=['# Words'])
df.describe()
mean_word_count = ceil(np.mean(content_lengths))
token_to_word_ratio = 1.3
approx_token_count = ceil(mean_word_count * token_to_word_ratio)
print(f'The mean word count for each video is about {mean_word_count} words, which corresponds to a rough token count of {approx_token_count} tokens.')
The mean word count for each video is about 254 words, which corresponds to a rough token count of 331 tokens.

Milvus Sink I/O

This could be delegated to the Beam Milvus Sink I/O once it is implemented. For now, we will use pymilvs client directly for indexing.

Setup Milvus

db = None
milvus_version = "milvusdb/milvus:v2.5.10"
if db:
    # Stop existing Milvus DB container to prevent duplicates.
    MilvusEnrichmentTestHelper.stop_db_container(db)
db = MilvusEnrichmentTestHelper.start_db_container(milvus_version)
milvus_connection_parameters = MilvusConnectionParameters(uri=db.uri, user=db.user, password=db.password, db_id=db.id)
client = MilvusClient(**milvus_connection_parameters.__dict__)
client.get_server_version()
'2.5.10'

Define Vector Schema and Indices

Define Fields

# Choosing `sentence-transformers/all-MiniLM-L6-v2` as our embedding generator here. It gives
# a good balance between embedding generation speed, accuracy, and being free to use.
embedding_model_config = {
    "name": 'sentence-transformers/all-MiniLM-L6-v2',
    "token_limit": 384
}
fields = [
    FieldSchema(name="id", dtype=DataType.VARCHAR, is_primary=True, max_length=100),
    FieldSchema(name="content", dtype=DataType.VARCHAR, max_length=65279),
    FieldSchema(name="embedding", dtype=DataType.FLOAT_VECTOR, dim=embedding_model_config["token_limit"]),
    FieldSchema(name="sparse_embedding", dtype=DataType.SPARSE_FLOAT_VECTOR),
    FieldSchema(name="metadata", dtype=DataType.JSON),
    FieldSchema(name="title_and_content", dtype=DataType.VARCHAR, max_length=65279+256, enable_analyzer=True),
]

Define Functions for Processing

bm25_function = Function(
    name="content_bm25_emb",
    input_field_names=["title_and_content"],
    output_field_names=["sparse_embedding"],
    function_type=FunctionType.BM25)

functions = [bm25_function]
schema = CollectionSchema(fields=fields,functions=functions)
schema
{'auto_id': False, 'description': '', 'fields': [{'name': 'id', 'description': '', 'type': <DataType.VARCHAR: 21>, 'params': {'max_length': 100}, 'is_primary': True, 'auto_id': False}, {'name': 'content', 'description': '', 'type': <DataType.VARCHAR: 21>, 'params': {'max_length': 65279} }, {'name': 'embedding', 'description': '', 'type': <DataType.FLOAT_VECTOR: 101>, 'params': {'dim': 384} }, {'name': 'sparse_embedding', 'description': '', 'type': <DataType.SPARSE_FLOAT_VECTOR: 104>, 'is_function_output': True}, {'name': 'metadata', 'description': '', 'type': <DataType.JSON: 23>}, {'name': 'title_and_content', 'description': '', 'type': <DataType.VARCHAR: 21>, 'params': {'max_length': 65535, 'enable_analyzer': True} }], 'enable_dynamic_field': False, 'functions': [{'name': 'content_bm25_emb', 'description': '', 'type': <FunctionType.BM25: 1>, 'input_field_names': ['title_and_content'], 'output_field_names': ['sparse_embedding'], 'params': {} }]}

Define Indices

index_params = IndexParams()

Define Dense Vector Index

index_params.add_index(
    field_name="embedding",
    index_name="dense_embedding_ivf_flat",
    index_type="IVF_FLAT",
    metric_type=VectorSearchMetrics.COSINE.value,
    params={"nlist": 1024})

Define Sparse Vector Index

index_params.add_index(
    field_name="sparse_embedding",
    index_name="sparse_inverted_index",
    index_type="SPARSE_INVERTED_INDEX",
    metric_type=KeywordSearchMetrics.BM25.value,
    params={"inverted_index_algo": "DAAT_MAXSCORE", "bm25_k1": 1.2, "bm25_b": 0.75})
index_params
[{'field_name': 'embedding', 'index_type': 'IVF_FLAT', 'index_name': 'dense_embedding_ivf_flat', 'nlist': 1024, 'metric_type': 'COSINE'},
 {'field_name': 'sparse_embedding', 'index_type': 'SPARSE_INVERTED_INDEX', 'index_name': 'sparse_inverted_index', 'inverted_index_algo': 'DAAT_MAXSCORE', 'bm25_k1': 1.2, 'bm25_b': 0.75, 'metric_type': 'BM25'}]

Create Collection

collection_name = "beam_minilm_256"
client.drop_collection(collection_name=collection_name)
client.create_collection(collection_name=collection_name, schema=schema, index_params=index_params)
client.has_collection(collection_name)
True

Building the Vector Index: Chunking, Embedding, and Storage

class DocumentSplitterDoFn(beam.DoFn):
    def setup(self):
        # The `chunk_size` parameter is constrained by the embedding model we’re using.
        # Since we’re using `sentence-transformers/all-MiniLM-L6-v2`, which has a maximum
        # token limit of ~384 tokens, we need to ensure chunk sizes stay well within that limit.
        # Given that each document in our dataset contains approximately 331 tokens, using a chunk
        # size of 256 allows us to preserve nearly the most semantic meaning of each entry while
        # staying safely under the model’s token limit.
        #
        # For simplicity, We'll use sentence splitting as the chunking strategy for simplicity. Ideally,
        # we would pass a tokenizer here — preferably the same one used by the retriever to ensure
        # consistency. However, in this example, we are not using a tokenizer.
        from llama_index.core.text_splitter import SentenceSplitter
        chunk_size, chunk_overlap = 256, 20
        self.llama_txt_splitter = SentenceSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)

    def process(self, element: Dict[str, Any]) -> List[Chunk]:
        id_field, content_field = 'id', 'content'
        metadata_fields = ["title", "keywords", "tags"]
        global_doc_id = element.get('id', str(uuid.uuid4()))
        text_content = element.get('content', '')
        splits = self.llama_txt_splitter.split_text(text_content)
        for i, split in enumerate(splits):
            local_doc_id = f"{global_doc_id}_{i}"
            yield Chunk(id=local_doc_id, content=Content(split), metadata={f:element[f] for f in metadata_fields})

class ChunkingTransformProvider(ChunkingTransformProvider):
    def get_splitter_transform(self) -> beam.PTransform[beam.PCollection[Dict[str, Any]], beam.PCollection[Chunk]]:
        return beam.ParDo(DocumentSplitterDoFn())

class IndexToVectorDBDoFn(beam.DoFn):
    def __init__(self, collection_name: str, batch_size: int = 100):
        self.collection_name = collection_name
        self.batch_size = batch_size

    def setup(self):
        self._client = MilvusClient(**milvus_connection_parameters.__dict__)

    def start_bundle(self):
        self._batch = []

    def process(self, doc: Chunk):
        doc_to_index = {
            "id": doc.id,
            "content": doc.content.text,
            "title_and_content": f"{doc.metadata['title']}. {doc.content.text}",
            "metadata": doc.metadata,
            "embedding": doc.embedding.dense_embedding,
        }
        self._batch.append(doc_to_index)

        if len(self._batch) >= self.batch_size:
            self._flush_batch()

        yield doc_to_index

    def finish_bundle(self):
        if self._batch:
            self._flush_batch()

    def _flush_batch(self):
        if self._batch:
            # Upsert API gives us a built-in idempotency over the insert API.
            result = self._client.upsert(collection_name=self.collection_name, data=self._batch)
            print(f"Upserted batch of {len(self._batch)} documents. Result: {result}")
            self._batch = []

huggingface_embedder = HuggingfaceTextEmbeddings(
    model_name=embedding_model_config["name"],
    max_seq_length=embedding_model_config["token_limit"])

with beam.Pipeline() as pipeline:
    data_transformed = (
        pipeline
        | 'Creating Documents' >> beam.Create(corpus)
        | 'Converting to Chunks' >> MLTransform(
            write_artifact_location=tempfile.mkdtemp()).with_transform(ChunkingTransformProvider())
        | 'Generating Embeddings' >> MLTransform(
            write_artifact_location=tempfile.mkdtemp()).with_transform(huggingface_embedder)
        | 'Indexing to Vector DB' >> beam.ParDo(IndexToVectorDBDoFn(collection_name=collection_name))
    )

ib.show(data_transformed)
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.
Upserted batch of 5 documents. Result: {'upsert_count': 5, 'primary_keys': ['1_0', '1_1', '2_0', '2_1', '3_0']}
Upserted batch of 5 documents. Result: {'upsert_count': 5, 'primary_keys': ['1_0', '1_1', '2_0', '2_1', '3_0']}

Milvus Beam Enrichment Handler

Prep for Milvus Beam Enrichment Handler

class FormatAndPrintResults(beam.PTransform):
    def expand(self, pcoll):
        return pcoll | beam.Map(self.format_and_print)

    @staticmethod
    def format_and_print(chunk):
        # Create a clean structure to display.
        formatted_result = {
            "query": chunk.content.text,
            "query_embedding": FormatAndPrintResults.get_embedding_count(chunk),
            "results": []
        }

        # Extract the enrichment data
        enrichment_data = chunk.metadata.get('enrichment_data', defaultdict(list))

        # Format each result with its distance score
        for i in range(len(enrichment_data.get('id', []))):
            result = {
                "id": enrichment_data['id'][i],
                "distance": round(enrichment_data['distance'][i], 4),
                "fields": enrichment_data['fields'][i] if i < len(enrichment_data.get('fields', [])) else {}
            }
            formatted_result["results"].append(result)

        # Sort by distance in descending order (highest/best first)
        formatted_result["results"] = sorted(formatted_result["results"], key=lambda x: x["distance"], reverse=True)

        # Print the formatted JSON
        print_json(data=formatted_result)

        # Return the original chunk for further processing if needed
        return chunk

    @staticmethod
    def get_embedding_count(chunk):
        if chunk.embedding:
            if chunk.embedding.dense_embedding:
                return len(chunk.embedding.dense_embedding)
            if chunk.embedding.sparse_embedding:
                return len(chunk.embedding.sparse_embedding)

Let’s choose a deliberate query that illustrates the unique benefits of pure vector search, especially its ability to grasp semantic meaning:

Query: How do I process large datasets efficiently?

This query demonstrates vector search advantages because:

  • Dense vector (semantic) contribution: The semantic component understands the conceptual intent of "processing large datasets efficiently," connecting it to frameworks like Apache Beam and Google Cloud Dataflow, even if those terms aren't in the query.
  • Overcoming keyword limitations: For conversational queries like this, traditional keyword search struggles. Vector search moves beyond exact lexical matching to find documents that semantically answer the "how-to" aspect.
  • Vector search advantage: Documents describing solutions like Apache Beam (e.g., Document #1) rank highest. Vector search understands that Beam's "unified programming model for defining and executing data processing pipelines" directly addresses the query's need for efficient large dataset processing, even without an exact phrase match, by prioritizing based on deep semantic alignment.
query = "How do I process large datasets efficiently?"
query_chunk = Chunk(content=Content(text=query))
search_parameters = MilvusSearchParameters(
    collection_name=collection_name,
    search_strategy=VectorSearchParameters(limit=10, anns_field="embedding"),
    output_fields=["metadata","content"])
collection_load_parameters = MilvusCollectionLoadParameters()
milvus_handler = MilvusSearchEnrichmentHandler(
    connection_parameters=milvus_connection_parameters,
    search_parameters=search_parameters,
    collection_load_parameters=collection_load_parameters)
with beam.Pipeline() as p:
    _ = (
        p
        | "Creating Queries" >> beam.Create([query_chunk])
        | 'Generating Embeddings' >> MLTransform(
            write_artifact_location=tempfile.mkdtemp()).with_transform(huggingface_embedder)
        | "Enriching W/ Milvus Vector Search" >> Enrichment(milvus_handler)
        | "Formatting and Printing Results" >> FormatAndPrintResults())
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.

Let’s choose a deliberate query that illustrates the unique benefits of pure keyword search, especially its ability to pinpoint exact textual matches:

Query: Project Starline

This query demonstrates keyword search advantages because:

  • Keyword (lexical) contribution: The query, Project Starline, is an exact phrase. Keyword search is designed to prioritize and precisely match such literal strings, acting as an exact textual filter for specific product names or unique identifiers.
  • Overcoming vector limitations: For a highly specific, proper noun like "Project Starline", pure vector search might struggle. It could semantically relate to other "projects" or "communication technologies," potentially diluting the precision by not inherently prioritizing the exact string match over broader semantic similarity.
  • Keyword search advantage: Only Document 3 ("Google Beam: 3D Communication Powered by AI") contains the exact phrase: Google Beam is an innovative video communication platform that builds on the research of Project Starline. A keyword search for "Project Starline" will exclusively and precisely retrieve Document 3, showcasing its unparalleled accuracy for factual lookups and named entities where the exact string is paramount.
query = "Project Starline"
query_chunk = Chunk(content=Content(text=query))
search_parameters = MilvusSearchParameters(
    collection_name=collection_name,
    search_strategy=KeywordSearchParameters(limit=10,anns_field="sparse_embedding"),
    output_fields=["metadata","content"])
collection_load_parameters = MilvusCollectionLoadParameters()
milvus_handler = MilvusSearchEnrichmentHandler(
    connection_parameters=milvus_connection_parameters,
    search_parameters=search_parameters,
    collection_load_parameters=collection_load_parameters)
with beam.Pipeline() as p:
    _ = (
        p
        | "Creating Queries" >> beam.Create([query_chunk])
        | 'Generating Embeddings' >> MLTransform(
            write_artifact_location=tempfile.mkdtemp()).with_transform(huggingface_embedder)
        | "Enriching W/ Milvus Keyword Search" >> Enrichment(milvus_handler)
        | "Formatting and Printing Results" >> FormatAndPrintResults()
    )
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.

Let’s choose a deliberate query that illustrates the unique benefits of hybrid search:

Query: real-time data processing systems

This query demonstrates hybrid search advantages because:

  • Dense vector (semantic) contribution: Will understand the conceptual relationship between "real-time processing" and "streaming" (found in docs #1 and #2)
  • Sparse vector (keyword) contribution: Will match exact terms like "data" and "processing" (found in docs #1 and #2)
  • Hybrid advantage: Document #1 about Apache Beam should rank highest since it contains more specific technical details about real-time processing capabilities like "event time," "triggers," and "stateful processing" - even though the exact phrase "real-time data processing" doesn't appear in any document
query = "real-time data processing system"
query_chunk = Chunk(content=Content(text=query))
hybrid_search_parameters = HybridSearchParameters(
    vector=VectorSearchParameters(limit=10,anns_field="embedding"),
    keyword=KeywordSearchParameters(limit=10,anns_field="sparse_embedding"),
    ranker=RRFRanker(3),
    limit=2)
search_parameters = MilvusSearchParameters(
    collection_name=collection_name,
    search_strategy=hybrid_search_parameters,
    output_fields=["metadata", "content"])
collection_load_parameters = MilvusCollectionLoadParameters()
milvus_handler = MilvusSearchEnrichmentHandler(
    connection_parameters=milvus_connection_parameters,
    search_parameters=search_parameters,
    collection_load_parameters=collection_load_parameters)
with beam.Pipeline() as p:
    _ = (
        p
        | "Creating Queries" >> beam.Create([query_chunk])
        | 'Generating Embeddings' >> MLTransform(
            write_artifact_location=tempfile.mkdtemp()).with_transform(huggingface_embedder)
        | "Enriching W/ Milvus Hybrid Search" >> Enrichment(milvus_handler)
        | "Formatting and Printing Results" >> FormatAndPrintResults()
    )
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.

Filtered Search (Metadata Filtering)

When a user queries what is beam? using a vector search strategy, the semantic nature of vector embeddings can lead to ambiguity. Without additional context, the system might confuse Google Beam (a 3D communication platform) with Apache Beam (a data processing framework).

Metadata filtering directly solves this by adding contextual constraints. For instance, applying a specific metadata filter (e.g., {"category": "computing"} or {"domain": "communication"}) before the vector search ensures that only documents relevant to the intended concept are considered. This dramatically narrows down results, enhances search precision, and overcomes the limitations of pure content-based search by disambiguating terms like "beam" with specific, structured criteria.

As seen in the search results down below when a user searches for what is beam? without applying filters, the search results include both Apache Beam and Google Beam. Filtered search can come in play here by limiting the relevant search results.

query = "what is beam?"
query_chunk = Chunk(content=Content(text=query))
search_parameters = MilvusSearchParameters(
    collection_name=collection_name,
    search_strategy=VectorSearchParameters(
        limit=10,
        anns_field="embedding",
    ),
    output_fields=["metadata","content"])
collection_load_parameters = MilvusCollectionLoadParameters()
milvus_handler = MilvusSearchEnrichmentHandler(
    connection_parameters=milvus_connection_parameters,
    search_parameters=search_parameters,
    collection_load_parameters=collection_load_parameters)
with beam.Pipeline() as p:
    _ = (
        p
        | "Creating Queries" >> beam.Create([query_chunk])
        | 'Generating Embeddings' >> MLTransform(
            write_artifact_location=tempfile.mkdtemp()).with_transform(huggingface_embedder)
        | "Enriching W/ Milvus Vector Search" >> Enrichment(milvus_handler)
        | "Formatting and Printing Results" >> FormatAndPrintResults())
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.

To precisely target Apache Beam and ensure the retrieval of only relevant documents, we can leverage the power of metadata filtering. By applying a filter that specifies the document's keywords must contain data pipelines, we can instruct the undelrying search engine to exclude any documents related to Google Beam from the result set. This allows the vector search to operate on a pre-filtered, highly relevant subset of the corpus, guaranteeing that the retrieved information pertains exclusively to Apache Beam's domain, thereby resolving the semantic ambiguity with remarkable precision.

query = "what is beam?"
query_chunk = Chunk(content=Content(text=query))
search_parameters = MilvusSearchParameters(
    collection_name=collection_name,
    search_strategy=VectorSearchParameters(
        filter="ARRAY_CONTAINS(metadata['keywords'], 'data pipelines')",
        limit=10,
        anns_field="embedding",
    ),
    output_fields=["metadata","content"])
collection_load_parameters = MilvusCollectionLoadParameters()
milvus_handler = MilvusSearchEnrichmentHandler(
    connection_parameters=milvus_connection_parameters,
    search_parameters=search_parameters,
    collection_load_parameters=collection_load_parameters)
with beam.Pipeline() as p:
    _ = (
        p
        | "Creating Queries" >> beam.Create([query_chunk])
        | 'Generating Embeddings' >> MLTransform(
            write_artifact_location=tempfile.mkdtemp()).with_transform(huggingface_embedder)
        | "Enriching W/ Milvus Vector Search" >> Enrichment(milvus_handler)
        | "Formatting and Printing Results" >> FormatAndPrintResults())
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.

To precisely target Google Beam and ensure the retrieval of only relevant documents, we can leverage the power of metadata filtering. By applying a filter that specifies the document's tags must contain Remote Work, we can instruct the underlying search engine to exclude any documents related to Apache Beam from the result set. This allows the vector search to operate on a pre-filtered, highly relevant subset of the corpus, guaranteeing that the retrieved information pertains exclusively to Google Beam's domain, thereby resolving the semantic ambiguity with remarkable precision.

query = "what is beam?"
query_chunk = Chunk(content=Content(text=query))
search_parameters = MilvusSearchParameters(
    collection_name=collection_name,
    search_strategy=VectorSearchParameters(filter="ARRAY_CONTAINS(metadata['tags'], 'Remote Work')",limit=10,anns_field="embedding"),
    output_fields=["metadata", "content"])
collection_load_parameters = MilvusCollectionLoadParameters()
milvus_handler = MilvusSearchEnrichmentHandler(
    connection_parameters=milvus_connection_parameters,
    search_parameters=search_parameters,
    collection_load_parameters=collection_load_parameters)
with beam.Pipeline() as p:
    _ = (
        p
        | "Creating Queries" >> beam.Create([query_chunk])
        | 'Generating Embeddings' >> MLTransform(
            write_artifact_location=tempfile.mkdtemp()).with_transform(huggingface_embedder)
        | "Enriching W/ Milvus Vector Search" >> Enrichment(milvus_handler)
        | "Formatting and Printing Results" >> FormatAndPrintResults())
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.
WARNING:root:This output type hint will be ignored and not used for type-checking purposes. Typically, output type hints for a PTransform are single (or nested) types wrapped by a PCollection, PDone, or None. Got: Union[Tuple[apache_beam.pvalue.PCollection[~MLTransformOutputT], apache_beam.pvalue.PCollection[apache_beam.pvalue.Row]], apache_beam.pvalue.PCollection[~MLTransformOutputT]] instead.

Cleanup

MilvusEnrichmentTestHelper.stop_db_container(db)
db = None