はじめに
このガイドでは、バックエンドデータベースとしてCouchbaseを使用し、強力なセマンティック検索エンジンを構築する方法について説明します。, Mistral AI as the AI-powered embedding Model. Semantic search goes beyond simple keyword matching by understanding the context and meaning behind the words in a query, making it an essential tool for applications that require intelligent information retrieval. This tutorial is designed to be beginner-friendly, with clear, step-by-step instructions that will equip you with the knowledge to create a fully functional semantic search system from scratch. Alternatively, if you want to perform semantic search using the Search Vector Index, please take a look at このもの。.
Couchbase is a NoSQL distributed document database (JSON) with many of the best features of a relational DBMS: SQL, distributed ACID transactions, and much more. Couchbase カペラ is the easiest way to get started, but you can also download and run Couchbase Server on-premises.
Mistral AI is a research lab building the best open source models in the world. La Plateforme enables developers and enterprises to build new products and applications, powered by Mistral’s open source and commercial LLMs.
について Mistral AI APIs empower LLM applications via:
- Text generation, enables streaming and provides the ability to display partial model results in real-time
- Code generation, empowers code generation tasks, including fill-in-the-middle and code completion
- Embeddings, useful for RAG where it represents the meaning of text as a list of numbers
- Function calling, enables Mistral models to connect to external tools
- Fine-tuning, enables developers to create customized and specialized models
- JSON mode, enables developers to set the response format to json_object
- Guardrailing, enables developers to enforce policies at the system level of Mistral models
This tutorial demonstrates how to use Mistral AI’s embedding capabilities with Couchbase’s Hyperscale and Composite Vector Indexes for optimized vector search operations. Hyperscale and Composite Vector Indexes provide superior performance for vector operations compared to traditional search methods, especially for large-scale applications.
始める前に
Get Credentials for Mistral AI
どうか従ってください 説明書 to generate the Mistral AI credentials.
Capellaで無料Tier運用クラスターを作成およびデプロイ
To get started with Couchbase Capella, create an account and use it to deploy a forever free tier operational cluster. This account provides you with a environment where you can explore and learn about Capella with no time constraint.
To know more, please follow the 説明書.
Note: Hyperscale and Composite Vector Indexes require Couchbase Server 8.0 or above, unlike Search Vector Index which works with 7.6+
Couchbase Capellaの設定
「couchbase」を以下のように実行すると、 Capella, 以下のような前提条件を満たしている必要があります。.
- Create the データベース認証情報 アプリケーションで使用される travel-sample バケット (読み取りおよび書き込み) にアクセスします。.
- アクセス許可を許可する アプリケーションが実行されている IP からのクラスタへの接続です。.
Install necessary libraries
%pip install couchbase==4.4.0 mistralai==1.9.10 langchain-couchbase==0.5.0 langchain-core==0.3.76 python-dotenv==1.1.1
[Output too long, omitted for brevity]
Imports
from datetime import timedelta
from mistralai import Mistral
from couchbase.auth import PasswordAuthenticator
from couchbase.cluster import Cluster
from couchbase.options import ClusterOptions
from langchain_couchbase.vectorstores import CouchbaseQueryVectorStore
from langchain_couchbase.vectorstores import DistanceStrategy, IndexType
from langchain_core.embeddings import Embeddings
from typing import List
from dotenv import load_dotenv
import os
import time
前提条件
import getpass
## Load environment variables from .env file if it exists
load_dotenv()
## Load from environment variables or prompt for input
CB_HOST = os.getenv('CB_HOST') or input("Cluster URL:")
CB_USERNAME = os.getenv('CB_USERNAME') or input("Couchbase username:")
CB_PASSWORD = os.getenv('CB_PASSWORD') or getpass.getpass("Couchbase password:")
CB_BUCKET_NAME = os.getenv('CB_BUCKET_NAME') or input("Couchbase bucket:")
SCOPE_NAME = os.getenv('SCOPE_NAME') or input("Couchbase scope:")
COLLECTION_NAME = os.getenv('COLLECTION_NAME') or input("Couchbase collection:")
Couchbase Connection
auth = PasswordAuthenticator(
CB_USERNAME,
CB_PASSWORD
)
options = ClusterOptions(auth)
options.apply_profile("wan_development")
cluster = Cluster(CB_HOST, options)
cluster.wait_until_ready(timedelta(seconds=40))
bucket = cluster.bucket(CB_BUCKET_NAME)
scope = bucket.scope(SCOPE_NAME)
collection = scope.collection(COLLECTION_NAME)
Couchbaseでのコレクションのセットアップ
setup_collection() 関数は、Couchbase で階層的なデータ構造の作成と設定を処理します:
-
バケットの作成:
- 指定されたバケットが存在するかどうかをチェックし、存在しない場合は作成します。
- RAM割り当て(1024MB)、レプリケーション(無効)などのバケットプロパティを設定します
- 注:Capellaではバケットを作成できません。
-
スコープ管理:
- リクエストされたスコープがバケット内に存在するかどうかを確認します。
- 必要に応じて新しいスコープを作成します(デフォルトの「_default」スコープの場合は除きます)。
-
コレクションのセットアップ:
- 範囲内でコレクションが存在するかどうかをチェックする
- 存在しない場合コレクションを作成する
- コレクションの準備が完了するまで2秒待つ
追加のタスク:
- 既存のドキュメントをすべてクリアして、状態をクリアにします
- 包括的なエラー処理とログの記録を実装
def setup_collection(cluster, bucket_name, scope_name, collection_name):
try:
## Check if bucket exists, create if it doesn't
try:
bucket = cluster.bucket(bucket_name)
except Exception as e:
bucket_settings = CreateBucketSettings(
name=bucket_name,
bucket_type='couchbase',
ram_quota_mb=1024,
flush_enabled=True,
num_replicas=0
)
cluster.buckets().create_bucket(bucket_settings)
time.sleep(2) # Wait for bucket creation to complete and become available
bucket = cluster.bucket(bucket_name)
bucket_manager = bucket.collections()
## Check if scope exists, create if it doesn't
scopes = bucket_manager.get_all_scopes()
scope_exists = any(scope.name == scope_name for scope in scopes)
if not scope_exists and scope_name != "_default":
bucket_manager.create_scope(scope_name)
## Check if collection exists, create if it doesn't
collections = bucket_manager.get_all_scopes()
collection_exists = any(
scope.name == scope_name and collection_name in [col.name for col in scope.collections]
for scope in collections
)
if not collection_exists:
bucket_manager.create_collection(scope_name, collection_name)
## Wait for collection to be ready
collection = bucket.scope(scope_name).collection(collection_name)
time.sleep(2) # Give the collection time to be ready for queries
## Clear all documents in the collection
try:
query = f"DELETE FROM `{bucket_name}`.`{scope_name}`.`{collection_name}`"
cluster.query(query).execute()
except Exception as e:
print(f"Error while clearing documents: {str(e)}. The collection might be empty.")
return collection
except Exception as e:
raise RuntimeError(f"Error setting up collection: {str(e)}")
setup_collection(cluster, CB_BUCKET_NAME, SCOPE_NAME, COLLECTION_NAME)
<couchbase.collection.Collection at 0x1118984a0>
Creating Mistral AI Embeddings Wrapper
Since Mistral AI doesn’t have native LangChain integration, we need to create a custom wrapper class that implements the LangChain Embeddings interface. This will allow us to use Mistral AI’s embedding model with Couchbase’s Hyperscale and Composite vector indexes.
class MistralAIEmbeddings(Embeddings):
"""Custom Mistral AI Embeddings wrapper for LangChain compatibility."""
def __init__(self, api_key: str, model: str = "mistral-embed"):
self.client = Mistral(api_key=api_key)
self.model = model
def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Embed search docs."""
try:
response = self.client.embeddings.create(
model=self.model,
inputs=texts,
)
return [embedding.embedding for embedding in response.data]
except Exception as e:
raise ValueError(f"Error generating embeddings: {str(e)}")
def embed_query(self, text: str) -> List[float]:
"""Embed query text."""
try:
response = self.client.embeddings.create(
model=self.model,
inputs=[text],
)
return response.data[0].embedding
except Exception as e:
raise ValueError(f"Error generating query embedding: {str(e)}")
Mistral Connection
MISTRAL_API_KEY = os.getenv('MISTRAL_API_KEY') or getpass.getpass("Mistral API Key:")
embeddings = MistralAIEmbeddings(api_key=MISTRAL_API_KEY, model="mistral-embed")
mistral_client = Mistral(api_key=MISTRAL_API_KEY)
Mistral API Key: ········
Understanding Hyperscale and Composite Vector Indexes
Optimizing Vector Search with Hyperscale and Composite Vector Indexes
With Couchbase 8.0+, you can leverage the power of Hyperscale and Composite Vector Indexes, which offer significant performance improvements over Search Vector Index approaches for vector-first workloads. These indexes provide high-performance vector similarity search with advanced filtering capabilities and are designed to scale to billions of vectors.
Hyperscale and Composite Vector Indexes vs Search Vector Indexes: Choosing the Right Approach
| 特徴 | Hyperscale and Composite Vector Index | 検索ベクトルインデックス |
|---|---|---|
| ベストフォー | ベクトルファーストワークロード、複雑なフィルタリング、高QPS性能 | ハイブリッド検索と高い想起率 |
| Couchbaseのバージョン | 8.0.0+ | 7.6+ |
| フィルタリング | プレフィルタリング用 どこ (複合)またはポストフィルタリング(ハイパースケール)の項 |
柔軟な順序による事前フィルタリング |
| スケーラビリティ | 最大数十億のベクトル(ハイスケーラ) | 最大1000万のベクトル |
| パフォーマンス | 低メモリ使用量で同時実行に対応 | テキストとベクターのクエリに最適 |
Vector Index Types
Couchbaseは2種類の明確なクエリベースのベクトルインデックスを提供しており、それぞれが異なるユースケースに最適化されています:
ハイパースケール・ベクトル・インデックス
- ベストなものコンテンツの発見、おすすめ、セマンティック検索などの純粋なベクトル検索
- 使用する際: あなたは主にベクトルのみのクエリを実行し、複雑なスカラーフィルターは使用しません。
- 機能:
- 低メモリ使用量で高いパフォーマンス
- 同時実行に対応した最適化
- 数十億のベクトルに対応するように設計されています
- 基本的なメタデータフィルタリング用の後処理フィルタリングをサポート
複合ベクトルインデックス
- ベストなものベクトル類似性をスカラー値のフィルタリングと組み合わせたフィルタード・ベクター検索
- 使用する際: あなたのクエリはベクトル類似性と、大量のデータを排除するスカラーフィルターを組み合わせています。
- 機能:
- スカラー属性によるベクトル比較の範囲を縮小する効率的なプリフィルタリング
- Best for well-defined workloads requiring complex filtering using Composite Vector Index features
- ベクトル検索と組み合わせて範囲検索をサポート
このチュートリアルのインデックスタイプ選択
このチュートリアルでは、 ハイパースケール・ベクトル・インデックス and running vector similarity queries. Hyperscale Vector Index is ideal for semantic search scenarios where you want:
- 高性能ベクトル検索 大規模なデータセット全体で
- 低遅延 リアルタイムアプリケーション向け
- スケーラビリティ 成長するベクトルコレクションを管理するため
- 同時進行中の操作 マルチユーザー環境向け
The Hyperscale Vector Index will provide optimal performance for our OpenAI embedding-based semantic search implementation.
代替方法:複合ベクトルインデックス
あなたのユースケースでスカラー属性を使用した複雑なフィルタリングが必要な場合は、 複合ベクトルインデックス 代わりに:
## 代替案:フィルタリングされた検索用の複合インデックスを作成する
vector_store.create_index(
index_type=IndexType.COMPOSITE、
index_description="IVF,SQ8",
distance_metric=DistanceStrategy.COSINE,
index_name="pydantic_composite_index",
)
以下の場合に複合インデックスを使用してください:
- ベクターの類似性を確認する前に、ドキュメントのメタデータや属性に基づいてフィルタリングする必要があります。
- あなたのクエリはベクター検索と WHERE 句を組み合わせています
- 明確なフィルタリング要件があるため、検索領域を小さくすることができます。
注記複合インデックスは、スカラー属性による事前フィルタリングが可能なので、特定のカテゴリ、日付範囲、またはユーザー固有のデータセグメント内で検索する必要があるアプリケーションに最適です。.
インデックス構成の理解 (Couchbase 8.0 の機能)
Hyperscaleインデックスを作成する前に、ベクトルストレージと検索パフォーマンスを最適化する構成パラメータを理解しておくことが重要です。 index_description このパラメータは、Couchbaseが中心点と量子化によってベクトルストレージを最適化する方法を制御します。.
インデックスの説明形式: '「IVF[],{PQ|SQ}「'
セントリオード(IVF – Inverted File)
- より高速な検索のためにデータセットをどのように分割するかを制御します。
- より多くの中心点 = より高速な検索、より長いトレーニング時間
- 中心点が少ない = 検索が遅くなる、トレーニング時間が短くなる
- 省略された場合(例えば
IVF、SQ8( ), Couchbaseはデータセットのサイズに基づいて自動的に選択します
スケール量子化(SQ):
SQ4,SQ6,SQ8(次元ごとに4ビット、6ビット、または8ビット)- メモリ使用量が低くなり、検索が高速になり、精度がわずかに低下しました。
製品量子化(PQ):
- フォーマット
PQx(例:,PQ32x8) - 非常に大きなデータセット向けのより優れた圧縮
- より複雑ですが、インデックスサイズが小さくなっても精度を維持できます。
一般的な構成例
IVF、SQ8– 自動中心点、8ビットのスカララル量子化(デフォルトは良好)IVF1000、SQ6– 1000 個の中心点、6 ビットのスカララル量子化IVF,PQ32x8– 自動中心点、8ビットの32サブ量子化器
詳細な設定オプションについては、 量子化と中心点の設定.
For more information on Hyperscale and Composite Vector Indexes, see Couchbase Hyperscale and Composite Vector Indexes Documentation.
私たちの構成選択
このチュートリアルでは、 IVF、SQ8 以下が提供されています:
- 自動選択された中心点 データセットのサイズに合わせて最適化されています
- 8ビットのスカララル量子化 速度、メモリ使用量、そして精度のバランスを良好にするために
- COSINE距離指標 意味類似性の検索に最適
- 最適な性能 ほとんどのセマンティック検索ユースケース向け
Setting Up Couchbase Hyperscale Vector Store
Instead of using FTS (Full-Text Search), we’ll use Couchbase’s Hyperscale Index for vector operations. Hyperscale Indexes provide better performance for vector search operations.
vector_store = CouchbaseQueryVectorStore(
cluster=cluster,
bucket_name=CB_BUCKET_NAME,
scope_name=SCOPE_NAME,
collection_name=COLLECTION_NAME,
embedding=embeddings,
distance_metric=DistanceStrategy.COSINE
)
print("Hyperscale Vector Store created successfully!")
Hyperscale Vector Store created successfully!
Embedding Documents
Mistral client can be used to generate vector embeddings for given text fragments. These embeddings represent the sentiment of corresponding fragments and can be stored in Couchbase for further retrieval. A custom embedding text can also be added into the embedding texts array by running this code block:
texts = [
"Couchbase Server is a multipurpose, distributed database that fuses the strengths of relational databases such as SQL and ACID transactions with JSON's versatility, with a foundation that is extremely fast and scalable.",
"It's used across industries for things like user profiles, dynamic product catalogs, GenAI apps, vector search, high-speed caching, and much more.",
input("custom embedding text")
]
## Store documents in the Hyperscale Vector store
vector_store.add_texts(texts)
print("Documents added to Hyperscale Vector store successfully!")
custom embedding text Couchbase is commonly used to store and search embeddings for GenAI and retrieval augmented generation applications.
Documents added to Hyperscale Vector store successfully!
Couchbaseでのセマンティック検索の理解
セマンティック検索は、クエリの背後にある意味や文脈を理解することで、従来のキーワードマッチングを超えた機能を提供します。Couchbaseでは、次のような方法で動作します。
セマンティック検索の仕組み
-
ベクトルエンベディング: Documents and queries are converted into high-dimensional vectors using an embeddings model (in our case, Mistral AI’s mistral-embed)
-
類似性計算クエリが実行される際、CouchbaseはCOSINE距離指標を用いて、クエリベクトルと保存されたドキュメントベクトルを比較します。
-
結果ランキングドキュメントはベクトル距離に基づいてランク付けされます(低い距離はより類似する意味を表します)。
-
柔軟な構成さまざまな距離指標(コサイン、ユークリッド、ドット積)やエンベディングモデルを、お客様のニーズに合わせて使用できます。
について similarity_search_with_score このメソッドはこのプロセス全体を実行し、類似度スコアとともにドキュメントを返します。これにより、正確なキーワードが一致しない場合でも、意味的に関連するコンテンツを見つけることができます。.
それでは、セマンティック検索を実際に見て、さまざまな最適化戦略でそのパフォーマンスを測定してみましょう。.
Vector Search Performance Optimization
それでは、さまざまな最適化戦略によるパフォーマンス上の利点を測定し比較してみましょう。ここでは、2つのフェーズで包括的なパフォーマンス分析を行います。
Performance Testing Phases
-
第1フェーズ – 基線パフォーマンス: Test vector search without Hyperscale & Composite Vector indexes to establish baseline metrics
-
Phase 2 – Hyperscale & Composite Vector Index-Optimized Searchハイスケールインデックスの作成とパフォーマンス改善の測定
重要な背景:
- Hyperscale & Composite Vector Index performance benefits scale with dataset size and concurrent load
- With our dataset (~3 documents), improvements may be modest
- Production environments with millions of vectors show significant Hyperscale and Composite Vector Index advantages
- The combination of Hyperscale and Composite Vector Index + embeddings provides optimal semantic search performance
Phase 1: Baseline Performance (Without Hyperscale Vector Index or Composite Vector Index)
First, let’s test the search performance without Hyperscale Vector index or Composite Vector Index. This will help us establish a baseline for comparison.
import logging
## Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
## Phase 1: Baseline Performance (Without Hyperscale or Composite Vector Index)
print("="*80)
print("PHASE 1: BASELINE PERFORMANCE (Without Hyperscale or Composite Vector Index)")
print("="*80)
query = "name a multipurpose database with distributed capability"
try:
## Perform the semantic search
start_time = time.time()
search_results = vector_store.similarity_search_with_score(query, k=3)
baseline_time = time.time() - start_time
logging.info(f"Baseline search completed in {baseline_time:.2f} seconds")
## Display search results
print(f"nBaseline Search Results (completed in {baseline_time:.4f} seconds):")
print("-" * 80)
for i, (doc, distance) in enumerate(search_results, 1):
print(f"[Result {i}] Vector Distance: {distance:.4f}")
## Truncate for readability
content_preview = doc.page_content[:150] + "..." if len(doc.page_content) > 150 else doc.page_content
print(f"Text: {content_preview}")
print("-" * 80)
except Exception as e:
raise RuntimeError(f"Error performing semantic search: {str(e)}")
================================================================================
PHASE 1: BASELINE PERFORMANCE (Without Hyperscale or Composite Vector Index)
================================================================================
2026-02-02 12:17:21,919 - INFO - HTTP Request: POST https://api.mistral.ai/v1/embeddings "HTTP/1.1 200 OK"
2026-02-02 12:17:22,607 - INFO - Baseline search completed in 0.98 seconds
Baseline Search Results (completed in 0.9779 seconds):
--------------------------------------------------------------------------------
[Result 1] Vector Distance: 0.2870
Text: Couchbase Server is a multipurpose, distributed database that fuses the strengths of relational databases such as SQL and ACID transactions with JSON'...
--------------------------------------------------------------------------------
[Result 2] Vector Distance: 0.3484
Text: It's used across industries for things like user profiles, dynamic product catalogs, GenAI apps, vector search, high-speed caching, and much more.
--------------------------------------------------------------------------------
[Result 3] Vector Distance: 0.3865
Text: Couchbase is commonly used to store and search embeddings for GenAI and retrieval augmented generation applications.
--------------------------------------------------------------------------------
Phase 2: Hyperscale Vector Index-Optimized Performance
Now let’s create a Hyperscale index and measure the performance improvements when searching.
## Create a Hyperscale index for optimal vector search performance
print("nCreating Hyperscale index for index optimization...")
vector_store.create_index(
index_type=IndexType.BHIVE,
index_name="mistral_hyperscale_index_optimized",
index_description="IVF,SQ8"
)
print("Hyperscale index created successfully!")
Creating Hyperscale index for index optimization...
2026-02-02 12:18:39,480 - INFO - HTTP Request: POST https://api.mistral.ai/v1/embeddings "HTTP/1.1 200 OK"
Hyperscale index created successfully!
## Phase 2: Hyperscale Index-Optimized Performance
print("n" + "="*80)
print("PHASE 2: Hyperscale Index-OPTIMIZED PERFORMANCE ")
print("="*80)
query = "name a multipurpose database with distributed capability"
try:
# Perform the semantic search with Hyperscale Vector Index
start_time = time.time()
search_results = vector_store.similarity_search_with_score(query, k=3)
hyperscale_time = time.time() - start_time
logging.info(f"Hyperscale Vector index-optimized search completed in {hyperscale_time:.2f} seconds")
# Display search results
print(f"nHyperscale Vector index-Optimized Search Results (completed in {hyperscale_time:.4f} seconds):")
print("-" * 80)
for i, (doc, distance) in enumerate(search_results, 1):
print(f"[Result {i}] Vector Distance: {distance:.4f}")
# Truncate for readability
content_preview = doc.page_content[:150] + "..." if len(doc.page_content) > 150 else doc.page_content
print(f"Text: {content_preview}")
print("-" * 80)
except Exception as e:
raise RuntimeError(f"Error performing semantic search: {str(e)}")
================================================================================
PHASE 2: Hyperscale Index-OPTIMIZED PERFORMANCE
================================================================================
2026-02-02 12:18:45,737 - INFO - HTTP Request: POST https://api.mistral.ai/v1/embeddings "HTTP/1.1 200 OK"
2026-02-02 12:18:46,873 - INFO - Hyperscale Vector index-optimized search completed in 1.51 seconds
Hyperscale Vector index-Optimized Search Results (completed in 1.5112 seconds):
--------------------------------------------------------------------------------
[Result 1] Vector Distance: 0.2870
Text: Couchbase Server is a multipurpose, distributed database that fuses the strengths of relational databases such as SQL and ACID transactions with JSON'...
--------------------------------------------------------------------------------
[Result 2] Vector Distance: 0.3484
Text: It's used across industries for things like user profiles, dynamic product catalogs, GenAI apps, vector search, high-speed caching, and much more.
--------------------------------------------------------------------------------
[Result 3] Vector Distance: 0.3865
Text: Couchbase is commonly used to store and search embeddings for GenAI and retrieval augmented generation applications.
--------------------------------------------------------------------------------
Performance Summary
Let’s analyze the performance improvements achieved through Hyperscale Vector Index optimization.
print("n" + "="*80)
print("VECTOR SEARCH PERFORMANCE OPTIMIZATION SUMMARY")
print("="*80)
print(f"n📊 Performance Comparison:")
print(f"{'Optimization Level':<35} {'Time (seconds)':<20} {'Status'}")
print("-" * 80)
print(f"{'Phase 1 - Baseline (No Index)':<35} {baseline_time:.4f}{'':16} ⚪ Baseline")
print(f"{'Phase 2 - Hyperscale & Composite Vector Index-Optimized (Hyperscale)':<35} {hyperscale_time:.4f}{'':16} ✅ Optimized")
# Calculate improvement
if baseline_time > hyperscale_time:
speedup = baseline_time / hyperscale_time
improvement = ((baseline_time - hyperscale_time) / baseline_time) * 100
print(f"n✨ Index Performance Gain: {speedup:.2f}x faster ({improvement:.1f}% improvement)")
elif hyperscale_time > baseline_time:
slowdown_pct = ((hyperscale_time - baseline_time) / baseline_time) * 100
print(f"n⚠️ Note: Hyperscale Vector Index was {slowdown_pct:.1f}% slower than baseline in this run")
print(f" This can happen with small datasets. Hyperscale Vector Index benefits emerge with scale.")
else:
print(f"n⚖️ Performance: Comparable to baseline")
print("n" + "-"*80)
print("KEY INSIGHTS:")
print("-"*80)
print("1. 🚀 Hyperscale & Composite Vector Index Optimization:")
print(" • Hyperscale vector indexes excel with large-scale datasets (millions+ vectors)")
print(" • Performance gains increase with dataset size and concurrent queries")
print(" • Optimal for production workloads with sustained traffic patterns")
print("n2. 📦 Dataset Size Impact:")
print(f" • Current dataset: ~3 sample documents")
print(" • At this scale, performance differences may be minimal or variable")
print(" • Significant gains typically seen with 10M+ vectors")
print("n3. 🎯 When to Use Hyperscale & Composite Vector Index:")
print(" • Large-scale vector search applications")
print(" • High query-per-second (QPS) requirements")
print(" • Multi-user concurrent access scenarios")
print(" • Production environments requiring scalability")
print("n" + "="*80)
================================================================================
VECTOR SEARCH PERFORMANCE OPTIMIZATION SUMMARY
================================================================================
📊 Performance Comparison:
Optimization Level Time (seconds) Status
--------------------------------------------------------------------------------
Phase 1 - Baseline (No Index) 0.9779 ⚪ Baseline
Phase 2 - Hyperscale & Composite Vector Index-Optimized (Hyperscale) 1.5112 ✅ Optimized
⚠️ Note: Hyperscale Vector Index was 54.5% slower than baseline in this run
This can happen with small datasets. Hyperscale Vector Index benefits emerge with scale.
--------------------------------------------------------------------------------
KEY INSIGHTS:
--------------------------------------------------------------------------------
1. 🚀 Hyperscale & Composite Vector Index Optimization:
• Hyperscale vector indexes excel with large-scale datasets (millions+ vectors)
• Performance gains increase with dataset size and concurrent queries
• Optimal for production workloads with sustained traffic patterns
2. 📦 Dataset Size Impact:
• Current dataset: ~3 sample documents
• At this scale, performance differences may be minimal or variable
• Significant gains typically seen with 10M+ vectors
3. 🎯 When to Use Hyperscale & Composite Vector Index:
• Large-scale vector search applications
• High query-per-second (QPS) requirements
• Multi-user concurrent access scenarios
• Production environments requiring scalability
================================================================================
結論
This tutorial demonstrated how to use Mistral AI’s embedding capabilities with Couchbase’s Hyperscale and Composite Vector search, including comprehensive performance analysis. The combination of Mistral AI’s embeddings and Couchbase’s Hyperscale and Composite Vector Index provides a powerful, scalable foundation for building intelligent search applications.