SDKを使用したベクトル検索のクイックスタート
この例では、Linux環境を例に、pyseekdb(OceanBaseが提供するPythonクライアント)またはseekdb-js(OceanBaseが提供するNode.jsクライアント)の組み込みseekdbを使用して、ベクトル検索を手軽に試す方法を説明します。
Linuxシステム以外にも、macOSおよびWindowsシステムでpyseekdbとseekdb-jsの使用をサポートしています。ただし、現在Windowsシステムではサーバーモードのseekdbのみがサポートされています。macOSおよびWindowsシステムでの使用方法については、pyseekdb クイックスタートおよびseekdb-js クイックスタートを参照してください。
この例では、以下の操作を実行します:
- pyseekdb / seekdb-jsと組み込みseekdbをデプロイします。
- seekdbに接続し、データベースを作成します。
- データベースに接続し、Embedding Functionsを含むcollectionを作成します。
- documentsを使用してデータを追加します(vectorsは自動生成されます)。
- ベクトル検索を実行します(vectorsは自動生成されます)およびクエリ結果を出力します。
- 環境をクリーンアップします。
背景
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もインストールされます。これにより、埋め込み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:環境をクリーンアップ
上記のサンプルデータベースと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="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")
ステップ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もインストールされます。これにより、埋め込みseekdbに直接接続してデータベースの作成などの操作を実行できます。
ステップ2:seekdbに接続し、データベースを作成
SeekdbAdminClientを使用してseekdbに接続し、query_testという名前のデータベースを作成します。
-
SeekdbAdminClientの詳細については、SeekdbAdminClientを参照してください。
-
データベース作成の詳細については、createDatabase - データベースの作成を参照してください。
import { SeekdbAdminClient } from "seekdb";
// Create embedded admin client
const admin = new SeekdbAdminClient({ path: "./seekdb.db" });
// Create database
await admin.createDatabase("query_test");
ステップ3:データベースに接続し、Embedding Functionsを持つcollectionを作成
SeekdbClientを使用してquery_testデータベースに接続し、collectionを作成します。
- SeekdbClientの詳細については、SeekdbClientを参照してください。
- collection作成の詳細については、createCollection - Collectionの作成を参照してください。
import { SeekdbClient } from "seekdb";
// Create embedded client
const client = new SeekdbClient({
path: "./seekdb.db",
database: "query_test",
});
// Create collection
const collection = await client.createCollection({ name: "query_demo" });
ステップ4:データを挿入
addメソッドを使用してcollectionにデータを挿入します。
データ挿入の詳細については、add - データの挿入を参照してください。
import { SeekdbClient } from "seekdb";
// Create embedded client
const client = new SeekdbClient({
path: "./seekdb.db",
database: "query_test",
});
// get collection
const collection = await client.getCollection({
name: 'query_demo'
});
// Define documents
const 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",
];
const ids = ["id1", "id2", "id3", "id4", "id5"];
// Add data with documents only - embeddings will be auto-generated by embedding function
await collection.add({
ids,
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 { SeekdbClient } from "seekdb";
// Create embedded client
const client = new SeekdbClient({
path: "./seekdb.db",
database: "query_test",
});
// get collection
const collection = await client.getCollection({
name: 'query_demo'
});
// Perform query
const queryText = "artificial intelligence and machine learning";
const results = await collection.query({
queryTexts: queryText, // Query text - will be embedded automatically
nResults: 3, // Return top 3 most similar documents
include: ["documents", "metadatas", "distances"],
});
const hitCount = results.ids?.[0]?.length ?? 0;
console.log(`\nQuery: '${queryText}'`);
console.log(`Query results: ${hitCount} items found`);
for (let i = 0; i < hitCount; i++) {
console.log(`\nResult ${i + 1}:`);
console.log(` ID: ${results.ids?.[0]?.[i]}`);
console.log(` Distance: ${results.distances?.[0]?.[i]?.toFixed(4)}`);
console.log(` Document: ${results.documents?.[0]?.[i]}`);
console.log(` Metadata: ${JSON.stringify(results.metadatas?.[0]?.[i])}`);
}
ステップ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: "query_test",
});
// Delete collection
await client.deleteCollection('query_demo');
console.log('\nDeleted collection')
// Delete database
await admin.deleteDatabase("query_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("query_test");
// ==================== Create Collection ====================
// Create embedded client
const client = new SeekdbClient({
path: "./seekdb.db",
database: "query_test",
});
// Create collection
const collection = await client.createCollection({ name: "query_demo" });
// ==================== Add Data to Collection ====================
// Define documents
const 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",
];
const ids = ["id1", "id2", "id3", "id4", "id5"];
// Add data with documents only - embeddings will be auto-generated by embedding function
await collection.add({
ids,
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
const queryText = "artificial intelligence and machine learning";
const results = await collection.query({
queryTexts: queryText, // Query text - will be embedded automatically
nResults: 3, // Return top 3 most similar documents
include: ["documents", "metadatas", "distances"],
});
const hitCount = results.ids?.[0]?.length ?? 0;
console.log(`\nQuery: '${queryText}'`);
console.log(`Query results: ${hitCount} items found`);
for (let i = 0; i < hitCount; i++) {
console.log(`\nResult ${i + 1}:`);
console.log(` ID: ${results.ids?.[0]?.[i]}`);
console.log(` Distance: ${results.distances?.[0]?.[i]?.toFixed(4)}`);
console.log(` Document: ${results.documents?.[0]?.[i]}`);
console.log(` Metadata: ${JSON.stringify(results.metadatas?.[0]?.[i])}`);
}
// ==================== Cleanup ====================
// Delete collection
await client.deleteCollection('query_demo');
console.log('\nDeleted collection')
// Delete database
await admin.deleteDatabase("query_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を使用した操作も可能です。SQLの使用方法については、SQLによるベクトル検索のクイック体験およびSQLによるハイブリッド検索のクイック体験を参照してください。