Skip to content

Direct API Integration

This guide will walk you through integrating Marqo's powerful multimodal search capabilities directly into your ecommerce platform using the Marqo API. Learn how to create intelligent product search that understands both text descriptions and visual content.

Prerequisites

Overview

Marqo enables you to build sophisticated ecommerce search experiences that can: - Search products using natural language descriptions - Find products by visual similarity - Combine text and image search for better results - Provide semantic understanding beyond keyword matching

API Reference

For detailed API documentation including all available parameters, error codes, and advanced configuration options, visit the Marqo API Reference.

Step 1: Initialize Marqo Client

First, set up your connection to the Marqo API:

Python

from marqo import Client

# Initialize the Marqo client with your API key
api_key = "your_api_key_here"
mq = Client("https://api.marqo.ai", api_key=api_key)

cURL

# Set your API key as an environment variable
export MARQO_API_KEY="your_api_key_here"

Step 2: Create Your Product Search Index

Create a specialized index optimized for ecommerce product search:

Python

# Define your ecommerce index name
index_name = 'ecommerce-product-search'

# Configure settings optimized for ecommerce
settings = {
    "treatUrlsAndPointersAsImages": True,
    "model": "Marqo/marqo-ecommerce-embeddings-L",
    "numberOfShards": 1,
    "numberOfReplicas": 0,
    "inferenceType": "marqo.GPU",
    "storageClass": "marqo.basic",
    "numberOfInferences": 1
}

# Create the index
mq.create_index(index_name, settings_dict=settings)

cURL

curl -X POST 'https://api.marqo.ai/api/v2/indexes/ecommerce-product-search' \
-H "x-api-key: $MARQO_API_KEY" \
-H 'Content-type: application/json' \
-d '{
  "treatUrlsAndPointersAsImages": true,
  "model": "Marqo/marqo-ecommerce-embeddings-L",
  "numberOfShards": 1,
  "numberOfReplicas": 0,
  "inferenceType": "marqo.GPU",
  "storageClass": "marqo.basic",
  "numberOfInferences": 1
}'

Step 3: Index Your Product Catalog

Add your products to the index using multimodal mappings that combine text and visual information:

Python

# Sample ecommerce product data
products = [
    {
        "product_id": "SKU001",
        "title": "Premium Wireless Bluetooth Headphones",
        "description": "High-quality over-ear headphones with noise cancellation and 30-hour battery life",
        "category": "Electronics",
        "brand": "AudioTech",
        "price": 199.99,
        "image_url": "https://your-cdn.com/products/headphones-001.jpg",
        "tags": ["wireless", "bluetooth", "noise-cancelling", "premium"]
    },
    {
        "product_id": "SKU002", 
        "title": "Organic Cotton T-Shirt",
        "description": "Comfortable everyday t-shirt made from 100% organic cotton in navy blue",
        "category": "Clothing",
        "brand": "EcoWear",
        "price": 29.99,
        "image_url": "https://your-cdn.com/products/tshirt-navy-002.jpg",
        "tags": ["organic", "cotton", "casual", "navy"]
    },
    {
        "product_id": "SKU003",
        "title": "Stainless Steel Water Bottle",
        "description": "Insulated water bottle keeps drinks cold for 24 hours, hot for 12 hours",
        "category": "Home & Kitchen",
        "brand": "HydroLife",
        "price": 34.99,
        "image_url": "https://your-cdn.com/products/bottle-steel-003.jpg",
        "tags": ["insulated", "stainless-steel", "eco-friendly", "travel"]
    }
]

# Index products with multimodal mappings
response = mq.index(index_name).add_documents(
    products,
    client_batch_size=50,  # Batch size for efficient indexing
    mappings={
        "product_multimodal": {
            "type": "multimodal_combination",
            "weights": {
                "title": 0.1,        # Product title importance
                "image_url": 0.9,     # Image visual features (highest weight)
            }
        }
    },
    tensor_fields=["product_multimodal"]  # Generate embeddings for this combined field
)

print(f"Indexed {len(products)} products successfully")

cURL

curl -X POST 'https://api.marqo.ai/api/v2/indexes/ecommerce-product-search/documents' \
-H "x-api-key: $MARQO_API_KEY" \
-H 'Content-type: application/json' \
-d '{
  "documents": [
    {
      "product_id": "SKU001",
      "title": "Premium Wireless Bluetooth Headphones",
      "description": "High-quality over-ear headphones with noise cancellation and 30-hour battery life",
      "category": "Electronics",
      "brand": "AudioTech", 
      "price": 199.99,
      "image_url": "https://your-cdn.com/products/headphones-001.jpg",
      "tags": ["wireless", "bluetooth", "noise-cancelling", "premium"]
    }
  ],
  "mappings": {
    "product_multimodal": {
      "type": "multimodal_combination",
      "weights": {
        "title": 0.1,
        "image_url": 0.9,
      }
    }
  },
  "tensorFields": ["product_multimodal"]
}'

Step 4: Implement Product Search with Hybrid Parameters

Now you can search your product catalog using natural language queries, with hybrid search combining semantic understanding and traditional keyword matching:

Python

# Search for products using natural language
query = "comfortable headphones for music"

search_results = mq.index(index_name).search(
    q=query,
    limit=10,  # Number of results to return
    searchable_attributes=["product_multimodal"]  # Search in multimodal field
)

# Process results
for hit in search_results['hits']:
    print(f"Product: {hit['title']}")
    print(f"Score: {hit['_score']:.3f}")
    print(f"Price: ${hit['price']}")
    print("---")

Advanced Hybrid Search with Filters

Python

# Advanced search with hybrid parameters and filters
search_results = mq.index(index_name).search(
    q="wireless audio device",
    searchMethod="HYBRID",  # Use hybrid search (semantic + lexical)
    hybridParameters={
        "alpha": 0.7,  # Weight between semantic (1.0) and lexical (0.0) search
        "searchableAttributes": ["product_multimodal"],
        "lexicalSearchParameters": {
            "searchableAttributes": ["title", "description", "tags"]
        }
    },
    filter="category:(Electronics) AND price:[50 TO 300]",  # Filter by category and price range
    limit=5,
    showHighlights=True  # Show matching text snippets
)

# Display enhanced results
for hit in search_results['hits']:
    print(f"Product: {hit['title']}")
    print(f"Brand: {hit['brand']}")
    print(f"Price: ${hit['price']}")
    print(f"Relevance Score: {hit['_score']:.3f}")

    # Show highlighted matches if available
    if '_highlights' in hit:
        for field, highlights in hit['_highlights'].items():
            print(f"Matches in {field}: {highlights}")
    print("---")

cURL

curl -X POST 'https://api.marqo.ai/api/v2/indexes/ecommerce-product-search/search' \
-H "x-api-key: $MARQO_API_KEY" \
-H 'Content-type: application/json' \
-d '{
  "q": "wireless audio device",
  "searchMethod": "HYBRID",
  "hybridParameters": {
    "alpha": 0.7,
    "searchableAttributes": ["product_multimodal"],
    "lexicalSearchParameters": {
      "searchableAttributes": ["title", "description", "tags"]
    }
  },
  "filter": "category:(Electronics) AND price:[50 TO 300]",
  "limit": 5,
  "showHighlights": true
}'

Step 5: Visual Search Implementation

Enable customers to search for products using images:

Python

# Search using an image URL
image_query = "https://customer-uploads.com/search-image.jpg"

visual_search_results = mq.index(index_name).search(
    q=image_query,
    searchMethod="TENSOR",  # Use tensor search for image queries
    searchableAttributes=["product_multimodal"],
    limit=8
)

print("Visually similar products:")
for hit in visual_search_results['hits']:
    print(f"Product: {hit['title']}")
    print(f"Visual similarity: {hit['_score']:.3f}")
    print(f"Category: {hit['category']}")
    print("---")

Step 6: Real-time Catalog Updates

Keep your search index synchronized with your product catalog:

Add New Products

# Add a new product
new_product = {
    "product_id": "SKU004",
    "title": "Smart Fitness Watch",
    "description": "Track your workouts, heart rate, and sleep with GPS connectivity",
    "category": "Electronics",
    "brand": "FitTech",
    "price": 299.99,
    "image_url": "https://your-cdn.com/products/smartwatch-004.jpg",
    "tags": ["smartwatch", "fitness", "GPS", "health"]
}

mq.index(index_name).add_documents([new_product])

Update Existing Products

# Update product information
updated_product = {
    "product_id": "SKU001",
    "price": 179.99,  # New sale price
    "tags": ["wireless", "bluetooth", "noise-cancelling", "premium", "sale"]
}

mq.index(index_name).add_documents([updated_product])

Troubleshooting

Common issues and solutions:

  • Low Search Relevance: Adjust multimodal weights or hybrid parameters
  • Slow Indexing: Increase batch size and use client_batch_size parameter
  • Image Processing Errors: Ensure image URLs are publicly accessible and in supported formats (JPEG, PNG, WebP)
  • Memory Issues: Consider using smaller batches for large product catalogs

Support

For technical support and questions: - Community: Marqo Slack Community - Documentation: docs.marqo.ai - Support: support@marqo.ai