メインコンテンツまでスキップ
バージョン: V1.1.0

Ollamaとの連携

seekdbは、ベクトル型データの格納、ベクトルインデックス、そしてembeddingベクトル検索機能を提供します。これにより、ベクトル化したデータをseekdbに保存し、次の検索処理で利用できます。

Ollamaは、オープンソースツールであり、GPT-OSS、Gemma 3、DeepSeek-R1、Qwen3などの大規模言語モデルをローカル環境で簡単に実行および管理できるようにします。

前提条件​

  • seekdbがデプロイ済みであること。

  • 環境に使用可能なデータベースとアカウントが存在し、データベースアカウントに読み書き権限が付与されていること。

  • Python 3.11以降のバージョンをインストールしていること。

  • 依存関係をインストールしていること。

    python3 -m pip install cffi pyseekdb requests ollama

ステップ1:データベース接続情報を取得する​

seekdbのデプロイ担当者または管理者から、該当するデータベース接続文字列を取得します。例:

mysql -h$host -P$port -u$user_name -p$password -D$database_name

パラメータ説明:

  • $host:seekdbの接続IPアドレスを指定します。

  • $port:seekdbの接続ポートを指定します。デフォルトは2881です。

  • $database_name:アクセスするデータベース名を指定します。

    ヒント

    接続するユーザーには、データベースに対するCREATE、INSERT、DROP、SELECT権限が付与されていなければなりません。

  • $user_name:データベース接続アカウントを指定します。

  • $password:アカウントのパスワードを指定します。

ステップ2:AIアシスタントを構築する​

環境変数の設定​

seekdb接続情報を取得し、環境変数に設定します。

export SEEKDB_DATABASE_URL=YOUR_SEEKDB_DATABASE_URL
export SEEKDB_DATABASE_USER=YOUR_SEEKDB_DATABASE_USER
export SEEKDB_DATABASE_DB_NAME=YOUR_SEEKDB_DATABASE_DB_NAME
export SEEKDB_DATABASE_PASSWORD=YOUR_SEEKDB_DATABASE_PASSWORD

ollamaのインストールとモデルqwen3-embeddingの取得​

curl -fsSL https://ollama.ai/install.sh | sh
export PATH="/usr/local/bin:$PATH"
ollama --version
ollama pull qwen3-embedding:latest

サンプルコード​

データの読み込み​

ここでは、qwen3-embedding埋め込みモデルを例に説明します。

import requests, os, json, ollama, pyseekdb
from tqdm import tqdm
from pyseekdb import HNSWConfiguration

docs = [
"seekdb is an AI-native search database. It unifies relational, vector, text, JSON and GIS in a single engine, enabling hybrid search and in-database AI workflows.",

"Key features include automated workload analysis to capture SQL execution frequency, latency, CPU/IO usage; intelligent index recommendation based on real query patterns; performance bottleneck diagnosis for identifying full table scans, lock contention, and execution plan regression; and support for validating optimization suggestions in test environments.",

"seekdb supports two deployment modes: private deployment for enterprises with strict data security requirements, ensuring data never leaves the internal network; and cloud-based SaaS service for quick onboarding and trial use.",

"The standard workflow includes: 1) Configure database connection with read-only access; 2) Start data collection task (time-range or continuous); 3) Run analysis engine to generate workload profiling; 4) Review diagnostic reports via Web Console; 5) Apply and validate optimizations in production after testing.",

"Typical use cases include rapid root cause identification during database performance degradation; capacity assessment before major promotions; SQL and index tuning after system go-live; and routine health checks for proactive database maintenance.",

"Currently, seekdb primarily supports OceanBase Database in MySQL mode. Future versions will extend support to Oracle mode, as well as mainstream databases including MySQL and PostgreSQL.",

"seekdb adopts a lightweight architecture composed of: Agent (for performance data collection), Analyzer Engine (core analysis and rule matching), Recommendation Module (generates index and optimization suggestions), and Web Console (visualization and report export)."
]

ids, embeddings, documents = [], [], []

def emb_text(text):
response = ollama.embeddings(model="qwen3-embedding", prompt=text)
return response["embedding"]

for i, text in enumerate(tqdm(docs, desc="Creating embeddings")):
embedding = emb_text(text)
ids.append(f"{i+1}")
embeddings.append(embedding)
documents.append(text)

print(f"Successfully processed {len(documents)} texts")

テーブルの定義とデータのseekdbへの格納​

ollama_seekdb_demo_documents という名前のテーブルを作成し、qwen3-embeddingを使用して各テキストセグメントの埋め込みベクトルを生成し、seekdbに格納します。

SEEKDB_DATABASE_HOST = os.getenv('SEEKDB_DATABASE_HOST')
SEEKDB_DATABASE_PORT = int(os.getenv('SEEKDB_DATABASE_PORT', 2881))
SEEKDB_DATABASE_USER = os.getenv('SEEKDB_DATABASE_USER')
SEEKDB_DATABASE_DB_NAME = os.getenv('SEEKDB_DATABASE_DB_NAME')
SEEKDB_DATABASE_PASSWORD = os.getenv('SEEKDB_DATABASE_PASSWORD')

client = pyseekdb.Client(host=SEEKDB_DATABASE_HOST, port=SEEKDB_DATABASE_PORT, database=SEEKDB_DATABASE_DB_NAME, user=SEEKDB_DATABASE_USER, password=SEEKDB_DATABASE_PASSWORD)
table_name = "ollama_seekdb_demo_documents"
config = HNSWConfiguration(dimension=4096, distance='l2')
collection = client.create_collection(
name=table_name,
configuration=config,
embedding_function=None
)

print('- Inserting Data to seekdb...')
collection.add(
ids=ids,
embeddings=embeddings,
documents=documents
)

セマンティック検索​

qwen3-embedding埋め込みモデルを使用してクエリテキストの埋め込みベクトルを生成し、その後、クエリテキストの埋め込みベクトルとベクトルテーブル内の各埋め込みベクトルとのL2距離に基づいて、最も関連性の高いドキュメントを検索します。

query = 'What is seekdb?'
query_embedding = emb_text(query)

res = collection.query(
query_embeddings=query_embedding,
n_results=1
)

print('- The Most Relevant Document and Its Distance to the Query:')
for i, (doc_id, document, distance) in enumerate(zip(
res['ids'][0],
res['documents'][0],
res['distances'][0]
)):
print(f'- ID: {doc_id}')
print(f' content: {document}')
print(f' distance: {distance:.6f}')

期待される結果​

- ID: 1
content: seekdb is an AI-native search database. It unifies relational, vector, text, JSON and GIS in a single engine, enabling hybrid search and in-database AI workflows.
distance: 0.675768