SDKを使用したハイブリッド検索のクイック体験
この例では、Linux環境を例に、pyseekdb(OceanBaseが提供するPythonクライアント)またはseekdb-js(OceanBaseが提供するNode.jsクライアント)の組み込みseekdbを使用して、ハイブリッド検索をクイックに体験する方法を説明します。
Linuxシステム以外にも、macOSおよびWindowsシステムでpyseekdbを使用できます。ただし、現在のところWindowsシステムではサーバーモードのseekdbのみがサポートされています。macOSおよびWindowsシステムでの使用方法については、pyseekdb クイックスタートおよびseekdb-js クイックスタートを参照してください。
この例では、以下の操作を行います:
- pyseekdb/seekdb-jsと組み込みseekdbをデプロイします。
- seekdbに接続し、データベースを作成します。
- データベースに接続し、Embedding Functionsを持つcollectionを作成します。
- documentsを使用してデータを追加します(ベクトルは自動生成されます)。
- ハイブリッド検索を実行します(ベクトルは自動生成されます)し、クエリ結果を出力します。
- 環境をクリーンアップします。
背景
pyseekdb
pyseekdbはOceanBaseが提供するPythonクライアントです。一連のAPIを基盤として実装されており、3種類のデータベース接続モードを提供し、組み込みモードのseekdb、サーバーモードのseekdb、およびOceanBaseデータベースへの接続をサポートしています。
このクライアントをインストールすると、組み込みモードのseekdbも同時にインストールされるため、組み込みseekdbに直接接続してデータベースの作成などの操作を実行できます。または、既にデプロイ済みのサーバーモードのseekdbまたはOceanBaseデータベースにリモート接続することもできます。
seekdb-js
seekdb-jsはOceanBaseが提供するNode.jsクライアントです。一連のAPIを基盤として実装されており、3種類のデータベース接続モードを提供し、組み込みモードのseekdb、サーバーモードのseekdb、およびOceanBaseデータベースへの接続をサポートしています。
このクライアントをインストールすると、組み込みモードのseekdbも同時にインストールされるため、組み込みseekdbに直接接続してデータベースの作成などの操作を実行できます。または、既にデプロイ済みのサーバーモードのseekdbまたはOceanBaseデータベースにリモート接続することもできます。
seekdbデプロイメントモード
seekdbは、クイックプロトタイプ開発から大量ユーザーのサポートまで、さまざまなニーズに対応する柔軟なデプロイメントモードを提供しています。
-
埋め込みモード
seekdbは軽量ライブラリとしてアプリケーションに埋め込まれ、ワンクリックでインストールできます。個人学習やクイックプロトタイプ開発に適しており、多様なエンドデバイス上で効率的に動作します。
-
サーバーモード
テスト環境および本番環境でのデプロイメントに推奨されるモードです。軽量で使いやすく、安定した高効率なサービス提供に最適です。
サーバーモードの使用方法については、SQLを通じてサーバーモードのseekdbを試すを参照してください。
- pyseekdb
- seekdb-js
ステップ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に接続し、hybrid_search_testという名前のデータベースを作成します。
-
Admin Clientの詳細については、Admin Clientを参照してください。
-
データベース作成の詳細については、create_database - データベースの作成を参照してください。
import pyseekdb
# Create embedded admin client
admin = pyseekdb.AdminClient(path="./seekdb.db")
# Create database
admin.create_database("hybrid_search_test")
ステップ3:データベースに接続し、Embedding Functionsを持つcollectionを作成
Clientを使用してhybrid_search_testデータベースに接続し、collectionを作成します。
- Clientの詳細については、Clientを参照してください。
- collectionの作成に関する詳細は、create_collection - Collectionの作成を参照してください。
import pyseekdb
# Create embedded client
client = pyseekdb.Client(path="./seekdb.db", database="hybrid_search_test")
# Create collection
collection = client.create_collection(
name="hybrid_search_demo"
)
ステップ4:データを挿入
addメソッドを使用して、collectionにデータを挿入します。
データ挿入の詳細については、add - データの挿入を参照してください。
import pyseekdb
# Create embedded client
client = pyseekdb.Client(path="./seekdb.db", database="hybrid_search_test")
# get collection
collection = client.get_collection("hybrid_search_demo")
# Define documents
documents = [
"Machine learning is revolutionizing artificial intelligence and data science",
"Python programming language is essential for machine learning developers",
"Deep learning neural networks enable advanced AI applications",
"Data science combines statistics, programming, and domain expertise",
"Natural language processing uses machine learning to understand text",
"Computer vision algorithms process images using deep learning techniques",
"Reinforcement learning trains agents through reward-based feedback",
"Python libraries like TensorFlow and PyTorch simplify machine learning",
"Artificial intelligence systems can learn from large datasets",
"Neural networks mimic the structure of biological brain connections"
]
# Define metadatas
metadatas = [
{"category": "AI", "topic": "machine learning", "year": 2023, "popularity": 95},
{"category": "Programming", "topic": "python", "year": 2023, "popularity": 88},
{"category": "AI", "topic": "deep learning", "year": 2024, "popularity": 92},
{"category": "Data Science", "topic": "data analysis", "year": 2023, "popularity": 85},
{"category": "AI", "topic": "nlp", "year": 2024, "popularity": 90},
{"category": "AI", "topic": "computer vision", "year": 2023, "popularity": 87},
{"category": "AI", "topic": "reinforcement learning", "year": 2024, "popularity": 89},
{"category": "Programming", "topic": "python", "year": 2023, "popularity": 91},
{"category": "AI", "topic": "general ai", "year": 2023, "popularity": 93},
{"category": "AI", "topic": "neural networks", "year": 2024, "popularity": 94}
]
ids = [f"doc_{i+1}" for i in range(len(documents))]
# Insert data
collection.add(ids=ids, documents=documents, metadatas=metadatas)
ステップ5:ハイブリッド検索を実行し、クエリ結果を出力
hybrid_searchメソッドを使用してハイブリッド検索を実行し、クエリ結果を出力します。
ハイブリッド検索の詳細については、hybrid_search - ハイブリッド検索を参照してください。
import pyseekdb
# Create embedded client
client = pyseekdb.Client(path="./seekdb.db", database="hybrid_search_test")
# get collection
collection = client.get_collection("hybrid_search_demo")
# Perform hybrid search
hybrid_result = collection.hybrid_search(
query={"where_document": {"$contains": "machine learning"}, "n_results": 10},
knn={"query_texts": ["AI research"], "n_results": 10},
rank={"rrf": {}},
n_results=5
)
# Print results
print("\nhybrid_search() Results:")
print(f" ids: {hybrid_result ['ids'][0]}")
print(f" Document: {hybrid_result ['documents'][0]}")
ステップ6:環境をクリーンアップ
上記のサンプルデータベースとcollectionが不要になった場合は、delete_collectionメソッドでcollectionを削除し、delete_databaseメソッドでデータベースを削除できます。
-
collectionの削除に関する詳細は、delete_collection - Collectionの削除を参照してください。
-
データベースの削除に関する詳細は、delete_database - データベースの削除を参照してください。
import pyseekdb
# Create embedded client
admin = pyseekdb.AdminClient(path="./seekdb.db")
client = pyseekdb.Client(path="./seekdb.db", database="hybrid_search_test")
# Delete collection
client.delete_collection("hybrid_search_demo")
print(f"\nDeleted collection")
# Delete database
admin.delete_database("hybrid_search_test")
print(f"\nDeleted database")
全体の例
import pyseekdb
#==================== Create Database ====================
# Create embedded admin client
admin = pyseekdb.AdminClient(path="./seekdb.db")
# Create database
admin.create_database("hybrid_search_test")
# ==================== Create Collection ====================
# Create embedded client
client = pyseekdb.Client(path="./seekdb.db", database="hybrid_search_test")
# Create collection
collection = client.create_collection(
name="hybrid_search_demo"
)
# ==================== Add Data to Collection ====================
# Define documents
documents = [
"Machine learning is revolutionizing artificial intelligence and data science",
"Python programming language is essential for machine learning developers",
"Deep learning neural networks enable advanced AI applications",
"Data science combines statistics, programming, and domain expertise",
"Natural language processing uses machine learning to understand text",
"Computer vision algorithms process images using deep learning techniques",
"Reinforcement learning trains agents through reward-based feedback",
"Python libraries like TensorFlow and PyTorch simplify machine learning",
"Artificial intelligence systems can learn from large datasets",
"Neural networks mimic the structure of biological brain connections"
]
# Define metadatas
metadatas = [
{"category": "AI", "topic": "machine learning", "year": 2023, "popularity": 95},
{"category": "Programming", "topic": "python", "year": 2023, "popularity": 88},
{"category": "AI", "topic": "deep learning", "year": 2024, "popularity": 92},
{"category": "Data Science", "topic": "data analysis", "year": 2023, "popularity": 85},
{"category": "AI", "topic": "nlp", "year": 2024, "popularity": 90},
{"category": "AI", "topic": "computer vision", "year": 2023, "popularity": 87},
{"category": "AI", "topic": "reinforcement learning", "year": 2024, "popularity": 89},
{"category": "Programming", "topic": "python", "year": 2023, "popularity": 91},
{"category": "AI", "topic": "general ai", "year": 2023, "popularity": 93},
{"category": "AI", "topic": "neural networks", "year": 2024, "popularity": 94}
]
ids = [f"doc_{i+1}" for i in range(len(documents))]
# Insert data
collection.add(ids=ids, documents=documents, metadatas=metadatas)
# ==================== Perform Hybrid Search ====================
# Perform hybrid search
hybrid_result = collection.hybrid_search(
query={"where_document": {"$contains": "machine learning"}, "n_results": 10},
knn={"query_texts": ["AI research"], "n_results": 10},
rank={"rrf": {}},
n_results=5
)
# ==================== Print Query Results ====================
# Print results
print("\nhybrid_search() Results:")
print(f" ids: {hybrid_result ['ids'][0]}")
print(f" Document: {hybrid_result ['documents'][0]}")
# ==================== Cleanup ====================
# Delete collection
client.delete_collection("hybrid_search_demo")
print(f"\nDeleted collection")
# Delete database
admin.delete_database("hybrid_search_test")
print(f"\nDeleted database")
ステップ1:seekdb-jsをインストールし、埋め込みモードのseekdbをデプロイ
前提条件
お使いの環境が以下の要件を満たしていることを確認してください:
- オペレーティングシステム:Linux、macOS (Apple Silicon)
- Node.jsバージョン:Node.js 20以降
- システムアーキテクチャ:x86_64, aarch64
インストール
npmを使用してインストールします。
npm install seekdb @seekdb/default-embed
seekdb-jsのインストールと同時に、埋め込みモードのseekdbもインストールされます。これにより、埋め込みモードのseekdbに直接接続してデータベースの作成などの操作を実行できます。
ステップ2:seekdbに接続し、データベースを作成
SeekdbAdminClientを使用してseekdbに接続し、hybrid_search_testという名前のデータベースを作成します。
-
SeekdbAdminClientの詳細については、SeekdbAdminClientを参照してください。
-
データベース作成の詳細については、createDatabase - データベースの作成を参照してください。
import { SeekdbAdminClient } from "seekdb";
// Create embedded admin client
const admin = new SeekdbAdminClient({ path: "./seekdb.db" });
// Create database
await admin.createDatabase("hybrid_search_test");
ステップ3:データベースに接続し、Embedding Functionsを持つcollectionを作成
SeekdbClientを使用してhybrid_search_testデータベースに接続し、collectionを作成します。
- SeekdbClientの詳細については、SeekdbClientを参照してください。
- collectionの作成に関する詳細は、createCollection - Collectionの作成を参照してください。
import { SeekdbClient } from "seekdb";
// Create embedded client
const client = new SeekdbClient({
path: "./seekdb.db",
database: "hybrid_search_test",
});
// Create collection
const collection = await client.createCollection({ name: "hybrid_search_demo" });
ステップ4:データを挿入
addメソッドを使用して、collectionにデータを挿入します。
データ挿入の詳細については、add - データの挿入を参照してください。
import { SeekdbClient } from "seekdb";
// Create embedded client
const client = new SeekdbClient({
path: "./seekdb.db",
database: "hybrid_search_test",
});
// get collection
const collection = await client.getCollection({
name: 'hybrid_search_demo'
});
// Define documents
const documents = [
"Machine learning is revolutionizing artificial intelligence and data science",
"Python programming language is essential for machine learning developers",
"Deep learning neural networks enable advanced AI applications",
"Data science combines statistics, programming, and domain expertise",
"Natural language processing uses machine learning to understand text",
"Computer vision algorithms process images using deep learning techniques",
"Reinforcement learning trains agents through reward-based feedback",
"Python libraries like TensorFlow and PyTorch simplify machine learning",
"Artificial intelligence systems can learn from large datasets",
"Neural networks mimic the structure of biological brain connections",
];
// Define metadatas
const metadatas = [
{ category: "AI", topic: "machine learning", year: 2023, popularity: 95 },
{ category: "Programming", topic: "python", year: 2023, popularity: 88 },
{ category: "AI", topic: "deep learning", year: 2024, popularity: 92 },
{
category: "Data Science",
topic: "data analysis",
year: 2023,
popularity: 85,
},
{ category: "AI", topic: "nlp", year: 2024, popularity: 90 },
{ category: "AI", topic: "computer vision", year: 2023, popularity: 87 },
{
category: "AI",
topic: "reinforcement learning",
year: 2024,
popularity: 89,
},
{ category: "Programming", topic: "python", year: 2023, popularity: 91 },
{ category: "AI", topic: "general ai", year: 2023, popularity: 93 },
{ category: "AI", topic: "neural networks", year: 2024, popularity: 94 },
];
const ids = documents.map((_, i) => `doc_${i + 1}`);
// Insert data
await collection.add({ ids, documents, metadatas });
ステップ5:ハイブリッド検索を実行し、クエリ結果を出力
hybridSearchメソッドを使用してハイブリッド検索を実行し、クエリ結果を出力します。
ベクトル検索の詳細については、hybridSearch - ハイブリッド検索を参照してください。
import { SeekdbClient } from "seekdb";
// Create embedded client
const client = new SeekdbClient({
path: "./seekdb.db",
database: "hybrid_search_test",
});
// get collection
const collection = await client.getCollection({
name: 'hybrid_search_demo'
});
// Perform hybrid search
const hybridResult1 = await collection.hybridSearch({
query: { whereDocument: { $contains: "machine learning" }, nResults: 10 },
knn: { queryTexts: ["AI research"], nResults: 10 },
rank: { rrf: {} },
nResults: 5,
});
// Print results
console.log("\nhybridSearch() Results:");
for (let i = 0; i < hybridResult1.ids[0].length; i++) {
const docId = hybridResult1.ids[0][i];
const idx = ids.indexOf(docId);
console.log(` ${i + 1}. ${documents[idx]}`);
}
ステップ6:環境をクリーンアップ
上記のサンプルデータベースとcollectionが不要になった場合は、deleteCollectionメソッドでcollectionを削除し、deleteDatabaseメソッドでデータベースを削除できます。
-
collectionの削除に関する詳細は、deleteCollection - Collectionの削除を参照してください。
-
データベースの削除に関する詳細は、deleteDatabase - データベースの削除を参照してください。
import { SeekdbAdminClient } from "seekdb";
import { SeekdbClient } from "seekdb";
// Create embedded client
const admin = new SeekdbAdminClient({ path: "./seekdb.db" });
const client = new SeekdbClient({
path: "./seekdb.db",
database: "hybrid_search_test",
});
// Delete collection
await client.deleteCollection('hybrid_search_demo');
console.log('\nDeleted collection')
// Delete database
await admin.deleteDatabase("hybrid_search_test");
console.log('\nDeleted database')
全体の例
import { SeekdbAdminClient } from "seekdb";
import { SeekdbClient } from "seekdb";
//==================== Create Database ====================
// Create embedded admin client
const admin = new SeekdbAdminClient({ path: "./seekdb.db" });
// Create database
await admin.createDatabase("hybrid_search_test");
// ==================== Create Collection ====================
// Create embedded client
const client = new SeekdbClient({
path: "./seekdb.db",
database: "hybrid_search_test",
});
// Create collection
const collection = await client.createCollection({ name: "hybrid_search_demo" });
// ==================== Add Data to Collection ====================
// Define documents
const documents = [
"Machine learning is revolutionizing artificial intelligence and data science",
"Python programming language is essential for machine learning developers",
"Deep learning neural networks enable advanced AI applications",
"Data science combines statistics, programming, and domain expertise",
"Natural language processing uses machine learning to understand text",
"Computer vision algorithms process images using deep learning techniques",
"Reinforcement learning trains agents through reward-based feedback",
"Python libraries like TensorFlow and PyTorch simplify machine learning",
"Artificial intelligence systems can learn from large datasets",
"Neural networks mimic the structure of biological brain connections",
];
// Define metadatas
const metadatas = [
{ category: "AI", topic: "machine learning", year: 2023, popularity: 95 },
{ category: "Programming", topic: "python", year: 2023, popularity: 88 },
{ category: "AI", topic: "deep learning", year: 2024, popularity: 92 },
{
category: "Data Science",
topic: "data analysis",
year: 2023,
popularity: 85,
},
{ category: "AI", topic: "nlp", year: 2024, popularity: 90 },
{ category: "AI", topic: "computer vision", year: 2023, popularity: 87 },
{
category: "AI",
topic: "reinforcement learning",
year: 2024,
popularity: 89,
},
{ category: "Programming", topic: "python", year: 2023, popularity: 91 },
{ category: "AI", topic: "general ai", year: 2023, popularity: 93 },
{ category: "AI", topic: "neural networks", year: 2024, popularity: 94 },
];
const ids = documents.map((_, i) => `doc_${i + 1}`);
// Insert data
await collection.add({ ids, documents, metadatas });
// ==================== Perform Hybrid Search ====================
// Perform hybrid search
const hybridResult1 = await collection.hybridSearch({
query: { whereDocument: { $contains: "machine learning" }, nResults: 10 },
knn: { queryTexts: ["AI research"], nResults: 10 },
rank: { rrf: {} },
nResults: 5,
});
// ==================== Print Query Results ====================
// Print results
console.log("\nhybridSearch() Results:");
for (let i = 0; i < hybridResult1.ids[0].length; i++) {
const docId = hybridResult1.ids[0][i];
const idx = ids.indexOf(docId);
console.log(` ${i + 1}. ${documents[idx]}`);
}
// ==================== Cleanup ====================
// Delete collection
await client.deleteCollection('hybrid_search_demo');
console.log('\nDeleted collection')
// Delete database
await admin.deleteDatabase("hybrid_search_test");
console.log('\nDeleted database')
詳細を見る
-
pyseekdbの詳細な紹介と使用方法については、pyseekdbを参照してください。
-
pyseekdbの使用例については、以下を参照してください:
-
Simple サンプル:pyseekdbのベクトル検索機能を示すサンプルです。
-
Complete サンプル:現在のpyseekdbがサポートする全機能を示すサンプルです。
-
ハイブリッド検索のサンプル:seekdbのハイブリッド検索の使用方法を示し、ベクトル検索の機能と比較します。
-
seekdb-jsの使用例については、以下を参照してください:
-
Simple サンプル:seekdb-jsのベクトル検索機能を示すサンプルです。
-
Complete サンプル:現在のseekdb-jsがサポートする全機能を示すサンプルです。
-
ハイブリッド検索のサンプル:seekdbのハイブリッド検索の使用方法を示し、ベクトル検索の機能と比較します。
-
Python SDKおよびseekdb-js SDKに加えて、seekdbはSQLを使用した操作もサポートしています。SQLの使用方法については、SQLを利用したベクトル検索のクイックスタートおよびSQLを利用したハイブリッド検索のクイックスタートを参照してください。