NEWVectors or files. Pick a path.Start →

    Frequently Asked Questions

    Everything you need to know about multimodal AI, RAG, vector search, and Mixpeek

    57Questions
    4Categories
    43Code Examples

    Filter by Category:

    Filter by Difficulty:

    Definitions

    21 questions

    What is multimodal data?

    Data that combines multiple types of information like text, images, video, and audio in a single system.

    beginner
    Code Example

    Multimodal data refers to information that exists across different modalities or types - such as text, images, video, audio, and structured data. In AI and machine learning contexts, multimodal systems process and understand these different data types together, enabling richer analysis than single-modality approaches. For example, a multimodal AI system can analyze a product by examining both its image and description simultaneously, leading to better search results and recommendations. This approach mirrors how humans naturally process information using multiple senses.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Process multimodal content (text + image + video)
    response = client.embed.multimodal(
        content={
            "text": "Product description text",
            "image_url": "https://example.com/product.jpg",
            "video_url": "https://example.com/demo.mp4"
        }
    )
    multimodal
    data types
    AI
    basics

    What is RAG (Retrieval-Augmented Generation)?

    An AI technique that combines information retrieval with text generation to provide accurate, contextual answers based on your own data.

    intermediate
    Code Example

    RAG (Retrieval-Augmented Generation) is an AI architecture that enhances large language models by combining them with external knowledge retrieval. Instead of relying solely on the model's training data, RAG first retrieves relevant information from a knowledge base (like your documents, videos, or databases), then uses that retrieved context to generate more accurate and up-to-date responses. This approach reduces hallucinations, allows you to use proprietary data without retraining models, and provides source attribution for AI-generated answers. Mixpeek's multimodal RAG extends this to work with images, videos, and audio - not just text.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Step 1: Retrieve relevant context
    search_results = client.search(
        collection_id="your_collection",
        query="How do I process videos?",
        top_k=5
    )
    
    # Step 2: Generate answer using retrieved context
    context = "\n".join([r["content"] for r in search_results])
    answer = f"Based on our documentation: {context}"
    RAG
    LLM
    retrieval
    generation
    AI

    What is vector search and how does it work?

    A search method that finds similar items by comparing their mathematical representations (vectors) rather than matching keywords.

    intermediate
    Code Example

    Vector search, also called semantic search or similarity search, works by converting data (text, images, videos) into numerical vectors that capture their meaning. Items with similar meanings have similar vectors, allowing you to find relevant results even without exact keyword matches. For example, searching for 'puppy' will find results about 'dog' because their vector representations are close together in mathematical space. This is especially powerful for multimodal search where you can search videos using text queries, or find similar images. The process involves: 1) Converting your data to vectors using embedding models, 2) Storing vectors in a specialized database, 3) Converting search queries to vectors, 4) Finding the nearest vectors using algorithms like cosine similarity or HNSW.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Create embeddings for your content
    embedding = client.embed.text(
        text="Find videos about machine learning"
    )
    
    # Search using vector similarity
    results = client.search(
        collection_id="videos",
        vector=embedding.vector,
        top_k=10,
        filters={"modality": "video"}
    )
    vector search
    embeddings
    similarity
    semantic

    What are embeddings in AI?

    Mathematical representations of data (numbers in a list) that capture the meaning or features of content like text, images, or videos.

    beginner
    Code Example

    Embeddings are dense vector representations that encode the semantic meaning or visual features of your data into a fixed-size array of numbers. Each dimension in the embedding captures different aspects of the content - for text, this might be topics or sentiment; for images, it could be shapes, colors, or objects. Modern embedding models create high-dimensional vectors (e.g., 512, 768, or 1536 dimensions) where similar content has similar vectors. This allows mathematical operations like measuring distance or similarity. Mixpeek provides multimodal embeddings that work across text, images, video frames, and audio, enabling you to search for a video using text, or find similar images across your entire media library.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Text embedding
    text_embed = client.embed.text(text="Product description")
    # Returns: [0.123, -0.456, 0.789, ...] (768 dimensions)
    
    # Image embedding
    image_embed = client.embed.image(image_url="https://example.com/product.jpg")
    # Returns similar format, comparable with text embeddings
    
    # Video embedding (per frame or scene)
    video_embed = client.embed.video(video_url="https://example.com/demo.mp4")
    embeddings
    vectors
    AI
    representation learning

    What is hybrid search?

    A search approach that combines keyword-based matching with vector similarity for better accuracy and relevance.

    intermediate
    Code Example

    Hybrid search merges the precision of keyword search with the semantic understanding of vector search. It works by running both searches in parallel: keyword search finds exact or fuzzy matches based on terms, while vector search finds semantically similar content. Results are then combined using a scoring algorithm that weights both approaches. This gives you the best of both worlds - finding exact matches when users know what they're looking for, while also surfacing relevant content that doesn't contain exact keywords. Typical implementations use techniques like Reciprocal Rank Fusion (RRF) or weighted scoring to merge results. Hybrid search is particularly effective for: e-commerce product search, document retrieval, customer support, and any scenario where users might phrase queries in multiple ways. Most production search systems use hybrid approaches rather than pure vector or pure keyword search.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Hybrid search combines keyword + semantic
    results = client.search(
        collection_id="products",
        query="wireless bluetooth headphones with noise cancellation",
        hybrid_search=True,
        hybrid_config={
            "keyword_weight": 0.3,  # 30% keyword matching
            "vector_weight": 0.7,   # 70% semantic similarity
            "rrf_k": 60  # Reciprocal Rank Fusion parameter
        },
        top_k=20
    )
    hybrid search
    search
    semantic
    keyword

    What is zero-shot classification?

    A classification approach that categorizes content into classes without needing training examples, using only class descriptions.

    advanced
    Code Example

    Zero-shot classification allows you to categorize content into classes you haven't explicitly trained a model on. Instead of providing hundreds of labeled examples per class, you simply describe each class in natural language. The model uses its pre-trained understanding to match content to the best fitting description. For example, to classify customer support tickets into 'billing', 'technical', or 'sales' without any training data, you'd compare the ticket embedding against embeddings of descriptions like 'a question about invoices and payments', 'a problem with product functionality', etc. This works because modern embedding models capture semantic relationships during pre-training on massive datasets. Zero-shot is perfect for: rapidly prototyping classification systems, handling rare categories with few examples, adapting to new categories without retraining, and situations where labeling data is expensive. Accuracy is typically lower than supervised approaches but often good enough for many real-world use cases.

    Code Example

    from mixpeek import Mixpeek
    import numpy as np
    from sklearn.metrics.pairwise import cosine_similarity
    
    client = Mixpeek(token="your_token")
    
    # Define classes with descriptions
    classes = {
        "billing": "Questions about invoices, payments, refunds, or pricing",
        "technical": "Problems with product features, bugs, or performance",
        "sales": "Inquiries about purchasing, demos, or product capabilities"
    }
    
    # Embed the customer message
    message = "My payment didn't go through and I was charged twice"
    message_embedding = client.embed.text(text=message)
    
    # Embed class descriptions
    class_embeddings = {
        name: client.embed.text(text=desc)
        for name, desc in classes.items()
    }
    
    # Find most similar class
    similarities = {
        name: cosine_similarity(
            [message_embedding.vector],
            [class_embedding.vector]
        )[0][0]
        for name, class_embedding in class_embeddings.items()
    }
    
    predicted_class = max(similarities, key=similarities.get)
    print(f"Class: {predicted_class}, Confidence: {similarities[predicted_class]:.2%}")
    # Output: Class: billing, Confidence: 0.87
    zero-shot
    classification
    ML
    no training data

    When should I fine-tune an embedding model vs using pre-trained models?

    Fine-tune when you have domain-specific content with unique terminology or when pre-trained models don't capture your specific similarity requirements.

    advanced

    Pre-trained embedding models work well for general content, but fine-tuning becomes valuable when: 1) You have domain-specific jargon - Medical, legal, or technical content with specialized vocabulary. 2) Your similarity requirements differ from general understanding - For example, in fashion e-commerce, 'similar' might prioritize visual style over function, while general models might do the opposite. 3) You have significant labeled data - At least 10,000+ examples of what should be similar. 4) Generic models perform poorly - If your search quality metrics show room for improvement. Fine-tuning requires: paired examples (query-document or similar-dissimilar pairs), computational resources for training, and expertise in ML. The ROI calculation: Will the improvement in metrics (search CTR, conversion) justify the effort? For most use cases, start with pre-trained models, optimize your data pipeline and ranking, then consider fine-tuning only if generic models plateau. Mixpeek's pre-trained multimodal models cover most use cases without fine-tuning.

    Related Resources:

    fine-tuning
    ML
    model training
    advanced

    What is Mixpeek?

    Mixpeek is a multimodal data warehouse that enables semantic search and AI retrieval across text, images, video, and audio content.

    beginner
    Code Example

    Mixpeek is a cloud-native platform for indexing, searching, and retrieving multimodal content at scale. Unlike traditional databases that only handle structured data or keyword search, Mixpeek processes unstructured content (videos, images, audio, documents) and makes it semantically searchable using AI embeddings. The platform provides feature extractors for content understanding (object detection, transcription, scene detection), embedding models for similarity search, and retrieval APIs for building AI applications. Key capabilities include: reverse video search, cross-modal retrieval (search videos with text), content classification, deduplication, and RAG pipelines. Mixpeek handles the infrastructure complexity - distributed processing, vector databases, model serving - so you can focus on building features. It's designed for developers building AI-powered applications like content discovery platforms, e-commerce visual search, video analytics, and intelligent document processing.

    Code Example

    from mixpeek import Mixpeek
    
    # Initialize client
    client = Mixpeek(token="your_api_token")
    
    # Create a collection for your content
    collection = client.collections.create(
        name="my_media_library",
        feature_extractors=["video-embedding", "scene-splitting", "transcription"]
    )
    
    # Index content from S3, URLs, or local files
    client.ingest(
        collection_id=collection.id,
        source="s3://my-bucket/videos/",
        process_async=True
    )
    
    # Search semantically across all content
    results = client.search(
        collection_id=collection.id,
        query="people playing basketball outdoors",
        top_k=10
    )
    mixpeek
    platform
    introduction
    getting started

    How does Mixpeek pricing work?

    Mixpeek charges based on processing volume (GB processed), storage (GB stored), and API requests, with pay-as-you-go and volume-based pricing tiers.

    beginner

    Mixpeek uses consumption-based pricing with three main components: 1) Processing costs - Charged per GB of content processed through feature extractors. Video processing is priced per minute of footage, images per GB, audio per hour. Different extractors have different costs (e.g., transcription costs more than simple embedding). 2) Storage costs - Monthly charge for storing embeddings, metadata, and processed features. Vector storage is optimized and typically 10-20% of your original content size. 3) Search/API requests - Charged per 1000 API calls for search, retrieval, and management operations. High-volume customers get volume discounts. The platform offers: Build tier starting at $25/mo, pay-as-you-go for flexibility, and enterprise plans with committed usage discounts. Cost optimization tips: use scene detection instead of per-frame processing, batch uploads, and cache results. See the pricing page for current rates and use the cost calculator to estimate your usage.

    pricing
    costs
    billing
    platform

    What are feature extractors in Mixpeek?

    Feature extractors are AI models that analyze content to extract specific attributes like objects, faces, text, scenes, or audio transcripts.

    beginner
    Code Example

    Feature extractors are specialized AI models that process raw media to extract structured information. Mixpeek offers dozens of extractors across different modalities: For video - scene detection (splits videos into scenes), object detection (identifies items in frames), face detection (finds and tracks faces), transcription (speech-to-text), OCR (text in video), action recognition, and video embeddings. For images - object detection, face recognition, OCR, image embeddings, NSFW detection, and aesthetic scoring. For audio - transcription, speaker diarization, language detection, and audio embeddings. For text - entity extraction, sentiment analysis, and text embeddings. Each extractor runs independently and produces structured output that's indexed for search. You can combine multiple extractors in a pipeline - for example, run scene detection + transcription + object detection on videos to enable rich search across visual content, spoken words, and detected objects. Extractors are configurable (e.g., set confidence thresholds, languages, detection sensitivity) and update as models improve.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Create collection with multiple feature extractors
    collection = client.collections.create(
        name="video_analysis",
        feature_extractors=[
            "scene-splitting",      # Detect scene changes
            "video-embedding",      # Generate semantic embeddings
            "transcription",        # Speech-to-text
            "object-detection",     # Detect objects in frames
            "face-detection"        # Detect and track faces
        ],
        config={
            "transcription": {"language": "en"},
            "object_detection": {"confidence_threshold": 0.7}
        }
    )
    
    # Features are automatically extracted during ingestion
    client.index(
        collection_id=collection.id,
        video_url="https://example.com/video.mp4"
    )
    feature extractors
    AI models
    processing
    platform

    What security features does Mixpeek provide?

    Mixpeek offers API token authentication, TLS encryption, SOC 2-ready controls, data isolation, and configurable retention policies.

    intermediate

    Mixpeek implements enterprise-grade security across multiple layers: 1) Authentication - API token-based authentication with rotation capabilities. Supports different permission levels (read, write, admin). 2) Encryption - All data encrypted in transit (TLS 1.3) and at rest (AES-256). 3) Compliance - SOC 2-ready, GDPR compliant, and follows data privacy regulations. 4) Data isolation - Collections are logically isolated. Enterprise plans offer dedicated infrastructure. 5) Access control - Granular permissions per collection, support for SSO (SAML) on enterprise plans. 6) Audit logging - Track all API operations, data access, and configuration changes. 7) Data retention - Configure retention policies to auto-delete data after specified periods. 8) Network security - Rate limiting, DDoS protection, and IP whitelisting (enterprise). 9) Content security - Optional content filtering to prevent indexing of malicious or inappropriate content. 10) Vulnerability management - Regular security audits and dependency updates. For regulated industries (healthcare, finance), Mixpeek offers BAA agreements and additional compliance certifications. Contact sales for security documentation and compliance reports.

    Related Resources:

    security
    compliance
    privacy
    platform

    What is CLIP and how does it enable multimodal search?

    CLIP is an AI model that learns joint representations of images and text, enabling cross-modal search like finding images using text queries.

    intermediate
    Code Example

    CLIP (Contrastive Language-Image Pre-training) is a neural network trained by OpenAI on 400 million image-text pairs from the internet. Unlike traditional vision models that learn fixed object categories, CLIP learns to associate images with their natural language descriptions in a shared embedding space. This means images and text that describe similar concepts have similar embeddings, even if they use different words or visual styles. Key innovation: CLIP enables zero-shot visual classification - you can classify images into categories the model has never explicitly seen during training, simply by comparing image embeddings to text embeddings of category descriptions. For search, CLIP allows: searching images with text queries, searching text with image queries, and finding similar images. Limitations: CLIP struggles with fine-grained visual details, counting objects, and understanding spatial relationships. It's trained on web data, so performance varies by domain. Mixpeek's multimodal embeddings are based on CLIP-like architectures, optimized for production search use cases across images, video frames, and text.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # CLIP-style cross-modal search
    # Search images using text
    image_results = client.search(
        collection_id="product_images",
        query="red leather handbag with gold hardware",  # Text query
        modality_filter="image",
        top_k=10
    )
    
    # Search text using an image
    text_results = client.search(
        collection_id="product_descriptions",
        query_image_url="https://example.com/handbag.jpg",  # Image query
        modality_filter="text",
        top_k=10
    )
    
    # Zero-shot image classification
    categories = ["laptop", "phone", "tablet", "watch"]
    image_embedding = client.embed.image(image_url="https://example.com/device.jpg")
    
    category_embeddings = [
        client.embed.text(text=f"a photo of a {cat}")
        for cat in categories
    ]
    
    # Compare and find best match (CLIP-style zero-shot)
    CLIP
    multimodal
    AI
    deep learning

    What are transformers in multimodal AI?

    Transformers are neural network architectures that use attention mechanisms to process sequential data like text, video frames, or audio.

    advanced

    Transformers are the foundation of modern AI, including BERT (text), GPT (language generation), ViT (vision), and CLIP (multimodal). The key innovation is the attention mechanism, which allows the model to weigh the importance of different parts of the input when processing each element. For text: transformers process words in parallel (unlike RNNs) and learn contextual relationships (e.g., 'bank' near 'river' vs 'money'). For images: Vision Transformers (ViT) split images into patches and process them like words, learning spatial relationships. For video: transformers process frames as sequences, capturing temporal dynamics. For multimodal: models like CLIP use dual transformers (one for images, one for text) that learn aligned representations. Benefits: state-of-the-art performance, parallelizable training, transfer learning via pre-training. Challenges: computational cost (quadratic in sequence length), data hungry. Mixpeek's feature extractors use transformer-based models under the hood, optimized for inference efficiency. You don't need to understand transformers to use Mixpeek, but knowing they power the embeddings helps explain why semantic search works so well.

    transformers
    deep learning
    AI
    architecture

    What is AI-powered content moderation?

    Using AI models to automatically detect and filter inappropriate, harmful, or policy-violating content in images, videos, and text.

    intermediate
    Code Example

    AI content moderation uses machine learning to automatically flag or remove content that violates guidelines, such as: violence, NSFW/adult content, hate speech, spam, misinformation, copyright violations, and dangerous content. Traditional rule-based systems can't scale to the volume and variety of user-generated content, so AI provides: 1) Speed - Process millions of items per day. 2) Consistency - Apply rules uniformly without human bias or fatigue. 3) Proactive detection - Catch violations before users report them. 4) Multi-modal analysis - Check images, video, audio, and text together. Implementation approaches: Classification models trained on labeled datasets of violating content, zero-shot detection using embeddings to find similar-to-known-bad content, and hybrid human-AI review where AI flags suspicious content for human moderators. Key challenges: edge cases requiring human judgment, evolving tactics by bad actors, cultural context, and balancing over-filtering vs under-filtering. Best practice: use AI for initial screening (high recall), then human review for final decisions (high precision). Mixpeek provides NSFW detection, violence detection, and custom moderation models as feature extractors.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Set up content moderation pipeline
    collection = client.collections.create(
        name="user_generated_content",
        feature_extractors=[
            "nsfw-detection",        # Detects adult content
            "violence-detection",    # Detects violent imagery
            "hate-speech-detection", # Detects hate speech in text
            "video-embedding"        # For similarity to known violations
        ]
    )
    
    # Index user upload
    result = client.index(
        collection_id=collection.id,
        video_url="https://example.com/user-video.mp4",
        metadata={"user_id": "user123", "upload_time": "2024-01-15"}
    )
    
    # Check moderation flags
    if result.features.get("nsfw_score", 0) > 0.8:
        # High confidence NSFW, auto-reject
        action = "reject"
    elif result.features.get("violence_score", 0) > 0.6:
        # Medium confidence violence, queue for human review
        action = "review"
    else:
        # Passed automated checks
        action = "approve"
    
    print(f"Moderation decision: {action}")
    content moderation
    AI
    safety
    policy

    What is object detection in videos?

    AI technique that identifies and locates specific objects in video frames, providing bounding boxes, labels, and confidence scores.

    intermediate
    Code Example

    Object detection analyzes video frames to identify objects, their locations (bounding boxes), and categories (person, car, dog, etc.). Unlike image classification which says 'this video contains a car', object detection says 'there's a car at coordinates (x1,y1,x2,y2) in frame 150 with 95% confidence'. Modern object detectors use deep learning (YOLO, Faster R-CNN) trained on millions of labeled images. For video, object detection runs per-frame or at intervals, then tracking algorithms link detections across frames to follow objects over time. Key outputs: 1) Bounding boxes - Pixel coordinates defining where each object appears. 2) Class labels - What the object is (from a taxonomy like COCO: 80 classes, or custom classes). 3) Confidence scores - Model's certainty (0-1). 4) Timestamps - When the object appears in the video. Use cases: Video search by objects ('find videos with dogs'), content indexing, surveillance, retail analytics (count customers), autonomous vehicles, and quality control. Mixpeek's object-detection extractor supports multiple taxonomies and custom object training. Combine with embeddings for powerful search: 'videos with people playing soccer at sunset'.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Enable object detection
    collection = client.collections.create(
        name="video_objects",
        feature_extractors=[
            "object-detection",  # Detect objects in frames
            "video-embedding"    # For semantic search
        ],
        config={
            "object_detection": {
                "taxonomy": "coco",  # 80 common objects
                "confidence_threshold": 0.6,
                "frame_interval": 30  # Process every 30th frame
            }
        }
    )
    
    # Index video
    result = client.index(
        collection_id=collection.id,
        video_url="https://example.com/video.mp4"
    )
    
    # Query: Find videos with specific objects
    results = client.search(
        collection_id=collection.id,
        filters={
            "detected_objects": {"$in": ["person", "bicycle", "car"]}
        },
        top_k=20
    )
    
    # Each result includes object detections
    for match in results:
        print(f"Video: {match.video_id}")
        for detection in match.objects:
            print(f"  {detection.label} at {detection.timestamp}s "
                  f"(confidence: {detection.confidence:.2%})")
    object detection
    computer vision
    video analysis

    What is semantic segmentation in video analysis?

    Pixel-level classification that labels every pixel in a frame with its object category, creating detailed masks of objects.

    advanced

    Semantic segmentation goes beyond object detection by classifying every single pixel in an image or video frame into categories (person, road, sky, car, etc.). Instead of just bounding boxes, you get pixel-perfect masks showing exactly where objects are. This enables: precise object boundaries, understanding spatial layout, separating overlapping objects, and measuring exact sizes. For video, semantic segmentation provides: foreground/background separation, scene understanding (30% road, 40% vegetation, 30% buildings), and instance segmentation (distinguishing multiple instances of the same class, like 'person_1', 'person_2'). Applications: Autonomous driving (identify drivable areas), augmented reality (replace backgrounds), video editing (rotoscoping), medical imaging (tumor segmentation), and satellite imagery (land use classification). Computational cost: Semantic segmentation is more expensive than object detection because it processes every pixel. For video, typically run at key frames or intervals. Mixpeek offers semantic segmentation for specialized use cases - contact sales for custom models trained on your specific classes and domains.

    semantic segmentation
    computer vision
    advanced

    What are attention mechanisms in AI models?

    Neural network components that learn to focus on relevant parts of input data, enabling models to weigh importance dynamically.

    advanced

    Attention mechanisms allow neural networks to focus on specific parts of input when making predictions, similar to how humans pay attention to relevant information. In transformers (the backbone of modern AI), attention works by: 1) Query-Key-Value paradigm - Each input element creates a query, key, and value vector. 2) Similarity computation - Compare query against all keys to determine relevance (usually via dot product). 3) Weighted aggregation - Sum values weighted by their relevance scores. This lets models: handle variable-length inputs, capture long-range dependencies, and interpret what the model focuses on. For text: attention identifies which words relate to each other ('it' refers to 'car'). For images: attention highlights relevant regions (when classifying 'bird', attend to feathers not background). For video: temporal attention captures relationships across frames. Multi-head attention uses multiple attention mechanisms in parallel to capture different types of relationships. Self-attention applies attention within a single modality, while cross-attention applies between modalities (e.g., in CLIP, cross-attention between image and text). Why it matters for search: attention-based embeddings capture nuanced semantic relationships, making similarity search more accurate.

    attention
    transformers
    deep learning
    AI

    What file formats and media types does Mixpeek support?

    Mixpeek supports common video (MP4, MOV, AVI, WebM), image (JPEG, PNG, WebP, GIF), audio (MP3, WAV, AAC), and document (PDF, DOCX) formats.

    beginner

    Mixpeek processes a wide range of media formats: Video formats - MP4, MOV, AVI, WebM, MKV, FLV, MPEG. Supports H.264, H.265/HEVC, VP9 codecs. Resolution up to 4K. Frame rates from 1fps to 120fps. Image formats - JPEG, PNG, WebP, GIF, BMP, TIFF, SVG. Supports transparency, animation, and EXIF metadata. Audio formats - MP3, WAV, AAC, OGG, FLAC, M4A. Mono and stereo, various sample rates. Document formats - PDF (text extraction and OCR), DOCX, TXT. Archive formats - ZIP, TAR (extracts and processes contents). Input sources - Direct file upload, S3/GCS/Azure Blob URLs, public HTTP URLs, base64-encoded data. Size limits - Build: 5GB per file. Paid tiers: 5GB per file. Enterprise: custom limits. Processing considerations: Larger files take longer to process, use async ingestion for files >50MB, very high-resolution videos may be downscaled for processing efficiency, and corrupted or DRM-protected files will fail processing. For unsupported formats, consider converting before upload (ffmpeg for video/audio, ImageMagick for images).

    Related Resources:

    formats
    supported files
    media types
    specifications

    What webhooks does Mixpeek support and how do I use them?

    Mixpeek sends webhooks for ingestion completion, processing errors, and collection updates; configure webhook URLs in dashboard or API calls.

    intermediate
    Code Example

    Webhooks enable real-time notifications when async operations complete, avoiding the need for polling. Supported webhook events: 1) ingestion.completed - Fires when file(s) finish processing. Payload includes file IDs, processing time, extracted features. 2) ingestion.failed - Fires when processing fails. Payload includes error details, file info. 3) collection.updated - Fires when collection schema or configuration changes. 4) search.slow_query - Optional webhook for queries taking >5 seconds (helps identify optimization opportunities). Webhook configuration: Set webhook_url parameter in API calls (per-operation), or configure default webhooks in dashboard (global). Webhook payload format: JSON with event type, timestamp, data object, and retry attempt number. Security: Webhooks include HMAC signature in headers for verification (validate using your secret key). Implement idempotency - webhooks may be delivered multiple times. Best practices: Respond with 200 OK quickly (don't block webhook), process payload asynchronously in background job, implement retry logic for webhook processing failures, and log all webhook receipts for debugging.

    Code Example

    from mixpeek import Mixpeek
    from flask import Flask, request, jsonify
    import hmac
    import hashlib
    
    app = Flask(__name__)
    client = Mixpeek(token="your_token")
    
    # Set up ingestion with webhook
    def ingest_with_webhook(video_url, collection_id):
        job = client.index(
            collection_id=collection_id,
            video_url=video_url,
            process_async=True,
            webhook_url="https://myapp.com/webhooks/mixpeek"
        )
        return job.id
    
    # Webhook endpoint
    @app.route('/webhooks/mixpeek', methods=['POST'])
    def handle_mixpeek_webhook():
        # Step 1: Verify signature
        signature = request.headers.get('X-Mixpeek-Signature')
        webhook_secret = "your_webhook_secret"
    
        computed_sig = hmac.new(
            webhook_secret.encode(),
            request.data,
            hashlib.sha256
        ).hexdigest()
    
        if not hmac.compare_digest(signature, computed_sig):
            return jsonify({"error": "Invalid signature"}), 401
    
        # Step 2: Parse payload
        payload = request.json
        event_type = payload["event"]
        data = payload["data"]
    
        # Step 3: Handle event
        if event_type == "ingestion.completed":
            # Process completed ingestion
            print(f"File processed: {data['file_id']}")
            print(f"Features: {data['features']}")
    
            # Trigger downstream actions (e.g., notify user, update database)
            notify_user(data['file_id'], "processing_complete")
    
        elif event_type == "ingestion.failed":
            # Handle failure
            print(f"Processing failed: {data['error']}")
            log_error(data)
    
        # Step 4: Respond quickly (200 OK)
        return jsonify({"status": "received"}), 200
    
    def notify_user(file_id, status):
        # Async notification logic
        pass
    
    if __name__ == '__main__':
        app.run(port=8080)

    Related Resources:

    webhooks
    events
    API
    async

    What is multimodal search?

    A search technique that queries and retrieves results across multiple data types like text, images, video, and audio simultaneously.

    beginner

    Multimodal search is a retrieval approach that allows users to search across different data modalities, text, images, video, audio, and documents, using a single query. Unlike traditional keyword search that only works with text, multimodal search converts all data types into a shared embedding space, enabling cross-modal queries. For example, you can describe a scene in natural language and retrieve matching video clips, or upload an image to find similar products described in text. This is powered by models like CLIP and multimodal transformers that understand relationships between different data types. Mixpeek provides multimodal search out of the box with configurable retrieval pipelines that combine vector similarity, filtering, and ranking across any combination of modalities.

    multimodal search
    cross-modal
    semantic search
    AI search

    What is a feature extractor in machine learning?

    A model or algorithm that transforms raw data into structured numerical representations (features) that capture meaningful patterns for downstream tasks.

    beginner

    A feature extractor in machine learning is a component that takes raw input data, such as images, text, video, or audio, and produces a set of meaningful numerical features that represent the important characteristics of that data. In traditional ML, feature extraction was manual (e.g., counting word frequencies for text, or computing edge histograms for images). In modern deep learning, feature extractors are neural networks trained to automatically learn the most useful representations. For example, a vision transformer extracts visual features like objects, textures, and spatial relationships from images, while a language model extracts semantic features from text. These extracted features (often called embeddings) are then used for tasks like search, classification, clustering, and recommendation. Mixpeek provides configurable feature extractors for every modality, including specialized ones for face identity, scene splitting, transcription, OCR, and multimodal embeddings, that run as part of your data processing pipeline.

    feature extraction
    machine learning
    deep learning
    embeddings
    basics

    How-To Guides

    26 questions

    How do I implement reverse video search?

    Upload a reference video, extract embeddings from frames, then search your video library for similar visual content using vector similarity.

    intermediate
    Code Example

    Implementing reverse video search involves four main steps: First, process your video library by extracting embeddings from video frames using multimodal embedding models. Store these embeddings in a vector database with metadata like timestamps and video IDs. Second, when a user uploads a query video, extract embeddings from its frames using the same model. Third, use vector similarity search (cosine similarity or dot product) to find the most similar frames across your database. Fourth, aggregate results by video ID and rank them by relevance. For production systems, consider scene boundary detection to avoid over-indexing similar consecutive frames, and implement filters for video duration, quality, or metadata. Mixpeek handles the complexity of video processing, embedding generation, and similarity search with a simple API.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Step 1: Index your video library
    collection = client.collections.create(
        name="video_library",
        feature_extractors=["scene-splitting", "video-embedding"]
    )
    
    # Step 2: Add videos to collection
    client.ingest(
        collection_id=collection.id,
        source="s3://my-videos/",
        process_async=True
    )
    
    # Step 3: Search by uploading a query video
    results = client.search(
        collection_id=collection.id,
        query_video_url="https://example.com/query-video.mp4",
        top_k=10
    )
    
    # Results contain similar videos with timestamps
    for result in results:
        print(f"Video: {result.video_id}, Timestamp: {result.timestamp}, Score: {result.score}")
    video search
    reverse image search
    similarity
    how-to

    How do I build a semantic search engine?

    Convert your content to embeddings, store in a vector database, then search by converting queries to embeddings and finding nearest neighbors.

    intermediate
    Code Example

    Building a semantic search engine requires five steps: 1) Choose an embedding model that matches your data type (text, images, video). Mixpeek provides SOTA multimodal models. 2) Generate embeddings for all your existing content. For large datasets, batch process and consider incremental updates. 3) Store embeddings in a vector database optimized for similarity search (Mixpeek provides this). 4) Create a search endpoint that: converts user queries to embeddings using the same model, performs nearest neighbor search, applies any metadata filters, and ranks results. 5) Implement hybrid search combining vector similarity with traditional keyword matching for best results. Monitor query quality and iterate on your embedding model choice and ranking strategies.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Step 1: Create collection with embeddings
    collection = client.collections.create(
        name="product_search",
        feature_extractors=["text-embedding", "image-embedding"]
    )
    
    # Step 2: Index your products
    for product in products:
        client.index(
            collection_id=collection.id,
            content={
                "text": product.description,
                "image_url": product.image,
                "metadata": {"category": product.category, "price": product.price}
            }
        )
    
    # Step 3: Search semantically
    results = client.search(
        collection_id=collection.id,
        query="comfortable running shoes for marathon",
        filters={"price": {"$lt": 200}},
        top_k=20
    )
    semantic search
    search engine
    implementation
    how-to

    How do I automatically classify videos by content?

    Extract visual and audio features from videos, then use classification models or similarity matching against labeled examples to categorize content.

    advanced
    Code Example

    Automatic video classification can be approached in three ways: 1) Zero-shot classification: Use multimodal embeddings to compare videos against text descriptions of categories. This requires no training data. 2) Few-shot classification: Provide a few examples of each category, compute their embeddings, and classify new videos by finding the nearest category. 3) Custom classifier: Train a model on your specific categories using labeled data. For most use cases, start with zero-shot or few-shot approaches using Mixpeek's video embeddings. Extract features at the scene level (not every frame) to balance accuracy and cost. Consider multi-label classification where videos can belong to multiple categories. Implement confidence thresholds to flag uncertain classifications for human review. For specialized domains like medical or security footage, fine-tune models on your specific content types.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Zero-shot video classification
    categories = ["tutorial", "product demo", "customer testimonial", "advertisement"]
    
    # Process video
    video_embedding = client.embed.video(
        video_url="https://example.com/video.mp4",
        scene_detection=True
    )
    
    # Compare against category descriptions
    category_embeddings = [
        client.embed.text(f"A video showing a {cat}")
        for cat in categories
    ]
    
    # Find best matching category
    import numpy as np
    from sklearn.metrics.pairwise import cosine_similarity
    
    similarities = cosine_similarity(
        [video_embedding.vector],
        category_embeddings
    )[0]
    
    predicted_category = categories[np.argmax(similarities)]
    confidence = np.max(similarities)
    
    print(f"Category: {predicted_category} (confidence: {confidence:.2%})") 
    video classification
    automation
    ML
    how-to

    How do I handle multiple languages in search?

    Use multilingual embedding models that understand cross-lingual semantics, allowing searches in one language to find results in another.

    advanced
    Code Example

    Supporting multiple languages in search requires multilingual or cross-lingual embedding models. These models are trained on text from many languages and map semantically similar content to nearby points in the same vector space, regardless of language. This means a query in English can find relevant results in Spanish, French, or any supported language. Implementation steps: 1) Use a multilingual embedding model (like multilingual-e5 or mBERT-based models). Mixpeek provides these. 2) Index your content without language separation - all languages go into the same collection. 3) Optionally detect and tag content language as metadata for filtering. 4) Handle language-specific features like character sets, tokenization, and stemming in your application layer. 5) Test cross-lingual queries to validate quality. For production systems, consider: adding language auto-detection, providing language filters in the UI, and monitoring quality separately per language pair.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Use multilingual embedding model
    collection = client.collections.create(
        name="multilingual_docs",
        feature_extractors=["multilingual-text-embedding"]
    )
    
    # Index content in multiple languages
    client.index(collection_id=collection.id, content={"text": "Hello world", "lang": "en"})
    client.index(collection_id=collection.id, content={"text": "Hola mundo", "lang": "es"})
    client.index(collection_id=collection.id, content={"text": "Bonjour le monde", "lang": "fr"})
    
    # Search in English, finds results in all languages
    results = client.search(
        collection_id=collection.id,
        query="greetings and salutations",  # English query
        top_k=10
    )
    # Returns: Hello world, Hola mundo, Bonjour le monde...

    Related Resources:

    multilingual
    cross-lingual
    internationalization
    how-to

    How do I detect and remove duplicate videos?

    Generate perceptual hashes or embeddings for videos, then use similarity thresholds to identify near-duplicates even if resolution or format differs.

    advanced
    Code Example

    Video deduplication identifies duplicate or near-duplicate videos even when they differ in format, resolution, watermarks, or have minor edits. The process: 1) Extract visual signatures - Use perceptual hashing or embeddings from key frames. Mixpeek's video embeddings work well for this. 2) Define similarity threshold - Exact duplicates will have 99%+ similarity, near-duplicates (different resolutions, crops) might be 85-95%. 3) Cluster similar videos - Use algorithms like connected components or hierarchical clustering to group duplicates. 4) Choose canonical version - Keep the highest quality or most recent version from each cluster. 5) Handle edge cases - Similar content that's legitimately different (like series episodes). Implementation considerations: Process videos in batches, store embeddings for efficient comparison, use approximate nearest neighbor search for large collections, and manually review borderline cases before deletion. This approach also works for detecting copyright violations or finding re-uploads of your content.

    Code Example

    from mixpeek import Mixpeek
    import numpy as np
    from sklearn.metrics.pairwise import cosine_similarity
    
    client = Mixpeek(token="your_token")
    
    # Index video library with embeddings
    collection = client.collections.create(
        name="video_dedup",
        feature_extractors=["scene-splitting", "video-embedding"]
    )
    
    # Get all video embeddings
    videos = client.list(collection_id=collection.id)
    
    # Compare each video against others
    duplicates = []
    threshold = 0.90  # 90% similarity = likely duplicate
    
    for i, video1 in enumerate(videos):
        for j, video2 in enumerate(videos[i+1:], i+1):
            similarity = cosine_similarity(
                [video1.embedding],
                [video2.embedding]
            )[0][0]
    
            if similarity > threshold:
                duplicates.append({
                    "video1": video1.id,
                    "video2": video2.id,
                    "similarity": similarity
                })
    
    print(f"Found {len(duplicates)} potential duplicate pairs")
    deduplication
    video processing
    how-to
    data cleaning

    How do I get started with Mixpeek?

    Sign up for an account, get your API token, install the SDK, create a collection with feature extractors, ingest content, and start searching.

    beginner
    Code Example

    Getting started with Mixpeek takes about 15 minutes: 1) Sign up - Create an account at mixpeek.com. You'll get API credentials and access to the dashboard. 2) Install SDK - Install the Python SDK: `pip install mixpeek`. Also available in JavaScript/TypeScript. 3) Initialize client - Import and authenticate with your API token. 4) Create collection - Define a collection with the feature extractors you need (start with embeddings for search). 5) Ingest content - Upload your media files from S3, URLs, or local storage. Processing happens asynchronously. 6) Search - Use the search API to query your collection semantically. 7) Iterate - Monitor results in the dashboard, adjust extractors and search parameters based on quality. Start small with a test collection of 10-100 items to validate your use case, then scale to production volumes. Check the documentation for tutorials, recipes (implementation patterns), and the API reference. Join the Discord community for support.

    Code Example

    # Step 1: Install SDK
    # pip install mixpeek
    
    # Step 2: Import and authenticate
    from mixpeek import Mixpeek
    client = Mixpeek(token="your_api_token")
    
    # Step 3: Create collection
    collection = client.collections.create(
        name="my_first_collection",
        feature_extractors=["image-embedding", "text-embedding"]
    )
    
    # Step 4: Index some content
    client.index(
        collection_id=collection.id,
        content={
            "image_url": "https://example.com/image.jpg",
            "text": "A beautiful sunset over mountains",
            "metadata": {"category": "landscape"}
        }
    )
    
    # Step 5: Search!
    results = client.search(
        collection_id=collection.id,
        query="mountain scenery at dusk",
        top_k=5
    )
    
    for result in results:
        print(f"Match: {result.metadata}, Score: {result.score}")
    getting started
    tutorial
    quickstart
    how-to

    How do I deploy Mixpeek in production?

    Use environment-specific API tokens, implement retry logic and error handling, set up monitoring, configure rate limits, and follow security best practices.

    advanced
    Code Example

    Production deployment checklist: 1) API keys - Use separate tokens for dev/staging/production. Store tokens in environment variables or secrets managers (AWS Secrets Manager, Vault), never hardcode. 2) Error handling - Implement exponential backoff for retries, handle rate limits (429 errors), catch and log API errors. 3) Async processing - For large ingestion jobs, use async mode and webhooks to handle completion events rather than polling. 4) Monitoring - Track API latency, error rates, processing volume, and search quality metrics. Integrate with your observability stack (Datadog, New Relic). 5) Rate limiting - Configure appropriate rate limits for your workload. Enterprise plans offer higher limits. 6) Caching - Cache search results for popular queries to reduce costs and latency. Invalidate cache when collection updates. 7) Data backup - Export critical metadata and collection configurations. 8) Testing - Implement integration tests that run against a test collection. 9) Security - Use HTTPS only, validate inputs, implement authentication on your application layer. 10) Scaling - Start with a pilot collection, monitor performance, then scale gradually. Use collection-per-tenant for multi-tenant applications.

    Code Example

    import os
    from mixpeek import Mixpeek
    from tenacity import retry, stop_after_attempt, wait_exponential
    import logging
    
    # Production configuration
    client = Mixpeek(
        token=os.environ["MIXPEEK_API_TOKEN"],  # From environment
        timeout=30,  # Request timeout
        max_retries=3
    )
    
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    
    # Retry logic with exponential backoff
    @retry(
        stop=stop_after_attempt(3),
        wait=wait_exponential(multiplier=1, min=4, max=10)
    )
    def search_with_retry(collection_id, query):
        try:
            results = client.search(
                collection_id=collection_id,
                query=query,
                top_k=10
            )
            logger.info(f"Search successful: {len(results)} results")
            return results
        except Exception as e:
            logger.error(f"Search failed: {str(e)}")
            raise
    
    # Async ingestion with webhook callback
    def ingest_async(collection_id, source):
        job = client.ingest(
            collection_id=collection_id,
            source=source,
            process_async=True,
            webhook_url="https://myapp.com/webhooks/mixpeek/complete"
        )
        logger.info(f"Ingestion job started: {job.id}")
        return job.id

    Related Resources:

    production
    deployment
    devops
    best practices
    how-to

    How do I choose the right embedding model for my use case?

    Consider your data modality, domain specificity, performance requirements, and whether you need cross-modal search capabilities.

    intermediate
    Code Example

    Choosing an embedding model involves several factors: 1) Modality - Text-only: use text embedding models (e5, sentence-transformers). Images: use vision models (CLIP, ViT). Video: use video-specific models or frame-level image embeddings. Audio: use audio models or transcription + text embeddings. Multimodal: use CLIP-style models for cross-modal search. 2) Domain - General content: pre-trained models work well. Specialized domains (medical, legal): consider domain-adapted or fine-tuned models. Mixpeek offers both general and domain-specific extractors. 3) Performance - Latency-sensitive: smaller models (384d embeddings). Quality-focused: larger models (768d, 1536d embeddings). Balance: medium-sized models (512d). 4) Language - Multilingual content: use multilingual models (multilingual-e5, mBERT-based). Single language: language-specific models may perform better. 5) Features needed - Similarity search only: standard embeddings. Attributes + search: combine embeddings with feature extractors. Classification: consider specialized classification models or zero-shot approaches. Test multiple models on your data, measure retrieval quality (recall@k, MRR), and balance quality vs cost vs latency.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Example: E-commerce visual search
    # Need: image similarity + cross-modal text-to-image search
    collection_visual = client.collections.create(
        name="products_visual_search",
        feature_extractors=[
            "clip-image-embedding",  # For cross-modal (text→image search)
            "object-detection"       # For attributes (color, category)
        ]
    )
    
    # Example: Document search
    # Need: text-only, multilingual, high quality
    collection_docs = client.collections.create(
        name="documents_multilingual",
        feature_extractors=[
            "multilingual-e5-large"  # Supports 100+ languages, 1024d
        ]
    )
    
    # Example: Video content moderation
    # Need: fast processing, good enough quality
    collection_moderation = client.collections.create(
        name="video_moderation",
        feature_extractors=[
            "clip-video-embedding-small",  # Faster, 512d
            "nsfw-detection",               # Specialized classifier
            "transcription"                 # Speech content
        ]
    )
    
    # Test and compare model quality
    # Run evaluation set through different models, measure recall

    Related Resources:

    model selection
    embeddings
    how-to
    best practices

    How do I implement face recognition search in videos?

    Extract face embeddings from video frames, store them with timestamps, then search by comparing query face embeddings to find matching people.

    advanced
    Code Example

    Face recognition search in videos involves several steps: 1) Face detection - Identify faces in each video frame using face detection models. Mixpeek's face-detection extractor handles this. 2) Face embedding - Generate a unique vector representation for each detected face. These embeddings capture facial features invariant to lighting, angle, and expression. 3) Face tracking - Link faces across consecutive frames to avoid duplicates and get continuous timestamps. 4) Indexing - Store face embeddings with metadata: video ID, timestamp, bounding box coordinates, and optionally identity labels. 5) Search - When searching for a person: provide a reference face image, generate its embedding, search for similar embeddings in your collection, aggregate results by video and person. Applications: find all appearances of a person across your video library, identify unknown individuals, count unique people, and create appearance timelines. Privacy considerations: ensure compliance with privacy laws (GDPR, CCPA, BIPA), get consent for face recognition, implement data retention policies, and provide opt-out mechanisms. For identity labeling, you'll need a separate identity database mapping face embeddings to names.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Set up face recognition pipeline
    collection = client.collections.create(
        name="video_faces",
        feature_extractors=[
            "face-detection",  # Detect faces in frames
            "face-embedding",  # Generate face embeddings
            "face-tracking"    # Track faces across frames
        ]
    )
    
    # Index video library
    client.ingest(
        collection_id=collection.id,
        source="s3://security-footage/",
        process_async=True
    )
    
    # Search for a specific person
    # Provide reference image of the person
    reference_face = client.embed.face(
        image_url="https://example.com/person.jpg"
    )
    
    # Find all appearances of this person
    results = client.search(
        collection_id=collection.id,
        vector=reference_face.vector,
        filters={"has_face": True},
        top_k=100,
        min_score=0.85  # High threshold for face matching
    )
    
    # Group by video
    from collections import defaultdict
    appearances = defaultdict(list)
    for result in results:
        appearances[result.video_id].append({
            "timestamp": result.timestamp,
            "confidence": result.score
        })
    
    print(f"Found person in {len(appearances)} videos")
    face recognition
    video
    biometrics
    how-to

    How do I search within videos and get accurate timestamps?

    Process videos at frame or scene level, store embeddings with timestamps, then search returns matches with precise video positions.

    intermediate
    Code Example

    Timestamp-aware video search allows users to jump directly to relevant moments instead of watching entire videos. Implementation: 1) Temporal segmentation - Decide granularity: frame-level (every frame), interval-based (every N seconds), or scene-based (when content changes). Scene-based is most cost-effective and semantically meaningful. 2) Embedding with time - For each segment, generate an embedding and store the timestamp (start_time, end_time). Also store metadata like frame number, scene number. 3) Search - Query returns segments ranked by relevance, each with timestamp. 4) Presentation - In your UI, display video player cued to the timestamp, show thumbnail preview, and provide timeline navigation. Advanced features: Multi-moment search returns multiple relevant segments from the same video, temporal filtering searches within specific time ranges, and highlight reels automatically compile top segments. Considerations: Balance granularity (more segments = better precision but higher cost), use scene detection to avoid splitting mid-action, and aggregate nearby segments to avoid fragmented results. Mixpeek's scene-splitting extractor handles temporal segmentation automatically.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Set up scene-based video search
    collection = client.collections.create(
        name="timestamped_videos",
        feature_extractors=[
            "scene-splitting",   # Detect scene boundaries
            "video-embedding",   # Embed each scene
            "transcription"      # For spoken content search
        ]
    )
    
    # Index video - automatically split into scenes with timestamps
    client.index(
        collection_id=collection.id,
        video_url="https://example.com/lecture.mp4",
        metadata={"title": "ML Lecture Series Episode 1"}
    )
    
    # Search within videos
    results = client.search(
        collection_id=collection.id,
        query="explanation of gradient descent",
        top_k=5
    )
    
    # Results include precise timestamps
    for result in results:
        print(f"Video: {result.metadata['title']}")
        print(f"  Jump to: {result.start_time}s - {result.end_time}s")
        print(f"  Scene content: {result.transcript_snippet}")
        print(f"  Relevance: {result.score:.2%}")
        print(f"  Direct link: https://example.com/player?v={result.video_id}&t={result.start_time}")
        print()
    
    # Advanced: Multi-moment search (find multiple relevant segments in same video)
    all_moments = client.search(
        collection_id=collection.id,
        query="gradient descent",
        top_k=50,  # Get more results
        group_by="video_id",  # Group by video
        max_per_group=5  # Up to 5 moments per video
    )
    video search
    timestamps
    how-to
    user experience

    How do I evaluate and measure embedding quality?

    Use retrieval metrics like Recall@K, MRR, and NDCG on labeled test sets, and run A/B tests comparing search quality between models.

    advanced
    Code Example

    Evaluating embedding quality requires: 1) Test dataset - Create evaluation sets with query-relevant document pairs. For example, 'red dress' should retrieve actual red dress products. Need at least 100-1000 query-document pairs covering diverse scenarios. 2) Retrieval metrics - Recall@K: What fraction of relevant results appear in top K? MRR (Mean Reciprocal Rank): Where does the first relevant result appear? NDCG (Normalized Discounted Cumulative Gain): Considers relevance scores and ranking position. Precision@K: What fraction of top K are relevant? 3) Embedding space metrics - Cluster quality: Do similar items cluster together? Separation: Are dissimilar items far apart? Dimensionality: Can you reduce dimensions without losing quality? 4) Qualitative evaluation - Manual review of search results, edge case testing, and user feedback. 5) A/B testing - Deploy model variants to user segments, measure click-through rates, conversion rates, and time to find results. Benchmark process: Encode test queries and documents, compute similarity scores, rank results, calculate metrics, compare models. Iterate on: model choice, pre-processing (cleaning, normalization), fine-tuning, and query expansion. Tools: beir benchmarks, custom evaluation scripts, Mixpeek analytics dashboard.

    Code Example

    from mixpeek import Mixpeek
    import numpy as np
    from sklearn.metrics import ndcg_score
    
    client = Mixpeek(token="your_token")
    
    # Step 1: Prepare test set
    test_queries = [
        {"query": "red leather handbag", "relevant_ids": ["prod_123", "prod_456"]},
        {"query": "wireless headphones", "relevant_ids": ["prod_789", "prod_012"]},
        # ... more test cases
    ]
    
    # Step 2: Run searches and collect results
    def evaluate_model(collection_id, test_set):
        recall_at_10 = []
        mrr_scores = []
    
        for test in test_set:
            results = client.search(
                collection_id=collection_id,
                query=test["query"],
                top_k=10
            )
    
            # Calculate Recall@10
            retrieved_ids = [r.id for r in results]
            relevant_retrieved = set(retrieved_ids) & set(test["relevant_ids"])
            recall = len(relevant_retrieved) / len(test["relevant_ids"])
            recall_at_10.append(recall)
    
            # Calculate MRR
            for i, result in enumerate(results, 1):
                if result.id in test["relevant_ids"]:
                    mrr_scores.append(1.0 / i)
                    break
            else:
                mrr_scores.append(0.0)
    
        return {
            "recall@10": np.mean(recall_at_10),
            "mrr": np.mean(mrr_scores)
        }
    
    # Step 3: Compare models
    model_a_metrics = evaluate_model("collection_model_a", test_queries)
    model_b_metrics = evaluate_model("collection_model_b", test_queries)
    
    print(f"Model A - Recall@10: {model_a_metrics['recall@10']:.2%}, MRR: {model_a_metrics['mrr']:.3f}")
    print(f"Model B - Recall@10: {model_b_metrics['recall@10']:.2%}, MRR: {model_b_metrics['mrr']:.3f}")

    Related Resources:

    evaluation
    metrics
    quality
    how-to
    testing

    How do I integrate Mixpeek with my existing database?

    Keep your source of truth in your database, sync metadata to Mixpeek for search, then join results back to your database for full records.

    intermediate
    Code Example

    Mixpeek complements your existing database rather than replacing it. Recommended architecture: 1) Source of truth - Keep your primary data (user profiles, product catalogs, video metadata) in your existing database (Postgres, MongoDB, etc.). 2) Sync to Mixpeek - When creating/updating records, send relevant content to Mixpeek for indexing. Store Mixpeek's item IDs in your database as a reference. 3) Search via Mixpeek - For search queries, call Mixpeek API which returns item IDs and relevance scores. 4) Hydrate results - Use returned IDs to fetch full records from your database. This gives you: Mixpeek's powerful semantic search, your database's transactional guarantees and relational data, and ability to join search results with other data. Implementation patterns: Webhook sync (index new items when created), batch sync (nightly ETL for updates), and event-driven (Kafka/SQS for real-time sync). Consider: storing frequently-accessed metadata in Mixpeek to reduce database lookups, implementing cache for popular queries, and handling sync failures with retry logic.

    Code Example

    from mixpeek import Mixpeek
    import psycopg2
    
    client = Mixpeek(token="your_token")
    db = psycopg2.connect("postgresql://localhost/mydb")
    
    # When creating a product in your database
    def create_product(product_data):
        # Step 1: Insert into your database
        cursor = db.cursor()
        cursor.execute(
            "INSERT INTO products (title, description, image_url, price) VALUES (%s, %s, %s, %s) RETURNING id",
            (product_data["title"], product_data["description"], product_data["image_url"], product_data["price"])
        )
        product_id = cursor.fetchone()[0]
        db.commit()
    
        # Step 2: Index in Mixpeek for search
        mixpeek_result = client.index(
            collection_id="products",
            content={
                "text": f"{product_data['title']} {product_data['description']}",
                "image_url": product_data["image_url"],
                "metadata": {
                    "db_id": product_id,  # Reference back to database
                    "price": product_data["price"]
                }
            }
        )
    
        # Step 3: Store Mixpeek ID in database
        cursor.execute(
            "UPDATE products SET mixpeek_id = %s WHERE id = %s",
            (mixpeek_result.id, product_id)
        )
        db.commit()
    
        return product_id
    
    # When searching
    def search_products(query, max_price=None):
        # Step 1: Search in Mixpeek
        filters = {"price": {"$lt": max_price}} if max_price else {}
        search_results = client.search(
            collection_id="products",
            query=query,
            filters=filters,
            top_k=20
        )
    
        # Step 2: Fetch full records from database
        db_ids = [r.metadata["db_id"] for r in search_results]
        cursor = db.cursor()
        cursor.execute(
            "SELECT * FROM products WHERE id = ANY(%s)",
            (db_ids,)
        )
        products = cursor.fetchall()
    
        # Step 3: Combine search relevance with database data
        return products

    Related Resources:

    integration
    database
    architecture
    how-to

    How do I handle authentication with the Mixpeek API?

    Use API tokens passed in the Authorization header as 'Bearer YOUR_TOKEN', rotate tokens regularly, and use different tokens per environment.

    beginner
    Code Example

    Mixpeek uses API token authentication for security and access control: 1) Getting tokens - Generate tokens in the Mixpeek dashboard under API Keys. Each token has configurable permissions (read, write, admin). 2) Using tokens - Pass token in Authorization header: 'Authorization: Bearer YOUR_TOKEN'. SDKs handle this automatically when you initialize the client. 3) Token management - Create separate tokens for dev/staging/production environments, rotate tokens quarterly or after team member departures, revoke compromised tokens immediately in dashboard, and use read-only tokens for client-side applications when possible. 4) Security best practices - Never commit tokens to git repositories, store in environment variables or secrets managers (AWS Secrets Manager, HashiCorp Vault), use HTTPS only (tokens sent over plain HTTP are vulnerable), implement rate limiting on your application layer, and monitor token usage in dashboard for anomalies. 5) Token permissions - Create tokens with minimal necessary permissions (principle of least privilege). For example, search-only tokens for public search features, write tokens for ingestion services. Enterprise plans support SSO and SAML for centralized authentication.

    Code Example

    import os
    from mixpeek import Mixpeek
    
    # GOOD: Load from environment variable
    client = Mixpeek(token=os.environ["MIXPEEK_API_TOKEN"])
    
    # BAD: Never hardcode tokens!
    # client = Mixpeek(token="sk_live_abc123...")
    
    # For production: Use secrets manager
    import boto3
    
    def get_mixpeek_client():
        # Fetch token from AWS Secrets Manager
        secrets = boto3.client('secretsmanager')
        response = secrets.get_secret_value(SecretId='prod/mixpeek/api_token')
        token = response['SecretString']
    
        return Mixpeek(token=token)
    
    # Manual API requests (without SDK)
    import requests
    
    headers = {
        "Authorization": f"Bearer {os.environ['MIXPEEK_API_TOKEN']}",
        "Content-Type": "application/json"
    }
    
    response = requests.post(
        "https://api.mixpeek.com/v1/retrievers/my_retriever/execute",
        headers=headers,
        json={
            "inputs": {"query": "search query", "top_k": 10}
        }
    )
    
    # Token rotation strategy
    # 1. Create new token in dashboard
    # 2. Deploy new token to all services
    # 3. Monitor for errors
    # 4. Revoke old token after 24h grace period

    Related Resources:

    authentication
    API
    security
    how-to

    How do I batch process large video collections efficiently?

    Use async ingestion with S3/GCS sources, process in batches of 100-500 files, monitor with webhooks, and handle failures with retry logic.

    intermediate
    Code Example

    Batch processing large video libraries requires careful orchestration: 1) Source preparation - Organize videos in cloud storage (S3, GCS, Azure Blob) in a consistent folder structure. Ensure files are accessible (public or pre-signed URLs). 2) Batch ingestion - Use Mixpeek's bulk ingest API pointing to your storage bucket. Process in batches of 100-500 videos to manage load. Set process_async=True for background processing. 3) Progress tracking - Implement webhooks to receive completion notifications. Poll ingestion job status for batches. Log success/failure for each file. 4) Error handling - Some videos will fail (corruption, unsupported codecs). Implement retry logic with exponential backoff. Log failures for manual review. Consider pre-validation (check formats before uploading to Mixpeek). 5) Cost optimization - Use scene detection to reduce per-frame costs. Process lower resolution initially, upgrade on-demand. Schedule large batches during off-peak hours for potential discounts. 6) Parallelization - Process multiple batches in parallel (respecting rate limits). Use distributed task queues (Celery, SQS) to manage workload.

    Code Example

    from mixpeek import Mixpeek
    import time
    from concurrent.futures import ThreadPoolExecutor, as_completed
    
    client = Mixpeek(token="your_token")
    
    # Batch ingest from S3
    def batch_ingest_s3(bucket_path, collection_id, batch_size=100):
        """
        Process videos from S3 in batches
        """
        job = client.ingest(
            collection_id=collection_id,
            source=f"s3://{bucket_path}",
            process_async=True,
            batch_size=batch_size,
            webhook_url="https://myapp.com/webhooks/batch-complete"
        )
    
        print(f"Started batch job: {job.id}")
        return job.id
    
    # Monitor batch progress
    def monitor_batch_job(job_id, timeout=3600):
        """
        Poll job status until complete or timeout
        """
        start_time = time.time()
    
        while time.time() - start_time < timeout:
            status = client.jobs.get(job_id)
    
            print(f"Progress: {status.processed}/{status.total} files")
            print(f"Failed: {status.failed} files")
    
            if status.status == "completed":
                return status
            elif status.status == "failed":
                raise Exception(f"Batch job failed: {status.error}")
    
            time.sleep(30)  # Check every 30 seconds
    
        raise TimeoutError(f"Job {job_id} didn't complete in {timeout}s")
    
    # Process multiple batches in parallel
    def process_multiple_buckets(bucket_paths, collection_id):
        """
        Process multiple S3 paths concurrently
        """
        with ThreadPoolExecutor(max_workers=5) as executor:
            futures = {
                executor.submit(batch_ingest_s3, path, collection_id): path
                for path in bucket_paths
            }
    
            for future in as_completed(futures):
                path = futures[future]
                try:
                    job_id = future.result()
                    print(f"Successfully started job for {path}: {job_id}")
                except Exception as e:
                    print(f"Failed to start job for {path}: {e}")
    
    # Usage
    bucket_paths = [
        "my-videos/2024/january/",
        "my-videos/2024/february/",
        "my-videos/2024/march/"
    ]
    
    process_multiple_buckets(bucket_paths, "my_collection")
    batch processing
    video
    scale
    how-to

    How do I use Mixpeek with AWS S3 for video storage?

    Grant Mixpeek read access to your S3 bucket via IAM role or pre-signed URLs, then ingest using s3:// paths or HTTPS URLs.

    intermediate
    Code Example

    Integrating Mixpeek with S3 for video processing: 1) Access configuration (two options): Option A - IAM Role: Create IAM role with s3:GetObject permission for your bucket. Provide role ARN to Mixpeek in dashboard. Mixpeek assumes role to access files. Option B - Pre-signed URLs: Generate pre-signed URLs (valid 1-24 hours) for each file. Pass URLs to Mixpeek API. No IAM configuration needed. 2) Ingestion methods: Bulk ingest - Point to S3 prefix: client.ingest(source='s3://bucket/videos/'). Individual files - Reference specific objects: client.index(video_url='s3://bucket/video.mp4'). HTTPS URLs - Use S3 HTTPS URLs instead of s3:// paths. 3) Best practices: Organize files in consistent folder structure (/year/month/day/), use lifecycle policies to archive/delete processed files, enable S3 versioning for recovery, set up S3 events to trigger ingestion automatically, use CloudFront CDN for frequently accessed videos, and implement S3 access logging for audit trails. 4) Cost optimization: Use S3 Intelligent-Tiering for variable access patterns, move processed files to Glacier after indexing in Mixpeek, use S3 Select to filter files before processing.

    Code Example

    from mixpeek import Mixpeek
    import boto3
    from botocore.exceptions import ClientError
    
    client = Mixpeek(token="your_token")
    s3 = boto3.client('s3')
    
    # Method 1: Bulk ingest from S3 (using IAM role)
    def ingest_s3_bucket(bucket_name, prefix, collection_id):
        """
        Ingest all videos from S3 bucket/prefix
        Requires: Mixpeek has IAM role with GetObject permission
        """
        job = client.ingest(
            collection_id=collection_id,
            source=f"s3://{bucket_name}/{prefix}",
            process_async=True,
            filters={
                "extensions": [".mp4", ".mov", ".avi"]  # Only process videos
            }
        )
        return job.id
    
    # Method 2: Individual files with pre-signed URLs
    def ingest_with_presigned_url(bucket_name, key, collection_id):
        """
        Generate pre-signed URL and ingest single file
        No IAM configuration needed
        """
        try:
            # Generate pre-signed URL (valid for 1 hour)
            presigned_url = s3.generate_presigned_url(
                'get_object',
                Params={'Bucket': bucket_name, 'Key': key},
                ExpiresIn=3600
            )
    
            # Ingest using pre-signed URL
            result = client.index(
                collection_id=collection_id,
                video_url=presigned_url,
                metadata={
                    "s3_bucket": bucket_name,
                    "s3_key": key
                }
            )
            return result.id
    
        except ClientError as e:
            print(f"Error generating pre-signed URL: {e}")
            return None
    
    # Method 3: S3 Event-driven ingestion
    # Configure S3 bucket notification to trigger Lambda function
    # Lambda function calls Mixpeek to index new uploads
    def lambda_handler(event, context):
        """
        AWS Lambda function triggered by S3 PutObject events
        """
        for record in event['Records']:
            bucket = record['s3']['bucket']['name']
            key = record['s3']['object']['key']
    
            # Only process video files
            if key.endswith(('.mp4', '.mov', '.avi')):
                print(f"New video uploaded: {bucket}/{key}")
    
                # Ingest into Mixpeek
                result = client.index(
                    collection_id="my_collection",
                    video_url=f"s3://{bucket}/{key}",
                    metadata={"upload_time": record['eventTime']}
                )
    
                print(f"Indexed: {result.id}")
    
        return {"statusCode": 200}
    
    # Usage
    ingest_s3_bucket("my-video-bucket", "2024/videos/", "my_collection")

    Related Resources:

    AWS
    S3
    cloud storage
    integration
    how-to

    What's the best way to handle collections with millions of items?

    Partition collections by category or time, use metadata filters aggressively, implement collection-per-tenant for multi-tenant apps, and leverage approximate search.

    advanced
    Code Example

    Managing large-scale collections (1M+ items) requires strategic design: 1) Collection partitioning - Split by category: separate collections for 'electronics', 'clothing', 'books'. Split by time: monthly or yearly collections for time-series data. Benefits: faster search (smaller index), easier data lifecycle management, parallel queries across partitions. 2) Metadata strategy - Index frequently-filtered fields (category, date, status). Use compound filters to narrow results before vector search. Store minimal metadata in Mixpeek (keep full records in primary database). 3) Multi-tenant architecture - Collection-per-tenant: Isolation and security. Shared collection with tenant_id filter: More efficient for many small tenants. Hybrid: Shared for small tenants, dedicated for large enterprises. 4) Search optimizations - Always use filters when possible (reduces search space). Use approximate nearest neighbor (ANN) - accurate within 1-2% of exact, 10-100x faster. Tune ANN parameters (ef_construction, M) for quality vs speed trade-off. 5) Data lifecycle - Archive old data to cold storage. Implement retention policies (auto-delete after N days). Use soft deletes initially, hard delete in batches.

    Code Example

    from mixpeek import Mixpeek
    from datetime import datetime, timedelta
    
    client = Mixpeek(token="your_token")
    
    # Strategy 1: Time-based partitioning
    def get_collection_for_date(date):
        """
        Route queries to monthly collections
        """
        return f"videos_{date.strftime('%Y_%m')}"
    
    def search_across_time_partitions(query, start_date, end_date):
        """
        Search across multiple time-based collections
        """
        results = []
        current_date = start_date
    
        while current_date <= end_date:
            collection_id = get_collection_for_date(current_date)
    
            try:
                monthly_results = client.search(
                    collection_id=collection_id,
                    query=query,
                    top_k=20
                )
                results.extend(monthly_results)
            except Exception as e:
                print(f"No collection for {current_date}: {e}")
    
            # Move to next month
            current_date += timedelta(days=32)
            current_date = current_date.replace(day=1)
    
        # Re-rank combined results
        results.sort(key=lambda x: x.score, reverse=True)
        return results[:20]  # Top 20 overall
    
    # Strategy 2: Category-based partitioning
    CATEGORY_COLLECTIONS = {
        "electronics": "products_electronics",
        "clothing": "products_clothing",
        "books": "products_books",
        "home": "products_home"
    }
    
    def search_by_category(query, category):
        """
        Route to category-specific collection
        """
        collection_id = CATEGORY_COLLECTIONS.get(category)
    
        if not collection_id:
            raise ValueError(f"Unknown category: {category}")
    
        return client.search(
            collection_id=collection_id,
            query=query,
            top_k=20
        )
    
    # Strategy 3: Multi-tenant with shared collection
    def search_tenant_data(query, tenant_id, top_k=10):
        """
        Search within tenant's data in shared collection
        """
        results = client.search(
            collection_id="shared_multi_tenant",
            query=query,
            filters={"tenant_id": tenant_id},  # Critical: isolate tenant data
            top_k=top_k
        )
        return results
    
    # Strategy 4: Data archival
    def archive_old_data(collection_id, days_old=90):
        """
        Move old items to archive collection
        """
        cutoff_date = datetime.now() - timedelta(days=days_old)
    
        # Find old items
        old_items = client.list(
            collection_id=collection_id,
            filters={
                "created_at": {"$lt": cutoff_date.isoformat()}
            }
        )
    
        # Move to archive
        for item in old_items:
            client.index(
                collection_id=f"{collection_id}_archive",
                content=item.content,
                metadata=item.metadata
            )
    
            # Delete from main collection
            client.delete(collection_id=collection_id, item_id=item.id)
    
        print(f"Archived {len(old_items)} items")

    Related Resources:

    scale
    large collections
    partitioning
    how-to

    How do I implement caching for embeddings to reduce costs?

    Cache embeddings for static content, reuse embeddings for duplicate content, and implement embedding versioning to handle model updates.

    advanced
    Code Example

    Embedding caching strategies to reduce reprocessing costs: 1) Content-based caching - Compute content hash (MD5, SHA256) before embedding. Check cache for existing embedding with same hash. Store hash → embedding mapping in fast key-value store (Redis, DynamoDB). Benefits: Avoid re-embedding duplicate content, works across collections. 2) Deterministic embeddings - Same input always produces same embedding (for most models). Cache by canonical form (normalized text, standardized image size). Example: lowercase + trim text before embedding. 3) Cache invalidation - When embedding model updates, flush cache or version keys. Store model version in cache key: {hash}_{model_version}. Gradually migrate to new embeddings. 4) Partial caching - For multimodal content, cache individual modality embeddings. Combine cached text embedding + new image embedding. 5) Implementation patterns - Write-through cache: embed + cache in single operation. Read cache on search, but don't cache search results (they change with new data). 6) Cost analysis - Embedding costs: ~$0.0001 per 1K tokens. Cache storage: ~$0.01 per GB/month. Break-even: ~100 reads per embedding justifies caching.

    Code Example

    from mixpeek import Mixpeek
    import hashlib
    import redis
    import pickle
    from typing import Optional
    
    client = Mixpeek(token="your_token")
    cache = redis.Redis(host='localhost', port=6379, db=1)
    
    MODEL_VERSION = "v1"  # Update when embedding model changes
    
    def compute_content_hash(content: str) -> str:
        """
        Create deterministic hash for content
        """
        # Normalize content (lowercase, trim, etc.)
        normalized = content.lower().strip()
        return hashlib.sha256(normalized.encode()).hexdigest()
    
    def get_cached_embedding(content: str, model: str = "text") -> Optional[list]:
        """
        Check cache for existing embedding
        """
        content_hash = compute_content_hash(content)
        cache_key = f"embedding:{model}:{MODEL_VERSION}:{content_hash}"
    
        cached = cache.get(cache_key)
        if cached:
            print(f"Cache hit for {content_hash[:8]}")
            return pickle.loads(cached)
    
        return None
    
    def embed_with_cache(content: str, model: str = "text") -> list:
        """
        Get embedding with caching
        """
        # Check cache first
        cached_embedding = get_cached_embedding(content, model)
        if cached_embedding:
            return cached_embedding
    
        # Cache miss - compute embedding
        print(f"Cache miss - embedding content")
        if model == "text":
            result = client.embed.text(text=content)
        elif model == "image":
            result = client.embed.image(image_url=content)
        else:
            raise ValueError(f"Unknown model: {model}")
    
        embedding = result.vector
    
        # Store in cache (TTL: 30 days)
        content_hash = compute_content_hash(content)
        cache_key = f"embedding:{model}:{MODEL_VERSION}:{content_hash}"
        cache.setex(
            cache_key,
            30 * 24 * 3600,  # 30 days
            pickle.dumps(embedding)
        )
    
        return embedding
    
    # Advanced: Deduplication with embedding cache
    def index_with_dedup(collection_id: str, items: list):
        """
        Index items, reusing embeddings for duplicates
        """
        embeddings_computed = 0
        embeddings_cached = 0
    
        for item in items:
            # Check if we've seen this content before
            embedding = get_cached_embedding(item["text"])
    
            if embedding:
                embeddings_cached += 1
            else:
                # New content - compute and cache
                embedding = embed_with_cache(item["text"])
                embeddings_computed += 1
    
            # Index with pre-computed embedding
            client.index(
                collection_id=collection_id,
                vector=embedding,  # Pass embedding directly
                metadata=item["metadata"]
            )
    
        print(f"Computed: {embeddings_computed}, Cached: {embeddings_cached}")
        print(f"Cost savings: {embeddings_cached / (embeddings_computed + embeddings_cached):.1%}")
    
    # Cache migration when model updates
    def migrate_embeddings(old_version: str, new_version: str):
        """
        Gradually migrate to new embedding model
        """
        # Get all cached keys for old model
        old_pattern = f"embedding:*:{old_version}:*"
        old_keys = cache.keys(old_pattern)
    
        print(f"Found {len(old_keys)} old embeddings to migrate")
    
        # Option: Delete old embeddings (force recompute)
        # for key in old_keys:
        #     cache.delete(key)
    
        # Option: Keep old embeddings during transition period
        # (both versions coexist, gradually delete old as they expire)

    Related Resources:

    caching
    embeddings
    cost optimization
    how-to

    How do I monitor and analyze search performance?

    Track query latency, result quality metrics (CTR, zero-result rate), and use analytics to identify slow queries and optimization opportunities.

    intermediate
    Code Example

    Comprehensive search performance monitoring: 1) Latency metrics - p50, p95, p99 latency for search queries. Break down by: total latency, vector search time, metadata filtering time, result serialization. Set SLOs (e.g., p95 < 500ms) and alert on violations. 2) Quality metrics - Click-through rate (CTR): % of searches where user clicks a result. Zero-result rate: % of queries with no results. Average rank of clicked results. Session success rate: % of sessions where user finds what they need. 3) Query analysis - Most frequent queries (identify patterns). Slow queries (optimize these first). Failed queries (improve index coverage). Query length distribution (very short queries often have poor results). 4) Cost tracking - Queries per day/month. Average search cost. Top expensive queries (many filters, large top_k). 5) Implementation - Log all queries with: query text, latency, result count, filters used, top_k, user interaction. Send logs to analytics platform (Datadog, Elasticsearch, PostHog). Build dashboards for real-time monitoring. Set up alerts for anomalies.

    Code Example

    from mixpeek import Mixpeek
    import time
    import logging
    from datadog import statsd
    from functools import wraps
    
    client = Mixpeek(token="your_token")
    logger = logging.getLogger(__name__)
    
    def monitor_search(func):
        """
        Decorator to monitor search performance
        """
        @wraps(func)
        def wrapper(*args, **kwargs):
            start_time = time.time()
            query = kwargs.get('query', 'unknown')
    
            try:
                # Execute search
                results = func(*args, **kwargs)
    
                # Measure latency
                latency_ms = (time.time() - start_time) * 1000
    
                # Log metrics
                statsd.histogram('search.latency', latency_ms)
                statsd.increment('search.requests')
                statsd.histogram('search.results_count', len(results))
    
                # Log query details
                logger.info({
                    "event": "search_completed",
                    "query": query,
                    "latency_ms": latency_ms,
                    "result_count": len(results),
                    "top_k": kwargs.get('top_k', 10),
                    "filters": kwargs.get('filters')
                })
    
                # Alert on slow queries
                if latency_ms > 1000:
                    logger.warning(f"Slow query detected: {query} took {latency_ms}ms")
                    statsd.increment('search.slow_queries')
    
                return results
    
            except Exception as e:
                # Track errors
                statsd.increment('search.errors')
                logger.error(f"Search failed: {query}, error: {e}")
                raise
    
        return wrapper
    
    @monitor_search
    def search_products(collection_id, query, filters=None, top_k=10):
        """
        Monitored search function
        """
        return client.search(
            collection_id=collection_id,
            query=query,
            filters=filters,
            top_k=top_k
        )
    
    # Track user interactions for quality metrics
    def track_search_interaction(query, results, clicked_result_id=None):
        """
        Log user interaction with search results
        """
        event = {
            "event": "search_interaction",
            "query": query,
            "result_count": len(results),
            "clicked": clicked_result_id is not None
        }
    
        if clicked_result_id:
            # Find rank of clicked result
            for i, result in enumerate(results):
                if result.id == clicked_result_id:
                    event["clicked_rank"] = i + 1
                    statsd.histogram('search.clicked_rank', i + 1)
                    break
    
            # Calculate CTR
            statsd.increment('search.with_clicks')
        else:
            statsd.increment('search.without_clicks')
    
        logger.info(event)
    
    # Analytics query for slow searches
    def find_slow_queries(log_file, threshold_ms=500):
        """
        Analyze logs to find slow queries
        """
        import json
    
        slow_queries = []
    
        with open(log_file, 'r') as f:
            for line in f:
                try:
                    log = json.loads(line)
                    if log.get('event') == 'search_completed':
                        if log.get('latency_ms', 0) > threshold_ms:
                            slow_queries.append({
                                "query": log['query'],
                                "latency": log['latency_ms'],
                                "filters": log.get('filters')
                            })
                except:
                    continue
    
        # Sort by latency
        slow_queries.sort(key=lambda x: x['latency'], reverse=True)
    
        print(f"Top 10 slowest queries:")
        for q in slow_queries[:10]:
            print(f"  {q['query']}: {q['latency']}ms")
    
        return slow_queries
    
    # Usage
    results = search_products(
        collection_id="products",
        query="wireless headphones",
        filters={"price": {"$lt": 200}},
        top_k=20
    )
    
    # User clicked result #3
    track_search_interaction(
        query="wireless headphones",
        results=results,
        clicked_result_id=results[2].id
    )

    Related Resources:

    monitoring
    analytics
    performance
    how-to

    How do I build a visual product search for e-commerce?

    Index product images with text descriptions using multimodal embeddings, then enable search by image upload or text query with category filters.

    intermediate
    Code Example

    Building visual product search for e-commerce: 1) Data preparation - Collect product catalog: images, titles, descriptions, attributes (color, brand, category), pricing. Ensure high-quality product images (white background, multiple angles). 2) Indexing strategy - Use multimodal embeddings (CLIP-based) to index both images and text. This enables text-to-image search ('red sneakers') and image-to-image search (upload similar). Add metadata fields for filtering: category, price range, brand, availability. 3) Search features - Visual similarity: upload a product image, find similar items. Text-to-visual: search products with natural language. Hybrid filters: combine visual similarity with price, category filters. Attribute search: find 'blue dresses under $100'. 4) UI/UX considerations - Display results in grid with images. Show similarity scores or 'match percentage'. Enable refinement filters in sidebar. Implement infinite scroll for browsing. 5) Advanced features - Color search (find products by dominant color), style transfer (find items that match uploaded outfit), personalization (learn user preferences), and A/B test different ranking strategies.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Step 1: Create product search collection
    collection = client.collections.create(
        name="product_visual_search",
        feature_extractors=[
            "clip-image-embedding",  # For cross-modal search
            "text-embedding",         # For product descriptions
            "object-detection"        # Extract product attributes
        ]
    )
    
    # Step 2: Index product catalog
    def index_product_catalog(products):
        for product in products:
            client.index(
                collection_id=collection.id,
                content={
                    "image_url": product["image_url"],
                    "text": f"{product['title']} {product['description']}",
                    "metadata": {
                        "product_id": product["id"],
                        "category": product["category"],
                        "price": product["price"],
                        "brand": product["brand"],
                        "colors": product["colors"],
                        "in_stock": product["in_stock"]
                    }
                }
            )
    
    # Step 3: Search by text query
    def search_by_text(query, category=None, max_price=None):
        filters = {"in_stock": True}
    
        if category:
            filters["category"] = category
        if max_price:
            filters["price"] = {"$lt": max_price}
    
        return client.search(
            collection_id=collection.id,
            query=query,
            filters=filters,
            top_k=20
        )
    
    # Step 4: Search by image upload (find similar)
    def search_by_image(uploaded_image_url, category=None):
        filters = {"in_stock": True}
    
        if category:
            filters["category"] = category
    
        # Search using image instead of text
        return client.search(
            collection_id=collection.id,
            query_image_url=uploaded_image_url,
            filters=filters,
            top_k=20
        )
    
    # Step 5: Hybrid search (text + filters + visual)
    def advanced_product_search(text_query, color=None, price_range=None):
        filters = {"in_stock": True}
    
        if color:
            filters["colors"] = {"$contains": color}
        if price_range:
            filters["price"] = {
                "$gte": price_range["min"],
                "$lte": price_range["max"]
            }
    
        results = client.search(
            collection_id=collection.id,
            query=text_query,
            filters=filters,
            hybrid_search=True,  # Combine keyword + semantic
            top_k=50
        )
    
        return results
    
    # Usage examples
    # Text search: "summer dresses"
    text_results = search_by_text(
        query="summer dresses",
        category="womens-clothing",
        max_price=100
    )
    
    # Image search: User uploads a photo
    image_results = search_by_image(
        uploaded_image_url="https://user-upload.com/dress.jpg",
        category="womens-clothing"
    )
    
    # Advanced: "red leather handbags under $200"
    hybrid_results = advanced_product_search(
        text_query="leather handbag",
        color="red",
        price_range={"min": 50, "max": 200}
    )
    e-commerce
    visual search
    use case
    how-to

    How do I implement automated content compliance checking?

    Use content moderation extractors (NSFW, violence detection) combined with custom classifiers for industry-specific compliance rules.

    advanced
    Code Example

    Implementing content compliance for regulated industries: 1) Define compliance requirements - Identify regulations: COPPA (children's content), FCC (broadcast standards), industry codes (advertising guidelines). List prohibited content types: violence, adult content, medical misinformation, financial advice, etc. Define review thresholds and escalation paths. 2) Automated detection - NSFW detection: Flag adult or explicit content. Violence detection: Identify graphic violence or weapons. Text analysis: Detect prohibited language, medical claims, or financial advice. Logo/brand detection: Ensure trademark compliance. Age-appropriate classification: Rate content (G, PG, R equivalent). 3) Human-in-loop review - AI flags suspicious content (high recall). Human reviewers make final decisions (high precision). Track reviewer decisions to improve AI models. Implement appeal process for false positives. 4) Audit trail - Log all compliance checks with timestamps. Store decisions and rationale. Enable compliance reporting for regulators. Track trends in violations. 5) Real-time vs batch - Real-time for user-generated content before publishing. Batch review for catalog compliance audits. Periodic re-review as policies evolve.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Set up compliance checking pipeline
    compliance_collection = client.collections.create(
        name="content_compliance",
        feature_extractors=[
            "nsfw-detection",          # Adult content
            "violence-detection",      # Violent imagery
            "hate-speech-detection",   # Hate speech
            "medical-claims-detection",# Health misinformation
            "logo-detection",          # Brand/trademark
            "transcription"            # Audio content analysis
        ]
    )
    
    def check_compliance(content_url, content_type="video"):
        """
        Run compliance checks on content
        """
        # Process content
        result = client.index(
            collection_id=compliance_collection.id,
            video_url=content_url if content_type == "video" else None,
            image_url=content_url if content_type == "image" else None,
            metadata={
                "upload_time": "2024-01-15",
                "uploader_id": "user123"
            }
        )
    
        # Evaluate compliance scores
        compliance_status = {
            "approved": True,
            "flags": [],
            "requires_review": False,
            "violations": []
        }
    
        # NSFW check
        if result.features.get("nsfw_score", 0) > 0.7:
            compliance_status["approved"] = False
            compliance_status["violations"].append("NSFW content detected")
        elif result.features.get("nsfw_score", 0) > 0.4:
            compliance_status["requires_review"] = True
            compliance_status["flags"].append("Potential NSFW content")
    
        # Violence check
        if result.features.get("violence_score", 0) > 0.6:
            compliance_status["approved"] = False
            compliance_status["violations"].append("Violent content detected")
    
        # Hate speech check
        if result.features.get("hate_speech_score", 0) > 0.5:
            compliance_status["approved"] = False
            compliance_status["violations"].append("Hate speech detected")
    
        # Medical claims check (for advertising compliance)
        if result.features.get("medical_claims", []):
            compliance_status["requires_review"] = True
            compliance_status["flags"].append("Medical claims require verification")
    
        # Brand safety check
        detected_logos = result.features.get("logos", [])
        for logo in detected_logos:
            if logo["brand"] in RESTRICTED_BRANDS:
                compliance_status["requires_review"] = True
                compliance_status["flags"].append(f"Restricted brand detected: {logo['brand']}")
    
        # Log compliance check
        log_compliance_check(
            content_id=result.id,
            status=compliance_status,
            features=result.features
        )
    
        return compliance_status
    
    def log_compliance_check(content_id, status, features):
        """
        Create audit trail for compliance
        """
        audit_log = {
            "timestamp": "2024-01-15T10:30:00Z",
            "content_id": content_id,
            "decision": "approved" if status["approved"] else "rejected",
            "automated_flags": status["flags"],
            "violations": status["violations"],
            "feature_scores": {
                "nsfw": features.get("nsfw_score"),
                "violence": features.get("violence_score"),
                "hate_speech": features.get("hate_speech_score")
            }
        }
    
        # Store in compliance database
        # save_to_audit_log(audit_log)
        print(f"Compliance check logged: {audit_log}")
    
    # Batch compliance audit
    def audit_content_library(collection_id):
        """
        Review existing content for compliance
        """
        # Get all items
        items = client.list(collection_id=collection_id)
    
        violations = []
        for item in items:
            status = check_compliance(item.content_url)
    
            if not status["approved"]:
                violations.append({
                    "item_id": item.id,
                    "violations": status["violations"]
                })
    
        print(f"Audit complete: {len(violations)} violations found")
        return violations
    
    RESTRICTED_BRANDS = ["competitor-brand-1", "competitor-brand-2"]
    
    # Usage
    compliance_result = check_compliance(
        content_url="https://example.com/user-video.mp4",
        content_type="video"
    )
    
    if compliance_result["approved"]:
        print("Content approved for publication")
    elif compliance_result["requires_review"]:
        print(f"Content flagged for review: {compliance_result['flags']}")
    else:
        print(f"Content rejected: {compliance_result['violations']}")
    compliance
    content moderation
    regulatory
    use case
    how-to

    How do I detect deepfakes or manipulated videos?

    Combine video embeddings similarity analysis, frame consistency checks, and specialized deepfake detection models to identify synthetic content.

    advanced
    Code Example

    Detecting deepfakes and manipulated videos requires multi-layered approach: 1) Baseline detection - Compare video against known authentic versions (similarity search). Check for temporal inconsistencies (unnatural frame transitions). Analyze audio-visual sync (lip-sync accuracy). Detect artifacts from compression or re-encoding. 2) Specialized deepfake models - Face manipulation detection (facial artifacts, blending boundaries). Voice synthesis detection (spectral analysis of audio). GAN-generated content detection (statistical fingerprints). Use ensemble of multiple detection models for robustness. 3) Metadata analysis - Check EXIF data and file properties. Verify creation timestamps and editing history. Detect signs of re-encoding or tampering. Cross-reference with source attribution. 4) Content provenance - Implement content authentication (C2PA, blockchain). Track chain of custody from capture to distribution. Verify cryptographic signatures. 5) Human review for edge cases - AI flags suspicious content (90%+ accuracy). Expert human reviewers make final determination. Continuous model retraining on new deepfake techniques. Challenge: Deepfake technology evolves rapidly, requiring constant model updates and multi-factor verification.

    Code Example

    from mixpeek import Mixpeek
    import numpy as np
    
    client = Mixpeek(token="your_token")
    
    # Create deepfake detection pipeline
    deepfake_collection = client.collections.create(
        name="deepfake_detection",
        feature_extractors=[
            "video-embedding",           # Overall video similarity
            "face-embedding",            # Facial characteristics
            "deepfake-detection",        # Specialized deepfake model
            "audio-embedding",           # Voice characteristics
            "lip-sync-analysis",         # Audio-visual sync
            "frame-consistency-check"    # Temporal anomalies
        ]
    )
    
    def detect_deepfake(video_url, known_authentic_videos=None):
        """
        Analyze video for signs of manipulation
        """
        # Process suspect video
        result = client.index(
            collection_id=deepfake_collection.id,
            video_url=video_url,
            process_async=False  # Wait for immediate results
        )
    
        deepfake_indicators = {
            "is_deepfake": False,
            "confidence": 0.0,
            "flags": [],
            "authenticity_score": 1.0
        }
    
        # Check deepfake detection model score
        deepfake_score = result.features.get("deepfake_probability", 0)
        if deepfake_score > 0.7:
            deepfake_indicators["is_deepfake"] = True
            deepfake_indicators["confidence"] = deepfake_score
            deepfake_indicators["flags"].append("High deepfake probability")
    
        # Check lip-sync analysis
        lip_sync_score = result.features.get("lip_sync_accuracy", 1.0)
        if lip_sync_score < 0.6:
            deepfake_indicators["flags"].append("Poor audio-visual synchronization")
            deepfake_indicators["authenticity_score"] *= 0.7
    
        # Check frame consistency
        frame_consistency = result.features.get("frame_consistency_score", 1.0)
        if frame_consistency < 0.7:
            deepfake_indicators["flags"].append("Temporal inconsistencies detected")
            deepfake_indicators["authenticity_score"] *= 0.8
    
        # Compare against known authentic videos
        if known_authentic_videos:
            for auth_video in known_authentic_videos:
                # Search for similarity
                similarity_results = client.search(
                    collection_id=deepfake_collection.id,
                    query_video_url=auth_video,
                    top_k=1
                )
    
                if similarity_results and similarity_results[0].score > 0.95:
                    # Very similar to authentic - likely authentic
                    deepfake_indicators["authenticity_score"] = max(
                        deepfake_indicators["authenticity_score"],
                        similarity_results[0].score
                    )
    
        # Check for manipulation artifacts
        artifacts = result.features.get("manipulation_artifacts", [])
        if artifacts:
            deepfake_indicators["flags"].extend([
                f"Artifact detected: {a['type']}" for a in artifacts
            ])
            deepfake_indicators["authenticity_score"] *= 0.6
    
        # Final determination
        if deepfake_indicators["authenticity_score"] < 0.5:
            deepfake_indicators["is_deepfake"] = True
            deepfake_indicators["confidence"] = 1 - deepfake_indicators["authenticity_score"]
    
        return deepfake_indicators
    
    # Batch verification of video library
    def verify_video_library(video_urls, authentic_reference_urls):
        """
        Check multiple videos for authenticity
        """
        results = []
    
        for url in video_urls:
            detection = detect_deepfake(url, authentic_reference_urls)
            results.append({
                "video_url": url,
                "is_authentic": not detection["is_deepfake"],
                "confidence": detection["confidence"],
                "flags": detection["flags"]
            })
    
        # Summary statistics
        deepfakes_detected = sum(1 for r in results if not r["is_authentic"])
        print(f"Analyzed {len(results)} videos")
        print(f"Suspected deepfakes: {deepfakes_detected}")
    
        return results
    
    # Content provenance tracking
    def register_authentic_video(video_url, metadata):
        """
        Register video as authentic with provenance data
        """
        result = client.index(
            collection_id=deepfake_collection.id,
            video_url=video_url,
            metadata={
                "is_authentic": True,
                "source": metadata["source"],
                "capture_device": metadata.get("device"),
                "capture_time": metadata.get("timestamp"),
                "creator": metadata.get("creator"),
                "signature": metadata.get("cryptographic_signature")
            }
        )
    
        print(f"Registered authentic video: {result.id}")
        return result.id
    
    # Usage
    suspect_video = "https://example.com/suspect-video.mp4"
    authentic_refs = [
        "https://example.com/known-authentic-1.mp4",
        "https://example.com/known-authentic-2.mp4"
    ]
    
    detection_result = detect_deepfake(suspect_video, authentic_refs)
    
    if detection_result["is_deepfake"]:
        print(f"⚠️ Deepfake detected (confidence: {detection_result['confidence']:.1%})")
        print(f"Flags: {', '.join(detection_result['flags'])}")
    else:
        print(f"✓ Video appears authentic (score: {detection_result['authenticity_score']:.1%})")
    deepfake
    video verification
    security
    use case
    how-to

    How do I build a personalized video recommendation system?

    Track user viewing history, generate embeddings for watched videos, then recommend similar content using vector similarity and collaborative filtering.

    advanced
    Code Example

    Building video recommendations with Mixpeek: 1) Data collection - Track user interactions: video views, watch time, likes, shares. Store user profiles with preferences and demographics. Collect video metadata: genre, tags, duration, upload date. 2) Content-based filtering - Generate embeddings for all videos (visual content + metadata). When user watches video, find similar videos using vector similarity. Weight recommendations by engagement signals (completed views = higher weight). Filter out already-watched content. 3) Collaborative filtering - Find similar users based on viewing patterns. Recommend videos that similar users enjoyed. Use matrix factorization or graph-based approaches. Combine with content-based for hybrid recommendations. 4) Personalization features - Cold start: For new users, recommend popular/trending videos. Diversity: Mix similar and exploratory recommendations. Recency: Boost recent uploads. Session-based: Recommend based on current viewing session. 5) Ranking and optimization - Score recommendations by predicted engagement. A/B test different algorithms. Monitor click-through rate, watch time, and satisfaction. Implement feedback loops to improve over time.

    Code Example

    from mixpeek import Mixpeek
    from collections import defaultdict
    import numpy as np
    
    client = Mixpeek(token="your_token")
    
    # Index video catalog
    video_collection = client.collections.create(
        name="video_recommendations",
        feature_extractors=[
            "video-embedding",      # Content similarity
            "scene-splitting",      # Temporal features
            "transcription"         # Semantic content
        ]
    )
    
    # User viewing history storage
    user_viewing_history = defaultdict(list)  # user_id -> [video_ids]
    
    def track_video_view(user_id, video_id, watch_time_seconds, total_duration):
        """
        Record user viewing behavior
        """
        completion_rate = watch_time_seconds / total_duration
    
        user_viewing_history[user_id].append({
            "video_id": video_id,
            "watch_time": watch_time_seconds,
            "completion_rate": completion_rate,
            "timestamp": "2024-01-15T10:30:00Z",
            "engagement_score": completion_rate  # Higher if fully watched
        })
    
    def get_content_recommendations(user_id, num_recommendations=10):
        """
        Generate recommendations using content-based filtering
        """
        # Get user's viewing history
        history = user_viewing_history.get(user_id, [])
    
        if not history:
            # Cold start: return trending/popular videos
            return get_trending_videos(num_recommendations)
    
        # Find videos user engaged with most
        high_engagement = [
            v for v in history
            if v["engagement_score"] > 0.7
        ]
    
        # Sort by recency and engagement
        high_engagement.sort(
            key=lambda x: x["engagement_score"],
            reverse=True
        )
    
        # Get embeddings of top watched videos
        seed_videos = high_engagement[:5]
    
        recommendations = []
        for seed in seed_videos:
            # Find similar videos
            similar = client.search(
                collection_id=video_collection.id,
                query=f"video_id:{seed['video_id']}",  # Use video as query
                top_k=20
            )
    
            # Filter out already watched
            watched_ids = set(v["video_id"] for v in history)
            new_videos = [
                s for s in similar
                if s.metadata["video_id"] not in watched_ids
            ]
    
            recommendations.extend(new_videos)
    
        # Deduplicate and rank by similarity score
        seen = set()
        unique_recommendations = []
        for rec in recommendations:
            if rec.id not in seen:
                seen.add(rec.id)
                unique_recommendations.append(rec)
    
        unique_recommendations.sort(key=lambda x: x.score, reverse=True)
    
        return unique_recommendations[:num_recommendations]
    
    def get_collaborative_recommendations(user_id, num_recommendations=10):
        """
        Find similar users and recommend their favorites
        """
        # Find users with similar viewing patterns
        current_user_videos = set(
            v["video_id"] for v in user_viewing_history[user_id]
        )
    
        similar_users = []
        for other_user_id, other_history in user_viewing_history.items():
            if other_user_id == user_id:
                continue
    
            other_videos = set(v["video_id"] for v in other_history)
    
            # Calculate Jaccard similarity
            intersection = len(current_user_videos & other_videos)
            union = len(current_user_videos | other_videos)
            similarity = intersection / union if union > 0 else 0
    
            if similarity > 0.2:  # At least 20% overlap
                similar_users.append({
                    "user_id": other_user_id,
                    "similarity": similarity
                })
    
        # Get videos from similar users
        recommendations = defaultdict(float)
        for similar_user in sorted(similar_users, key=lambda x: x["similarity"], reverse=True)[:10]:
            for video in user_viewing_history[similar_user["user_id"]]:
                if video["video_id"] not in current_user_videos:
                    # Weight by user similarity and engagement
                    score = similar_user["similarity"] * video["engagement_score"]
                    recommendations[video["video_id"]] += score
    
        # Sort by aggregated score
        sorted_recs = sorted(
            recommendations.items(),
            key=lambda x: x[1],
            reverse=True
        )
    
        return [video_id for video_id, score in sorted_recs[:num_recommendations]]
    
    def get_hybrid_recommendations(user_id, num_recommendations=10):
        """
        Combine content-based and collaborative filtering
        """
        # Get both types of recommendations
        content_recs = get_content_recommendations(user_id, num_recommendations * 2)
        collab_recs = get_collaborative_recommendations(user_id, num_recommendations)
    
        # Merge and deduplicate
        # Weighted: 70% content-based, 30% collaborative
        final_recs = []
    
        # Add top content-based recs (70%)
        final_recs.extend(content_recs[:int(num_recommendations * 0.7)])
    
        # Add collaborative recs (30%)
        seen_ids = set(r.metadata["video_id"] for r in final_recs)
        collab_count = 0
        for video_id in collab_recs:
            if video_id not in seen_ids:
                # Fetch video details
                final_recs.append({"video_id": video_id})
                collab_count += 1
                if collab_count >= int(num_recommendations * 0.3):
                    break
    
        return final_recs[:num_recommendations]
    
    def get_trending_videos(num_videos=10):
        """
        Cold start: Get popular videos
        """
        # Query for most viewed videos in last 7 days
        return client.search(
            collection_id=video_collection.id,
            filters={
                "upload_date": {"$gte": "2024-01-08"},
                "view_count": {"$gte": 1000}
            },
            sort_by="view_count",
            top_k=num_videos
        )
    
    # Usage
    user_id = "user_123"
    
    # Track user behavior
    track_video_view(
        user_id=user_id,
        video_id="video_456",
        watch_time_seconds=180,
        total_duration=200
    )
    
    # Get personalized recommendations
    recommendations = get_hybrid_recommendations(user_id, num_recommendations=10)
    
    print(f"Top recommendations for {user_id}:")
    for i, rec in enumerate(recommendations, 1):
        print(f"{i}. Video: {rec.get('video_id', 'N/A')}")
    recommendations
    personalization
    video
    use case
    how-to

    How do I search within video transcripts and get timestamps?

    Enable transcription feature extractor, index transcripts with timestamps, then search transcript text to jump to specific moments.

    intermediate
    Code Example

    Implementing searchable video transcripts: 1) Transcription - Enable speech-to-text feature extractor during indexing. Specify language for better accuracy (supports 100+ languages). Get word-level timestamps for precise seeking. Store speaker diarization if multi-speaker content. 2) Indexing strategy - Index transcript segments with time boundaries (sentence or paragraph level). Store full transcript for context. Include transcript in multimodal search (combine with visual features). 3) Search capabilities - Keyword search in transcripts (traditional full-text search). Semantic search for concept matching ('artificial intelligence' matches 'machine learning discussion'). Phrase search with quotes for exact matches. Time-range filtering (search within specific video segments). 4) UI/UX - Display search results with video thumbnails at timestamp. Highlight matching text in transcript. Click transcript to jump to video timestamp. Show context before/after match. 5) Advanced features - Multi-video transcript search, auto-generated chapter markers from transcript topics, searchable captions for accessibility, and translation to enable multilingual search.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Create collection with transcription
    transcript_collection = client.collections.create(
        name="searchable_video_transcripts",
        feature_extractors=[
            "transcription",        # Speech-to-text with timestamps
            "video-embedding",      # Visual content
            "scene-splitting"       # Scene boundaries
        ],
        config={
            "transcription": {
                "language": "en",                    # Specify language
                "word_timestamps": True,             # Get word-level timestamps
                "speaker_diarization": True,         # Identify different speakers
                "punctuation": True,                 # Add punctuation
                "paragraph_segmentation": True       # Break into paragraphs
            }
        }
    )
    
    # Index video with transcription
    def index_video_with_transcript(video_url, metadata):
        result = client.index(
            collection_id=transcript_collection.id,
            video_url=video_url,
            metadata=metadata,
            process_async=False  # Wait for transcription
        )
    
        # Transcript is automatically generated and indexed
        transcript = result.features.get("transcript", {})
    
        print(f"Indexed video: {result.id}")
        print(f"Transcript length: {len(transcript.get('text', ''))} characters")
        print(f"Duration: {transcript.get('duration', 0)} seconds")
    
        return result
    
    # Search within transcripts
    def search_transcripts(query, collection_id=None):
        """
        Search for keywords or concepts in video transcripts
        """
        results = client.search(
            collection_id=collection_id or transcript_collection.id,
            query=query,
            search_fields=["transcript"],  # Only search transcript text
            top_k=20
        )
    
        # Process results
        matches = []
        for result in results:
            transcript = result.features.get("transcript", {})
    
            # Find matching segments with timestamps
            for segment in transcript.get("segments", []):
                if query.lower() in segment["text"].lower():
                    matches.append({
                        "video_id": result.metadata.get("video_id"),
                        "timestamp": segment["start"],
                        "end_time": segment["end"],
                        "text": segment["text"],
                        "speaker": segment.get("speaker"),
                        "relevance_score": result.score
                    })
    
        return matches
    
    # Get full transcript with timestamps
    def get_video_transcript(video_id):
        """
        Retrieve complete transcript for a video
        """
        # Fetch video item
        video = client.get(
            collection_id=transcript_collection.id,
            item_id=video_id
        )
    
        transcript = video.features.get("transcript", {})
    
        formatted_transcript = []
        for segment in transcript.get("segments", []):
            formatted_transcript.append({
                "timestamp": format_timestamp(segment["start"]),
                "text": segment["text"],
                "speaker": segment.get("speaker", "Unknown")
            })
    
        return formatted_transcript
    
    def format_timestamp(seconds):
        """
        Convert seconds to MM:SS format
        """
        minutes = int(seconds // 60)
        secs = int(seconds % 60)
        return f"{minutes:02d}:{secs:02d}"
    
    # Semantic search in transcripts
    def search_by_topic(topic, collection_id=None):
        """
        Find videos discussing a topic (semantic, not keyword match)
        """
        results = client.search(
            collection_id=collection_id or transcript_collection.id,
            query=f"discussion about {topic}",
            search_fields=["transcript"],
            hybrid_search=True,  # Combine semantic + keyword
            top_k=10
        )
    
        return [
            {
                "video_id": r.metadata.get("video_id"),
                "title": r.metadata.get("title"),
                "relevance": r.score,
                "transcript_preview": r.features.get("transcript", {}).get("text", "")[:200] + "..."
            }
            for r in results
        ]
    
    # Multi-video transcript search
    def search_across_library(query):
        """
        Search transcripts across entire video library
        """
        matches = search_transcripts(query, transcript_collection.id)
    
        # Group by video
        by_video = {}
        for match in matches:
            video_id = match["video_id"]
            if video_id not in by_video:
                by_video[video_id] = []
            by_video[video_id].append(match)
    
        # Format results
        results = []
        for video_id, video_matches in by_video.items():
            results.append({
                "video_id": video_id,
                "match_count": len(video_matches),
                "timestamps": [m["timestamp"] for m in video_matches],
                "snippets": [m["text"] for m in video_matches]
            })
    
        # Sort by match count
        results.sort(key=lambda x: x["match_count"], reverse=True)
    
        return results
    
    # Usage
    # Index a video
    video_result = index_video_with_transcript(
        video_url="https://example.com/lecture.mp4",
        metadata={
            "video_id": "lecture_001",
            "title": "Introduction to Machine Learning",
            "course": "CS101"
        }
    )
    
    # Search for specific keyword
    keyword_matches = search_transcripts("gradient descent")
    
    print(f"Found {len(keyword_matches)} mentions of 'gradient descent':")
    for match in keyword_matches[:5]:
        print(f"  At {format_timestamp(match['timestamp'])}: {match['text']}")
    
    # Semantic topic search
    topic_results = search_by_topic("neural networks and deep learning")
    
    print(f"\nVideos discussing neural networks:")
    for result in topic_results[:3]:
        print(f"  {result['title']} (relevance: {result['relevance']:.2%})")
    
    # Get full transcript
    full_transcript = get_video_transcript("lecture_001")
    
    print(f"\nFull transcript (first 3 segments):")
    for segment in full_transcript[:3]:
        print(f"[{segment['timestamp']}] {segment['speaker']}: {segment['text']}")
    transcription
    video search
    accessibility
    use case
    how-to

    How do I implement image similarity for e-commerce inventory management?

    Index product images with embeddings, use similarity thresholds to detect duplicates, and cluster similar products for better organization.

    intermediate
    Code Example

    Using image similarity for e-commerce operations: 1) Duplicate detection - Index all product images with visual embeddings. Find near-duplicates (>95% similarity) across catalog. Useful for: detecting duplicate listings, identifying supplier overlap, quality control (same product, different photos). Flag for human review before auto-deletion. 2) Visual clustering - Group visually similar products (80-90% similarity). Organize by: style (modern, vintage, minimalist), color schemes, product type variations. Improve browse experience with 'Shop the Look' features. 3) Quality control - Compare product photos to reference images. Detect: poor lighting or angles, wrong backgrounds, image manipulation, watermarks or logos. Ensure consistent image quality across catalog. 4) Smart categorization - Auto-categorize products based on visual similarity to category exemplars. Suggest tags based on visual features. Identify miscategorized items. 5) Inventory optimization - Find substitutable products (similar appearance, different SKUs). Recommend bundles of complementary items. Identify gaps in product line (clusters with few items).

    Code Example

    from mixpeek import Mixpeek
    from collections import defaultdict
    import numpy as np
    
    client = Mixpeek(token="your_token")
    
    # Create image similarity collection
    product_images = client.collections.create(
        name="product_image_similarity",
        feature_extractors=[
            "image-embedding",      # Visual similarity
            "object-detection",     # Product attributes
            "color-extraction",     # Dominant colors
            "image-quality-check"   # Quality metrics
        ]
    )
    
    # Index product catalog
    def index_product_images(products):
        for product in products:
            client.index(
                collection_id=product_images.id,
                content={
                    "image_url": product["image_url"],
                    "metadata": {
                        "sku": product["sku"],
                        "category": product["category"],
                        "price": product["price"],
                        "supplier_id": product.get("supplier_id")
                    }
                }
            )
    
    # Find duplicate product images
    def find_duplicate_images(similarity_threshold=0.95):
        """
        Detect near-duplicate product images
        """
        all_products = client.list(collection_id=product_images.id)
    
        duplicates = []
        checked = set()
    
        for product in all_products:
            if product.id in checked:
                continue
    
            # Search for visually similar images
            similar = client.search(
                collection_id=product_images.id,
                query_image_url=product.content["image_url"],
                top_k=10
            )
    
            # Find near-duplicates
            for match in similar:
                if match.id == product.id:
                    continue  # Skip self
    
                if match.score >= similarity_threshold:
                    duplicates.append({
                        "product_1": product.metadata["sku"],
                        "product_2": match.metadata["sku"],
                        "similarity": match.score,
                        "action": "review" if match.score < 0.99 else "likely_duplicate"
                    })
                    checked.add(match.id)
    
        print(f"Found {len(duplicates)} potential duplicates")
        return duplicates
    
    # Cluster similar products
    def cluster_similar_products(category, num_clusters=10):
        """
        Group products into visual style clusters
        """
        # Get all products in category
        category_products = client.search(
            collection_id=product_images.id,
            filters={"category": category},
            top_k=1000
        )
    
        # Extract embeddings
        embeddings = [p.embedding for p in category_products]
    
        # Cluster using k-means (simplified)
        from sklearn.cluster import KMeans
    
        kmeans = KMeans(n_clusters=num_clusters, random_state=42)
        cluster_labels = kmeans.fit_predict(embeddings)
    
        # Group products by cluster
        clusters = defaultdict(list)
        for product, label in zip(category_products, cluster_labels):
            clusters[label].append({
                "sku": product.metadata["sku"],
                "image_url": product.content["image_url"],
                "price": product.metadata["price"]
            })
    
        # Analyze clusters
        for cluster_id, products in clusters.items():
            print(f"Cluster {cluster_id}: {len(products)} products")
            # Get representative (centroid)
            # ...
    
        return clusters
    
    # Quality control check
    def check_image_quality(image_url):
        """
        Verify product image meets quality standards
        """
        result = client.index(
            collection_id=product_images.id,
            content={"image_url": image_url},
            process_async=False
        )
    
        quality_issues = []
    
        # Check quality metrics
        quality_score = result.features.get("quality_score", 1.0)
        if quality_score < 0.7:
            quality_issues.append("Low image quality")
    
        # Check resolution
        resolution = result.features.get("resolution", {})
        if resolution.get("width", 0) < 800 or resolution.get("height", 0) < 800:
            quality_issues.append("Resolution too low (< 800px)")
    
        # Check background
        background = result.features.get("background_type", "")
        if background != "white" and background != "transparent":
            quality_issues.append(f"Non-standard background: {background}")
    
        # Check for watermarks
        if result.features.get("has_watermark", False):
            quality_issues.append("Watermark detected")
    
        return {
            "passes": len(quality_issues) == 0,
            "issues": quality_issues,
            "quality_score": quality_score
        }
    
    # Find visually similar alternatives
    def find_similar_products(sku, max_price_difference=50):
        """
        Find products that look similar for substitution/upsell
        """
        # Get product
        product = client.search(
            collection_id=product_images.id,
            filters={"sku": sku},
            top_k=1
        )[0]
    
        # Find similar visually
        similar = client.search(
            collection_id=product_images.id,
            query_image_url=product.content["image_url"],
            filters={
                "category": product.metadata["category"],
                "price": {
                    "$gte": product.metadata["price"] - max_price_difference,
                    "$lte": product.metadata["price"] + max_price_difference
                }
            },
            top_k=10
        )
    
        alternatives = []
        for match in similar:
            if match.metadata["sku"] == sku:
                continue  # Skip self
    
            alternatives.append({
                "sku": match.metadata["sku"],
                "similarity": match.score,
                "price": match.metadata["price"],
                "price_diff": match.metadata["price"] - product.metadata["price"]
            })
    
        return alternatives
    
    # Usage
    # Find duplicates
    duplicates = find_duplicate_images(similarity_threshold=0.95)
    
    print("Duplicate product images:")
    for dup in duplicates[:5]:
        print(f"  {dup['product_1']} ≈ {dup['product_2']} ({dup['similarity']:.1%} similar)")
    
    # Cluster products by visual style
    clusters = cluster_similar_products(category="dresses", num_clusters=5)
    
    print(f"\nFound {len(clusters)} visual style clusters")
    
    # Quality check
    quality_result = check_image_quality("https://example.com/product-image.jpg")
    
    if not quality_result["passes"]:
        print(f"\nQuality issues: {', '.join(quality_result['issues'])}")
    
    # Find alternatives
    alternatives = find_similar_products(sku="SKU-12345", max_price_difference=30)
    
    print(f"\nSimilar products for upsell:")
    for alt in alternatives[:3]:
        price_diff = f"+{alt['price_diff']:.2f}" if alt['price_diff'] >= 0 else f"{alt['price_diff']:.2f}"
        print(f"  {alt['sku']}: {alt['similarity']:.1%} similar, \${price_diff}")
    e-commerce
    image similarity
    inventory
    use case
    how-to

    How do I build a video search engine?

    Extract features from video frames and audio, store embeddings in a vector database, then query using text or visual similarity.

    intermediate
    Code Example

    Building a video search engine requires three core steps: ingestion, extraction, and retrieval. During ingestion, videos are uploaded and split into meaningful segments using scene boundary detection. During extraction, AI models process each segment to generate embeddings from visual frames (using models like CLIP), transcribed audio (using Whisper), and detected objects or faces. These embeddings and metadata are stored in a vector database. For retrieval, user queries (text, image, or video clip) are converted to the same embedding space and matched against stored vectors using approximate nearest neighbor search. Production systems also need temporal indexing for frame-level results, deduplication to avoid redundant results, and ranking pipelines that combine multiple signals. Mixpeek handles all of this through configurable collections and retrieval pipelines.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Step 1: Create a collection with video extractors
    collection = client.collections.create(
        name="video_search_engine",
        feature_extractors=[
            "scene-splitting",
            "video-embedding",
            "transcription"
        ]
    )
    
    # Step 2: Ingest videos from your storage
    client.ingest(
        collection_id=collection.id,
        source="s3://my-video-library/",
        process_async=True
    )
    
    # Step 3: Search with natural language
    results = client.search(
        collection_id=collection.id,
        query="person giving a presentation about AI",
        top_k=10
    )
    video search
    search engine
    video AI
    how-to

    How do I implement face recognition in my app?

    Use a face detection model to find faces, generate identity embeddings with a recognition model, then match against a database of known faces.

    intermediate
    Code Example

    Implementing face recognition involves three stages: detection, embedding, and matching. First, a face detection model (like SCRFD or MTCNN) locates faces in images or video frames and outputs bounding box coordinates. Second, each detected face is cropped and passed through a face recognition model (like ArcFace) that produces a 512-dimensional embedding vector unique to that person's identity. Third, these embeddings are stored in a vector database and compared against new faces using cosine similarity, embeddings from the same person will be very close in vector space. For production systems, you need to handle multiple faces per image, varying angles and lighting, and set an appropriate similarity threshold to balance false positives and negatives. Mixpeek's face identity extractor handles detection, alignment, and embedding generation, with built-in deduplication for video frames where the same person appears across multiple frames.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # Create collection with face identity extraction
    collection = client.collections.create(
        name="face_identity_search",
        feature_extractors=["face-identity"]
    )
    
    # Ingest images/videos - faces are automatically detected and embedded
    client.ingest(
        collection_id=collection.id,
        source="s3://my-photos/",
        process_async=True
    )
    
    # Search by uploading a photo of a face
    results = client.search(
        collection_id=collection.id,
        query_image_url="https://example.com/query-face.jpg",
        top_k=10,
        filters={"type": "face"}
    )
    face recognition
    face search
    biometrics
    computer vision
    how-to

    Comparisons

    6 questions

    When should I use vector search vs keyword search?

    Use vector search for semantic understanding and fuzzy matching; use keyword search for exact matches and structured data. Combine both in hybrid search for best results.

    intermediate

    Vector search excels at understanding intent and finding semantically similar content, even without exact keyword matches. It's ideal for natural language queries, discovering related content, and cross-lingual search. Keyword search is faster, more predictable, and better for exact matches, Boolean logic, and structured queries. Use vector search when: users phrase questions naturally, you need to find conceptually similar items, or you're searching across different media types. Use keyword search when: users know exact terms, you need boolean operators (AND, OR, NOT), or you're filtering structured metadata. The best approach is hybrid search, combining both: use keywords for initial filtering and vectors for semantic ranking. This balances precision (keyword) with recall (vector). For example, search for 'laptop' (keyword) + 'portable work computer under $1000' (vector semantic matching).

    comparison
    search
    vector
    keyword
    hybrid

    What's the difference between a recipe and a tutorial?

    Recipes are implementation patterns and code snippets, while tutorials are step-by-step guides with detailed explanations.

    beginner

    Mixpeek offers two types of guidance: Recipes are reusable implementation patterns that provide quick-start code snippets and API patterns. They specify which feature extractors and retrieval stages to use for common use cases like 'video deduplication' or 'multimodal RAG'. Think of them as architectural blueprints with ready-to-use code. Tutorials are hands-on, step-by-step coding guides that teach you how to build specific features from scratch, with complete code examples and detailed explanations. They're ideal for learning and understanding the underlying concepts. Choose recipes when you need a quick implementation pattern or code snippet, and tutorials when you're learning or need detailed explanations of how things work.

    Related Resources:

    comparison
    getting started
    documentation

    What's the difference between embeddings and feature extraction?

    Feature extraction pulls out specific attributes (objects, faces, text); embeddings create holistic vector representations of content for similarity search.

    intermediate

    Feature extraction identifies and extracts specific, interpretable attributes from content - like detecting faces in images, transcribing speech in audio, or recognizing objects in videos. These features are usually human-understandable (e.g., 'person wearing red shirt', 'face with smile'). Embeddings, on the other hand, convert entire pieces of content into dense numerical vectors that capture overall semantic meaning in a high-dimensional space. While individual dimensions in embeddings aren't directly interpretable, the vectors enable powerful similarity comparisons. In practice, you often use both: extract features for filtering and metadata enrichment, then create embeddings for semantic search and recommendations. For example, extract 'product category' as a feature for filtering, but use embeddings to find visually similar products. Mixpeek provides both capabilities - feature extractors for attributes and embedding models for similarity.

    comparison
    embeddings
    features
    ML

    What's the difference between Mixpeek and Pinecone/Weaviate?

    Mixpeek is a complete multimodal processing and search platform, while Pinecone/Weaviate are vector databases that require you to generate embeddings separately.

    intermediate

    The key difference is scope: Pinecone and Weaviate are vector databases - they store and search embeddings, but you must generate those embeddings yourself using separate models. Mixpeek is an end-to-end platform that handles: content ingestion, feature extraction (embeddings + structured features), vector storage, and search APIs - all integrated. Comparison breakdown: Data processing - Mixpeek processes raw media (videos, images, audio) automatically. Pinecone/Weaviate require you to process content and generate embeddings before insertion. Feature extraction - Mixpeek provides 50+ extractors (transcription, object detection, etc.). Vector DBs have none. Multimodal - Mixpeek natively handles cross-modal search (search videos with text). Vector DBs store vectors but don't understand modalities. Infrastructure - Mixpeek manages distributed processing, model serving, and scaling. Vector DBs only handle vector search. Use Mixpeek when you need turnkey multimodal search. Use Pinecone/Weaviate when you want full control over embedding generation and only need vector storage/search. You can also use Mixpeek's feature extractors and bring your own vector database.

    Related Resources:

    comparison
    alternatives
    vector database
    platform

    When should I use async vs sync processing?

    Use async for large files, batch jobs, and background processing; use sync for small files, real-time needs, and when you need immediate results.

    intermediate
    Code Example

    Choosing between async and sync processing: Async processing (process_async=True): When to use - Large files (>10MB), batch ingestion (>10 files), background jobs (user doesn't wait), video processing (always takes time). Benefits - Non-blocking (returns immediately), parallel processing (faster for many files), handles long-running jobs (hours), retry logic for failures. Workflow - Submit job, receive job_id immediately, poll job status or use webhook, retrieve results when complete. Sync processing (process_async=False): When to use - Small files (<1MB), single files, real-time requirements (user waits for result), testing and development. Benefits - Simpler code (no polling), immediate results, easier error handling. Limitations - Blocks until complete (can timeout for large files), slower for batch operations, no automatic retry. Best practices: Default to async for production workloads, use sync only for small files or prototyping, implement webhooks for async jobs (don't poll), set appropriate timeouts for sync calls. Hybrid approach: Use async for ingestion, sync for search (search is fast, always synchronous).

    Code Example

    from mixpeek import Mixpeek
    import time
    
    client = Mixpeek(token="your_token")
    
    # Sync processing: Wait for result
    def sync_example(video_url, collection_id):
        """
        Use for small files or development
        """
        print("Starting sync processing...")
        start = time.time()
    
        try:
            result = client.index(
                collection_id=collection_id,
                video_url=video_url,
                process_async=False,  # Blocks until complete
                timeout=60  # Max wait time in seconds
            )
    
            print(f"Completed in {time.time() - start}s")
            print(f"Features extracted: {result.features}")
            return result
    
        except TimeoutError:
            print("Processing took too long, timed out")
            # Fallback: Retry with async
            return async_example(video_url, collection_id)
    
    # Async processing: Non-blocking
    def async_example(video_url, collection_id):
        """
        Use for large files or batch processing
        """
        print("Starting async processing...")
    
        # Submit job (returns immediately)
        job = client.index(
            collection_id=collection_id,
            video_url=video_url,
            process_async=True,
            webhook_url="https://myapp.com/webhook/complete"  # Get notified
        )
    
        print(f"Job submitted: {job.id}")
    
        # Continue with other work...
        # Results will come via webhook
    
        return job.id
    
    # Polling async job status (if not using webhooks)
    def wait_for_async_job(job_id, timeout=600):
        """
        Poll job until complete
        """
        start = time.time()
        poll_interval = 5  # Start with 5s
    
        while time.time() - start < timeout:
            status = client.jobs.get(job_id)
    
            if status.status == "completed":
                return status.result
    
            elif status.status == "failed":
                raise Exception(f"Job failed: {status.error}")
    
            # Exponential backoff
            print(f"Status: {status.status}, waiting {poll_interval}s...")
            time.sleep(poll_interval)
            poll_interval = min(poll_interval * 1.5, 30)  # Max 30s
    
        raise TimeoutError(f"Job {job_id} didn't complete in {timeout}s")
    
    # Decision tree
    def smart_index(file_url, collection_id, file_size_mb=None):
        """
        Automatically choose async vs sync based on file size
        """
        # Small file or unknown size: try sync
        if file_size_mb is None or file_size_mb < 10:
            try:
                return sync_example(file_url, collection_id)
            except TimeoutError:
                print("Sync timed out, falling back to async")
                return async_example(file_url, collection_id)
    
        # Large file: always async
        else:
            return async_example(file_url, collection_id)
    
    # Batch processing: Always async
    def batch_index(file_urls, collection_id):
        """
        For multiple files, always use async
        """
        job_ids = []
    
        for url in file_urls:
            job = client.index(
                collection_id=collection_id,
                video_url=url,
                process_async=True
            )
            job_ids.append(job.id)
    
        print(f"Submitted {len(job_ids)} jobs")
        return job_ids
    
    # Usage
    # Small image: sync is fine
    sync_example("https://example.com/small-image.jpg", "images")
    
    # Large video: use async
    async_example("https://example.com/large-video.mp4", "videos")

    Related Resources:

    async
    sync
    comparison
    processing

    What is the difference between keyword search and semantic search?

    Keyword search matches exact terms, while semantic search understands meaning and finds conceptually similar results even without matching words.

    beginner

    Keyword search (also called lexical search) finds documents containing the exact words in your query using techniques like TF-IDF and BM25. It is fast and precise but misses synonyms, paraphrases, and conceptual matches, searching for 'car' will not find results about 'automobile'. Semantic search uses AI embedding models to convert both queries and documents into numerical vectors that capture meaning. It finds conceptually similar content regardless of exact wording, so 'car' will match 'automobile', 'vehicle', and even 'Tesla Model 3'. The tradeoff is that semantic search requires more compute for embedding generation and may occasionally return loosely related results. In practice, the best approach is hybrid search, which combines both methods: use keyword matching for precision (exact names, codes, IDs) and semantic matching for recall (concepts, descriptions, natural language). Mixpeek supports hybrid search pipelines that blend both approaches with configurable weights.

    keyword search
    semantic search
    comparison
    hybrid search
    NLP

    Troubleshooting

    4 questions

    Why are my search results poor or irrelevant?

    Common causes include mismatched embedding models, insufficient training data, poor query phrasing, or missing metadata filters.

    intermediate
    Code Example

    Poor search quality usually stems from one of these issues: 1) Model mismatch - Using different embedding models for indexing vs querying, or using models trained on different domains than your data. Solution: Ensure consistent model usage and choose domain-appropriate models. 2) Query phrasing - Very short queries or queries with typos reduce accuracy. Solution: Implement query expansion, spell correction, or encourage longer queries. 3) Data quality - Low-quality source content, missing metadata, or poorly structured data. Solution: Clean your data, add rich metadata, and structure content consistently. 4) Missing filters - Not using metadata filters to narrow results. Solution: Combine vector search with filters on categories, dates, or attributes. 5) Wrong similarity metric - Using cosine vs dot product can matter. Solution: Experiment with different metrics. 6) Insufficient data - Small datasets don't provide enough context. Solution: Ensure at least 1000+ items for meaningful results. Use Mixpeek's analytics to identify which queries perform poorly and iterate on your configuration.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # GOOD: Use metadata filters + hybrid search
    results = client.search(
        collection_id="products",
        query="comfortable running shoes",
        filters={
            "category": "footwear",
            "price": {"$lt": 200},
            "in_stock": True
        },
        hybrid_search=True,  # Combine vector + keyword
        min_score=0.7  # Filter low-confidence results
    )
    
    # BAD: No filters, short query
    # results = client.search(collection_id="products", query="shoes")
    troubleshooting
    search quality
    debugging

    How do I reduce costs when processing large video libraries?

    Use scene detection instead of per-frame processing, batch process during off-peak hours, and implement smart caching to avoid reprocessing.

    advanced
    Code Example

    Cost optimization for video processing involves several strategies: 1) Scene-based processing - Instead of embedding every frame (30fps = 1800 frames/minute), use scene detection to only process when content changes significantly. This reduces processing by 90%+. 2) Adaptive resolution - Process low-resolution versions for initial indexing, then high-res only for selected scenes. 3) Batch processing - Process large uploads in batches during off-peak hours with async workflows. 4) Smart caching - Store embeddings and avoid reprocessing unchanged content. Check file hashes before processing. 5) Selective features - Only enable feature extractors you actually need. Don't run face detection if you only need scene classification. 6) Sampling strategies - For very long videos, sample keyframes at intervals rather than processing everything. 7) Progressive indexing - Start with thumbnails, add full processing on-demand when videos are accessed. Mixpeek's scene detection and async processing help optimize costs automatically.

    Code Example

    from mixpeek import Mixpeek
    
    client = Mixpeek(token="your_token")
    
    # COST-OPTIMIZED: Scene detection, selective extractors
    collection = client.collections.create(
        name="video_library_optimized",
        feature_extractors=[
            "scene-splitting",  # Only process scene changes
            "video-embedding"   # Only essential embeddings
        ],
        config={
            "scene_threshold": 0.3,  # Adjust sensitivity
            "max_scenes_per_video": 50,  # Cap scenes for very long videos
            "resolution": "480p"  # Lower res for initial processing
        }
    )
    
    # Process asynchronously in batches
    client.ingest(
        collection_id=collection.id,
        source="s3://my-videos/",
        batch_size=100,
        process_async=True  # Don't block, process in background
    )
    
    # EXPENSIVE: Per-frame processing, all extractors
    # Don't do this for large libraries!
    troubleshooting
    cost optimization
    performance

    How do I optimize search latency for faster results?

    Use metadata filters to narrow search space, implement caching, reduce top_k value, and consider smaller embedding models.

    advanced
    Code Example

    Search latency optimization strategies: 1) Metadata filtering - Apply filters before vector search to reduce candidate set. Filter on category, date, or other indexed fields. Example: filter to 'electronics' before searching 1M products. 2) Caching - Cache popular queries at application layer (Redis, Memcached). Set TTL based on data update frequency. Cache warm-up: pre-compute results for common queries. Invalidate cache when collection updates. 3) Query optimization - Reduce top_k if you don't need many results (10 vs 100 = 10x faster). Use approximate nearest neighbor (enabled by default) instead of exact search. Consider hybrid search only when needed (pure vector is faster). 4) Collection design - Use smaller embedding dimensions (384d vs 768d) if acceptable for your use case. Partition large collections by category/date. Create separate collections for different search contexts. 5) Model selection - Smaller, faster embedding models for latency-sensitive apps. Batch embed queries if possible (amortize overhead). 6) Infrastructure - Use CDN for frequently accessed results. Scale horizontally with multiple collections. Enterprise plans offer dedicated compute for guaranteed performance.

    Code Example

    from mixpeek import Mixpeek
    import redis
    import hashlib
    import json
    
    client = Mixpeek(token="your_token")
    cache = redis.Redis(host='localhost', port=6379, db=0)
    
    def search_with_cache(collection_id, query, filters=None, top_k=10, cache_ttl=3600):
        """
        Search with Redis caching
        """
        # Create cache key from query parameters
        cache_key = hashlib.md5(
            json.dumps({
                "collection": collection_id,
                "query": query,
                "filters": filters,
                "top_k": top_k
            }, sort_keys=True).encode()
        ).hexdigest()
    
        # Check cache
        cached_result = cache.get(cache_key)
        if cached_result:
            print("Cache hit!")
            return json.loads(cached_result)
    
        # Cache miss - query Mixpeek
        print("Cache miss - querying Mixpeek")
        results = client.search(
            collection_id=collection_id,
            query=query,
            filters=filters,
            top_k=top_k
        )
    
        # Serialize and cache results
        serialized = json.dumps([
            {"id": r.id, "score": r.score, "metadata": r.metadata}
            for r in results
        ])
        cache.setex(cache_key, cache_ttl, serialized)
    
        return results
    
    # Optimized search with metadata pre-filtering
    def fast_search(collection_id, query, category=None, max_results=10):
        """
        Use filters to reduce search space before vector search
        """
        filters = {}
    
        # Filter by category first (index scan, very fast)
        if category:
            filters["category"] = category
    
        # Only search recent items (temporal filter)
        filters["created_at"] = {"$gte": "2024-01-01"}
    
        # Smaller top_k for faster search
        results = client.search(
            collection_id=collection_id,
            query=query,
            filters=filters,
            top_k=max_results,  # Request only what you need
            approximate=True  # Use ANN (default, but explicit)
        )
    
        return results
    
    # Pre-warm cache for common queries
    def warm_cache(collection_id, common_queries):
        """
        Pre-compute and cache results for popular queries
        """
        for query in common_queries:
            print(f"Warming cache: {query}")
            search_with_cache(collection_id, query)
    
    # Usage
    common_queries = [
        "wireless headphones",
        "running shoes",
        "laptop backpack"
    ]
    warm_cache("products", common_queries)

    Related Resources:

    performance
    optimization
    latency
    troubleshooting

    Why is my indexing slow and how can I speed it up?

    Slow indexing is usually caused by large files, many feature extractors, or sequential processing; use async mode, batch uploads, and optimize extractors.

    intermediate
    Code Example

    Common causes of slow indexing and solutions: 1) File size - Large videos (>1GB) take longer to download and process. Solution: Use cloud storage (S3) co-located with Mixpeek for faster transfers, compress videos before upload, or downsample resolution if acceptable. 2) Feature extractor overhead - Running many extractors increases processing time. Solution: Only enable extractors you actually use, run expensive extractors (transcription, object detection) selectively, use scene-based processing instead of per-frame. 3) Sequential vs parallel processing - Processing files one-by-one is slow. Solution: Use batch ingestion (processes in parallel), use async mode (don't wait for each file), spawn multiple ingestion jobs concurrently (respect rate limits). 4) Network bottlenecks - Slow upload speeds to Mixpeek. Solution: Use S3/GCS direct integration (Mixpeek reads from cloud storage), batch upload files to cloud first, then trigger ingestion, use CDN for frequently accessed source files. 5) Rate limiting - Build tier has lower throughput limits. Solution: Upgrade to Scale for higher limits, implement exponential backoff and retry, spread ingestion over time to avoid bursts.

    Code Example

    from mixpeek import Mixpeek
    from concurrent.futures import ThreadPoolExecutor, as_completed
    import time
    
    client = Mixpeek(token="your_token")
    
    # SLOW: Sequential sync processing
    def slow_indexing(video_urls, collection_id):
        """
        Don't do this for many files!
        """
        start = time.time()
        for url in video_urls:
            result = client.index(
                collection_id=collection_id,
                video_url=url,
                process_async=False  # Blocks until complete
            )
            print(f"Indexed: {result.id}")
    
        print(f"Total time: {time.time() - start}s")
    
    # FAST: Async parallel processing
    def fast_indexing(video_urls, collection_id, max_workers=10):
        """
        Much faster - parallel async ingestion
        """
        start = time.time()
    
        def index_video(url):
            return client.index(
                collection_id=collection_id,
                video_url=url,
                process_async=True  # Returns immediately
            )
    
        # Process multiple files concurrently
        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            futures = {executor.submit(index_video, url): url for url in video_urls}
    
            for future in as_completed(futures):
                url = futures[future]
                try:
                    result = future.result()
                    print(f"Started job: {result.job_id} for {url}")
                except Exception as e:
                    print(f"Failed to start job for {url}: {e}")
    
        print(f"All jobs submitted in: {time.time() - start}s")
    
    # FASTEST: Bulk S3 ingestion
    def fastest_indexing(s3_bucket, prefix, collection_id):
        """
        Let Mixpeek handle parallelization
        """
        start = time.time()
    
        job = client.ingest(
            collection_id=collection_id,
            source=f"s3://{s3_bucket}/{prefix}",
            process_async=True,
            batch_size=500,  # Process in large batches
            config={
                # Only essential extractors
                "feature_extractors": [
                    "video-embedding",
                    "scene-splitting"
                ],
                # Optimize settings
                "scene_threshold": 0.4,  # Fewer scenes = faster
                "resolution": "720p"  # Lower res if acceptable
            }
        )
    
        print(f"Bulk job started: {job.id} in {time.time() - start}s")
        return job.id
    
    # Monitor async jobs
    def wait_for_completion(job_id, timeout=3600):
        """
        Wait for bulk job to complete
        """
        start = time.time()
        while time.time() - start < timeout:
            status = client.jobs.get(job_id)
    
            if status.status == "completed":
                print(f"Completed: {status.processed} files in {time.time() - start}s")
                return status
    
            print(f"Progress: {status.processed}/{status.total}")
            time.sleep(10)
    
        raise TimeoutError()
    
    # Usage
    urls = [f"https://example.com/video{i}.mp4" for i in range(100)]
    fast_indexing(urls, "my_collection", max_workers=20)

    Related Resources:

    indexing
    performance
    troubleshooting
    optimization

    Still have questions?

    Check out our comprehensive documentation or reach out to our team