SDKを使用したベクトル検索のクイックスタート
Linux上の組み込みseekdbでベクトル検索を実行します。Pythonの例では、pyseekdbでテキストからベクトルを生成します。Node.jsの例では、@oceanbase/seekdb-nodeとmysql2を使い、SQLでサンプルのベクトルを検索します。
ほかのプラットフォームについては、pyseekdbのクイックスタートと組み込みモードを参照してください。
背景
pyseekdb
pyseekdbは、OceanBaseが提供するPythonクライアントです。一つのAPIインターフェースを基に実装されており、3種類のデータベース接続モードを提供し、組み込みモードのseekdb、サーバーモードのseekdb、およびOceanBaseデータベースへの接続をサポートしています。
このクライアントをインストールすると、組み込みモードのseekdbも同時にインストールされるため、組み込みseekdbに直接接続してデータベースの作成などの操作を実行できます。または、既にデプロイ済みのサーバーモードのseekdbまたはOceanBaseデータベースにリモート接続することもできます。
Node.js
@oceanbase/seekdb-nodeはローカルのデータディレクトリで組み込みseekdbを起動します。取得した接続先にmysql2で接続し、SQLを実行します。対応プラットフォームは組み込みモードを参照してください。
seekdbのデプロイモード
seekdbは、迅速なプロトタイプ開発から大量ユーザーをサポートするまで、さまざまな柔軟なデプロイモードを提供し、アプリケーションのニーズを全面的に満たします。
-
埋め込みモード
埋め込みバインディングがローカルで独立したseekdbプロセスを管理します。学習やプロトタイプ開発に適しています。
-
サーバーモード
テストおよび本番環境でのデプロイに推奨されるモードで、軽量で使いやすく、安定した高効率なサービス提供に適しています。
サーバーモードの使用方法については、SQLを通じてサーバーモードのseekdbを体験するを参照してください。
- pyseekdb
- Node.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に接続し、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")
Node.jsバインディングをインストールする
Node.js 22以降を使用してください。新しいプロジェクトディレクトリで、次のコマンドを実行します。
npm install --include=optional @oceanbase/seekdb-node@1.4.1 mysql2
ベクトル検索を実行する
この例では、query_test データベースと query_demo テーブルを作成し、Python の例と同じ 5 件の文書とメタデータを挿入します。文書とクエリテキストには説明用の 3 次元ベクトルを指定します。COSINE_DISTANCE でクエリベクトルに最も近い 3 件を取得します。
次のプログラムをプロジェクトディレクトリにvector-search.mjsとして保存します。
import { seekdb } from "@oceanbase/seekdb-node";
import mysql from "mysql2/promise";
const dataDir = process.argv[2] ?? "./seekdb-node-vector-data";
const db = await seekdb.open(dataDir);
try {
const endpoint = db.connectionOptions();
const address = endpoint.transport === "tcp"
? { host: endpoint.host, port: endpoint.port }
: { socketPath: endpoint.unixSocket };
const connection = await mysql.createConnection({ ...address, user: endpoint.user });
try {
// Create the sample database and table.
await connection.query("CREATE DATABASE query_test");
await connection.query("USE query_test");
await connection.query(`
CREATE TABLE query_demo (
id VARCHAR(16) PRIMARY KEY,
document VARCHAR(200) NOT NULL,
metadata JSON NOT NULL,
embedding VECTOR(3) NOT NULL
)`);
// Add the documents and their sample vectors.
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"];
const metadatas = [
{ category: "AI", index: 0 },
{ category: "Programming", index: 1 },
{ category: "Database", index: 2 },
{ category: "AI", index: 3 },
{ category: "NLP", index: 4 },
];
const embeddings = [
[1, 0, 0], [0, 1, 0], [0.2, 0, 1], [0.9, 0.3, 0], [0.4, 0, 0.9],
];
const rows = documents.map((document, i) => [
ids[i], document, JSON.stringify(metadatas[i]), JSON.stringify(embeddings[i]),
]);
await connection.query("INSERT INTO query_demo VALUES ?", [rows]);
// Find the three nearest documents.
const queryText = "artificial intelligence and machine learning";
const queryVector = [1, 0, 0];
const [results] = await connection.query(`
SELECT id, document, metadata, COSINE_DISTANCE(embedding, ?) AS distance
FROM query_demo
ORDER BY distance
LIMIT 3`, [JSON.stringify(queryVector)]);
console.log(`\nQuery: '${queryText}'`);
console.log(`Query results: ${results.length} items found`);
for (const [i, { id, distance, document, metadata }] of results.entries()) {
console.log(`\nResult ${i + 1}:`);
console.log(` ID: ${id}`);
console.log(` Distance: ${distance.toFixed(4)}`);
console.log(` Document: ${document}`);
console.log(` Metadata: ${JSON.stringify(metadata)}`);
}
// Clean up the sample database and table.
await connection.query("DROP TABLE query_demo");
await connection.query("DROP DATABASE query_test");
} finally {
await connection.end();
}
} finally {
db.close();
}
プロジェクトディレクトリで次のコマンドを実行します。初回の実行時に、プログラムがデータディレクトリ./seekdb-node-vector-dataを作成します。
node vector-search.mjs
プログラムは、検索結果ごとに ID、距離、文書、メタデータを順位順に表示します。
Query: 'artificial intelligence and machine learning'
Query results: 3 items found
Result 1:
ID: id1
Distance: 0.0000
Document: Machine learning is a subset of artificial intelligence
Metadata: {"index":0,"category":"AI"}
Result 2:
ID: id4
Distance: 0.0513
Document: Neural networks are inspired by the human brain
Metadata: {"index":3,"category":"AI"}
Result 3:
ID: id5
Distance: 0.5939
Document: Natural language processing helps computers understand text
Metadata: {"index":4,"category":"NLP"}
プログラムはサンプルのテーブルとデータベースを削除し、SQL 接続を閉じてから seekdb のハンドルを解放します。再実行時は同じデータディレクトリを使用できます。
詳細を見る
-
pyseekdbの詳細な紹介と使い方については、pyseekdbを参照してください。
-
pyseekdbの使用例については、以下を参照してください:
-
Simpleサンプル:pyseekdbのベクトル検索機能をデモンストレーションします。
-
Completeサンプル:現在のpyseekdbがサポートする全機能をデモンストレーションします。
-
ハイブリッド検索サンプル:seekdbのハイブリッド検索の使用方法をデモンストレーションし、ベクトル検索の機能と比較します。
-
Node.jsバインディングについては、組み込みモードとハイブリッド検索用 SQLを参照してください。
-
SQLの使用例については、SQLによるベクトル検索のクイック体験とSQLによるハイブリッド検索のクイック体験を参照してください。