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をデプロイ
前提条件
お使いの環境が以下の要件を満たしていることを確認してください:
- OS: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もインストールされるため、直接接続してデータベースの作成などの操作を実行できます。
ステップ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をデプロイ
前提条件
お使いの環境が以下の要件を満たしていることを確認してください:
- OS:Linux、macOS (Apple Silicon)
- Node.jsバージョン:Node.js 20以降
- システムアーキテクチャ:x86_64、aarch64
インストール
npmを使用してインストールします。
npm install seekdb @seekdb/default-embed
seekdb-jsのインストールと同時に、埋め込みモードの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以外にも、SQLを使用してseekdbを操作できます。SQLの使用方法については、SQLを使用したベクトル検索のクイック体験およびSQLを使用したハイブリッド検索のクイック体験を参照してください。