> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # PG ベクターストア PgVector クラスは、[PostgreSQL](https://www.postgresql.org/) で [pgvector](https://github.com/pgvector/pgvector) 拡張を導入したベクトル検索を提供します。 既存の PostgreSQL データベース内で信頼性の高いベクトル類似検索を利用できます。 ## コンストラクターオプション **connectionString** (`string`): PostgreSQL 接続 URL **host** (`string`): PostgreSQL サーバーのホスト **port** (`number`): PostgreSQL サーバーのポート **database** (`string`): PostgreSQL データベース名 **user** (`string`): PostgreSQL ユーザー **password** (`string`): PostgreSQL パスワード **ssl** (`boolean | ConnectionOptions`): SSL を有効にするか、カスタム SSL 設定を指定します **schemaName** (`string`): ベクターストアで使用するスキーマ名。指定しない場合はデフォルトスキーマを使用します。 **max** (`number`): プール接続の最大数(デフォルト: 20) **idleTimeoutMillis** (`number`): アイドル接続のタイムアウト(ミリ秒、デフォルト: 30000) **pgPoolOptions** (`PoolConfig`): 追加の pg プール設定オプション **disableInit** (`boolean`): true の場合、createIndex 内での自動 DDL(スキーマ、拡張、テーブル、インデックスの作成)を省略します。スキーマとインデックスを別に管理し、ランタイムのデータベースロールに DDL 権限がない CI/CD パイプラインで役立ちます。環境変数 MASTRA\_DISABLE\_STORAGE\_INIT でも有効にできます。 (Default: `false`) ## コンストラクターの例 ### 接続文字列 ```ts import { PgVector } from '@mastra/pg' const vectorStore = new PgVector({ id: 'pg-vector', connectionString: 'postgresql://user:password@localhost:5432/mydb', }) ``` ### ホスト、ポート、データベースの設定 ```ts const vectorStore = new PgVector({ id: 'pg-vector', host: 'localhost', port: 5432, database: 'mydb', user: 'postgres', password: 'password', }) ``` ### 高度な設定 ```ts const vectorStore = new PgVector({ id: 'pg-vector', connectionString: 'postgresql://user:password@localhost:5432/mydb', schemaName: 'custom_schema', max: 30, idleTimeoutMillis: 60000, pgPoolOptions: { connectionTimeoutMillis: 5000, allowExitOnIdle: true, }, }) ``` ## メソッド ### `createIndex()` **indexName** (`string`): 作成するインデックスの名前 **dimension** (`number`): ベクトルの次元数(埋め込みモデルと一致させる必要があります) **metric** (`'cosine' | 'euclidean' | 'dotproduct'`): 類似検索の距離メトリクス (Default: `cosine`) **indexConfig** (`IndexConfig`): インデックス設定 (Default: `{ type: 'ivfflat' }`) **buildIndex** (`boolean`): インデックスを構築するかどうか (Default: `true`) **metadataIndexes** (`string[]`): btree インデックスを作成するメタデータフィールド名の配列。これらのメタデータフィールドでフィルタリングする際のクエリ性能を向上させます。 #### `IndexConfig` **type** (`'flat' | 'hnsw' | 'ivfflat'`): インデックスの種類 (Default: `ivfflat`) **type.flat** (`flat`): 全件検索を実行するシーケンシャルスキャン(インデックスなし)。 **type.ivfflat** (`ivfflat`): 近似検索のためにベクトルをリストへクラスタリングします。 **type.hnsw** (`hnsw`): 高速な検索と高い再現率を提供するグラフベースのインデックス。 **ivf** (`IVFConfig`): IVF 設定 **ivf.lists** (`number`): リスト数。指定しない場合、データセットのサイズに基づいて自動計算されます(最小 100、最大 4000)。 **hnsw** (`HNSWConfig`): HNSW 設定 **hnsw\.m** (`number`): ノードごとの最大接続数(デフォルト: 8) **hnsw\.efConstruction** (`number`): 構築時の複雑度(デフォルト: 32) #### メモリ要件 HNSW インデックスの構築には大量の共有メモリが必要です。ベクトルが 10 万件の場合: - 小さい次元(64d): デフォルト設定で \~60MB - 中程度の次元(256d): デフォルト設定で \~180MB - 大きい次元(384d 以上): デフォルト設定で \~250MB 以上 M または efConstruction の値を大きくすると、メモリ要件が大幅に増加します。必要に応じてシステムの共有メモリ上限を調整してください。 ### `upsert()` **indexName** (`string`): ベクトルを upsert するインデックスの名前 **vectors** (`number[][]`): 埋め込みベクトルの配列 **metadata** (`Record[]`): 各ベクトルのメタデータ **ids** (`string[]`): 任意のベクトル ID(指定しない場合は自動生成されます) ### `query()` **indexName** (`string`): 検索するインデックスの名前 **queryVector** (`number[]`): クエリベクトル **topK** (`number`): 返す結果の数 (Default: `10`) **filter** (`Record`): メタデータフィルター **includeVector** (`boolean`): 結果にベクトルを含めるかどうか (Default: `false`) **minScore** (`number`): 類似度スコアの最小しきい値 (Default: `0`) **options** (`{ ef?: number; probes?: number }`): HNSW および IVF インデックスの追加オプション **options.ef** (`number`): HNSW 検索パラメーター **options.probes** (`number`): IVF 検索パラメーター ### `listIndexes()` インデックス名を文字列の配列として返します。 ### `describeIndex()` **indexName** (`string`): 詳細を取得するインデックスの名前 戻り値: ```typescript interface PGIndexStats { dimension: number count: number metric: 'cosine' | 'euclidean' | 'dotproduct' type: 'flat' | 'hnsw' | 'ivfflat' config: { m?: number efConstruction?: number lists?: number probes?: number } } ``` ### `deleteIndex()` **indexName** (`string`): 削除するインデックスの名前 ### `updateVector()` ID またはメタデータフィルターで単一のベクトルを更新します。`id` と `filter` のどちらか一方だけを指定する必要があります。 **indexName** (`string`): ベクトルを含むインデックスの名前 **id** (`string`): 更新するベクトルの ID(filter と同時に指定できません) **filter** (`Record`): 更新するベクトルを特定するメタデータフィルター(id と同時に指定できません) **update** (`{ vector?: number[]; metadata?: Record; }`): 更新するベクトルやメタデータを含むオブジェクト ID またはフィルターで既存のベクトルを更新します。update オブジェクトには vector または metadata の少なくとも一方を指定する必要があります。 ```typescript // Update by ID await pgVector.updateVector({ indexName: 'my_vectors', id: 'vector123', update: { vector: [0.1, 0.2, 0.3], metadata: { label: 'updated' }, }, }) // Update by filter await pgVector.updateVector({ indexName: 'my_vectors', filter: { category: 'product' }, update: { metadata: { status: 'reviewed' }, }, }) ``` ### `deleteVector()` **indexName** (`string`): ベクトルを含むインデックスの名前 **id** (`string`): 削除するベクトルの ID 指定したインデックスから ID で単一のベクトルを削除します。 ```typescript await pgVector.deleteVector({ indexName: 'my_vectors', id: 'vector123' }) ``` ### `deleteVectors()` ID またはメタデータフィルターで複数のベクトルを削除します。`ids` と `filter` のどちらか一方だけを指定する必要があります。 **indexName** (`string`): 削除するベクトルを含むインデックスの名前 **ids** (`string[]`): 削除するベクトル ID の配列(filter と同時に指定できません) **filter** (`Record`): 削除するベクトルを特定するメタデータフィルター(ids と同時に指定できません) ### `disconnect()` データベース接続プールを閉じます。ストアの使用を終えたら呼び出してください。 ### `buildIndex()` **indexName** (`string`): 定義するインデックスの名前 **metric** (`'cosine' | 'euclidean' | 'dotproduct'`): 類似検索の距離メトリクス (Default: `cosine`) **indexConfig** (`IndexConfig`): インデックスの種類とパラメーターの設定 指定したメトリクスと設定でインデックスを構築または再構築します。新しいインデックスを作成する前に、既存のインデックスを削除します。 ```typescript // Define HNSW index await pgVector.buildIndex('my_vectors', 'cosine', { type: 'hnsw', hnsw: { m: 8, efConstruction: 32, }, }) // Define IVF index await pgVector.buildIndex('my_vectors', 'cosine', { type: 'ivfflat', ivf: { lists: 100, }, }) // Define flat index await pgVector.buildIndex('my_vectors', 'cosine', { type: 'flat', }) ``` ## レスポンス型 クエリ結果は次の形式で返されます。 ```typescript interface QueryResult { id: string score: number metadata: Record vector?: number[] // Only included if includeVector is true } ``` ## エラー処理 ストアはキャッチ可能な型付きエラーをスローします。 ```typescript try { await store.query({ indexName: 'index_name', queryVector: queryVector, }) } catch (error) { if (error instanceof VectorStoreError) { console.log(error.code) // 'connection_failed' | 'invalid_dimension' | etc console.log(error.details) // Additional error context } } ``` ## インデックス設定ガイド ### パフォーマンスの最適化 #### IVFFlat の調整 - **lists パラメーター**: n をベクトル数として `sqrt(n) * 2` に設定します - リストが多いほど精度は上がりますが、構築時間は長くなります - リストが少ないほど構築は速くなりますが、精度が下がる可能性があります #### HNSW の調整 - **m パラメーター**: - 8〜16: 中程度の精度、少ないメモリ - 16〜32: 高精度、中程度のメモリ - 32〜64: 非常に高い精度、多くのメモリ - **efConstruction**: - 32〜64: 高速な構築、良好な品質 - 64〜128: 低速な構築、より良い品質 - 128〜256: 最も低速な構築、最高の品質 ### インデックスの再作成動作 システムは設定変更を自動検出し、必要な場合にのみインデックスを再構築します。 - 同じ設定: インデックスを保持します(再作成なし) - 設定変更あり: インデックスを削除して再構築します - これにより、不要なインデックス再作成によるパフォーマンス上の問題を防ぎます ## ベストプラクティス - 最適なパフォーマンスを確保するため、インデックス設定を定期的に評価します。 - データセットのサイズとクエリ要件に基づいて、`lists` や `m` などのパラメーターを調整します。 - `describeIndex()` で使用状況を追跡し、**インデックスのパフォーマンスを監視**します - 特にデータが大幅に変更された後は、効率を維持するため定期的にインデックスを再構築します ## プールへの直接アクセス `PgVector` クラスは、基盤となる PostgreSQL 接続プールをパブリックフィールドとして公開します。 ```typescript pgVector.pool // instance of pg.Pool ``` これにより、SQL クエリの直接実行、トランザクション管理、プール状態の監視など、高度な使い方が可能になります。プールへ直接アクセスする場合: - 使用後のクライアント解放(`client.release()`)は利用者の責任です。 - `disconnect()` を呼び出した後もプールへアクセスできますが、新しいクエリは失敗します。 - 直接アクセスすると、PgVector メソッドが提供する検証やトランザクションロジックを迂回します。 この設計は高度なユースケースに対応しますが、利用者による慎重なリソース管理が必要です。 ## 使用例 ### fastembed を使用したローカル埋め込み 埋め込みは、Memory の `semanticRecall` がキーワードではなく意味に基づいて関連メッセージを取得するために使用する数値ベクトルです。この設定では `@mastra/fastembed` でベクトル埋め込みを生成します。 まず `fastembed` をインストールします。 **npm**: ```bash npm install @mastra/fastembed@latest ``` **pnpm**: ```bash pnpm add @mastra/fastembed@latest ``` **Yarn**: ```bash yarn add @mastra/fastembed@latest ``` **Bun**: ```bash bun add @mastra/fastembed@latest ``` Agent に次の内容を追加します。 ```typescript import { Memory } from '@mastra/memory' import { Agent } from '@mastra/core/agent' import { PostgresStore, PgVector } from '@mastra/pg' import { fastembed } from '@mastra/fastembed' export const pgAgent = new Agent({ id: 'pg-agent', name: 'PG Agent', instructions: 'You are an AI agent with the ability to automatically recall memories from previous interactions.', model: 'openai/gpt-5.6-sol', memory: new Memory({ storage: new PostgresStore({ id: 'pg-agent-storage', connectionString: process.env.DATABASE_URL!, }), vector: new PgVector({ id: 'pg-agent-vector', connectionString: process.env.DATABASE_URL!, }), embedder: fastembed, options: { lastMessages: 10, semanticRecall: { topK: 3, messageRange: 2, }, }, }), }) ``` ## 関連情報 - [メタデータフィルター](https://mastra.zisheng.pro/ja/reference/rag/metadata-filters)