SDKを使用したベクトル検索のクイックスタート
この例では、Linux環境を例に、OceanBaseが提供するPythonクライアントであるpyseekdbの組み込みseekdbを使用して、ベクトル検索を簡単に体験する方法を説明します。
Linuxシステム以外にも、macOSおよびWindowsシステムでpyseekdbを使用することができます。ただし、現在のところWindowsシステムではサーバーモードのseekdbのみがサポートされています。macOSおよびWindowsシステムでの使用方法については、pyseekdb クイックスタートを参照してください。
この例では、以下の操作を実行します:
- pyseekdbと組み込みseekdbをデプロイします。
- seekdbに接続し、データベースを作成します。
- データベースに接続し、Embedding Functionsを持つcollectionを作成します。
- documentsを使用してデータを追加します(ベクトルは自動生成されます)。
- ベクトル検索を実行します(ベクトルは自動生成されます)し、クエリ結果を出力します。
- 環境をクリーンアップします。
背景
pyseekdb
pyseekdbは、OceanBaseが提供するPythonクライアントです。単一のAPIセットに基づき、3種類のデータベース接続モードを実装しており、組み込みモードのseekdb、サーバーモードのseekdb、およびOceanBaseデータベースへの接続をサポートしています。
このクライアントをインストールすると、組み込みモードのseekdbも同時にインストールされるため、組み込みseekdbに直接接続してデータベースの作成などの操作を実行できます。または、既にデプロイ済みのサーバーモードのseekdbまたはOceanBaseデータベースにリモート接続することも選択できます。
seekdbのデプロイメントモード
seekdbは、迅速なプロトタイプ開発から大量ユーザーのサポートまで、あらゆるアプリケーションニーズに対応する、多様で柔軟なデプロイメントモードを提供しています。
-
組み込みモード
seekdbは軽量ライブラリとしてアプリケーションに組み込まれ、pipワンクリックでのインストールをサポートします。個人学習や迅速なプロトタイプ開発に適しており、さまざまなエンドデバイス上で効率的に動作します。
-
サーバーモード
テスト環境および本番環境でのデプロイメントモードとして推奨されており、軽量で使いやすく、安定した高効率なサービス提供に適しています。
サーバーモードの使用方法については、SQLを通じてサーバーモードのseekdbを体験するを参照してください。
ステップ1:pyseekdbをインストールし、組み込みseekdbをデプロイ
前提条件
環境が以下の要件を満たしていることを確認してください:
- オペレーティングシステム:Linux (glibc >= 2.28)
- Pythonバージョン:Python 3.11以降
- システムアーキテクチャ:x86_64, aarch64
インストール
pipを使用してインストールすると、デフォルトのPythonバージョンとプラットフォームが自動的に検出されます。
pip install -U pyseekdb
pipのバージョンが古い場合は、インストール前にpipをアップグレードしてください。
pip install --upgrade pip
pyseekdbをインストールすると同時に、組み込みモードのseekdbもインストールされるため、組み込みseekdbに直接接続してデータベースの作成などの操作を実行できます。
ステップ2:seekdbに接続し、データベースを作成
Admin Clientを使用してseekdbに接続し、query_testという名前のデータベースを作成します。
-
Admin Clientの詳細については、Admin Clientを参照してください。
-
データベース作成の詳細については、create_database - データベースの作成を参照してください。
import pyseekdb
# Create embedded admin client
admin = pyseekdb.AdminClient(path="./seekdb.db")
# Create database
admin.create_database("query_test")
ステップ3:データベースに接続し、Embedding Functionsを持つcollectionを作成する
Client を使用して query_test データベースに接続し、collectionを作成します。
- Clientの詳細については、Clientを参照してください。
- collectionの作成方法の詳細については、create_collection - Collectionの作成を参照してください。
import pyseekdb
# Create embedded client
client = pyseekdb.Client(path="./seekdb.db", database="query_test")
# Create collection
collection = client.create_collection(
name="query_demo"
)
ステップ4:データを挿入する
add メソッドを使用して、collectionにデータを挿入します。
データの挿入方法の詳細については、add - データの挿入を参照してください。
import pyseekdb
# Create embedded client
client = pyseekdb.Client(path="./seekdb.db", database="query_test")
# get collection
collection = client.get_collection("query_demo")
# Define documents
documents = [
"Machine learning is a subset of artificial intelligence",
"Python is a popular programming language",
"Vector databases enable semantic search",
"Neural networks are inspired by the human brain",
"Natural language processing helps computers understand text"
]
ids = ["id1", "id2", "id3", "id4", "id5"]
# Add data with documents only - embeddings will be auto-generated by embedding function
collection.add(
ids=ids,
documents=documents, # embeddings will be automatically generated
metadatas=[
{"category": "AI", "index": 0},
{"category": "Programming", "index": 1},
{"category": "Database", "index": 2},
{"category": "AI", "index": 3},
{"category": "NLP", "index": 4}
]
)
ステップ5:ベクトル検索を実行し、クエリ結果を出力する
query メソッドを使用してベクトル検索クエリを実行し、クエリ結果を出力します。
ベクトル検索の詳細については、query - ベクトル検索を参照してください。
import pyseekdb
# Create embedded client
client = pyseekdb.Client(path="./seekdb.db", database="query_test")
# get collection
collection = client.get_collection("query_demo")
# Perform query
query_text = "artificial intelligence and machine learning"
results = collection.query(
query_texts=query_text, # Query text - will be embedded automatically
n_results=3 # Return top 3 most similar documents
)
print(f"\nQuery: '{query_text}'")
print(f"Query results: {len(results['ids'][0])} items found")
for i in range(len(results['ids'][0])):
print(f"\nResult {i+1}:")
print(f" ID: {results['ids'][0][i]}")
print(f" Distance: {results['distances'][0][i]:.4f}")
if results.get('documents'):
print(f" Document: {results['documents'][0][i]}")
if results.get('metadatas'):
print(f" Metadata: {results['metadatas'][0][i]}")
ステップ6:環境をクリーンアップ
上記のサンプルデータベースとコレクションが不要になった場合は、delete_collection メソッドでコレクションを削除し、delete_database メソッドでデータベースを削除できます。
-
コレクションの削除に関する詳細は、delete_collection - コレクションの削除を参照してください。
-
データベースの削除に関する詳細は、delete_database - データベースの削除を参照してください。
import pyseekdb
# Create embedded client
admin = pyseekdb.AdminClient(path="./seekdb.db")
client = pyseekdb.Client(path="./seekdb.db", database="query_test")
# Delete collection
client.delete_collection("query_demo")
print(f"\nDeleted collection")
# Delete database
admin.delete_database("query_test")
print(f"\nDeleted database")
全体例
import pyseekdb
#==================== Create Database ====================
# Create embedded admin client
admin = pyseekdb.AdminClient(path="./seekdb.db")
# Create database
admin.create_database("query_test")
# ==================== Create Collection ====================
# Create embedded client
client = pyseekdb.Client(path="./seekdb.db", database="query_test")
# Create collection
collection = client.create_collection(
name="query_demo"
)
# ==================== Add Data to Collection ====================
# Define documents
documents = [
"Machine learning is a subset of artificial intelligence",
"Python is a popular programming language",
"Vector databases enable semantic search",
"Neural networks are inspired by the human brain",
"Natural language processing helps computers understand text"
]
ids = ["id1", "id2", "id3", "id4", "id5"]
# Add data with documents only - embeddings will be auto-generated by embedding function
collection.add(
ids=ids,
documents=documents, # embeddings will be automatically generated
metadatas=[
{"category": "AI", "index": 0},
{"category": "Programming", "index": 1},
{"category": "Database", "index": 2},
{"category": "AI", "index": 3},
{"category": "NLP", "index": 4}
]
)
# ==================== Perform Query ====================
# Perform Query
query_text = "artificial intelligence and machine learning"
results = collection.query(
query_texts=query_text, # Query text - will be embedded automatically
n_results=3 # Return top 3 most similar documents
)
print(f"\nQuery: '{query_text}'")
print(f"Query results: {len(results['ids'][0])} items found")
for i in range(len(results['ids'][0])):
print(f"\nResult {i+1}:")
print(f" ID: {results['ids'][0][i]}")
print(f" Distance: {results['distances'][0][i]:.4f}")
if results.get('documents'):
print(f" Document: {results['documents'][0][i]}")
if results.get('metadatas'):
print(f" Metadata: {results['metadatas'][0][i]}")
# ==================== Cleanup ====================
# Delete collection
client.delete_collection("query_demo")
print(f"\nDeleted collection")
# Delete database
admin.delete_database("query_test")
print(f"\nDeleted database")
詳細を見る
-
pyseekdbの詳細な紹介と使用方法については、pyseekdbを参照してください。
-
pyseekdbの使用例については、以下を参照してください:
-
Simpleインデックスの例:pyseekdbのベクトル検索機能を示す例です。
-
Completeインデックスの例:現在のpyseekdbがサポートする全機能を示す例です。
-
ハイブリッド検索の例:seekdbのハイブリッド検索の使用方法を示し、ベクトル検索機能と比較します。
-
Python SDK以外にも、seekdbはSQLを使用した操作をサポートしています。SQLの使用方法については、SQLを使用したベクトル検索のクイックスタートおよびSQLを使用したハイブリッド検索のクイックスタートを参照してください。