これは、Pineconeの公式node.js SDKであり、TypeScriptで記述されています。
v0.xからアップグレードする場合は、 V1 Migration Guideをご覧ください。v1.xからアップグレードしている場合は、 V2 Migration Guideをご覧ください。このREADMEに示されているスニペットは、簡潔にすることを目的としています。より現実的な例については、これらの例を調べてください。
2.xから3.xへのアップグレードこのアップデートでは、 configureIndex操作を含む破損の変更があります。インデックスを構成するときに渡されたオブジェクトの構造は、 deletionProtectionを含むように変更されました。 podTypeおよびreplicasフィールドは、 spec.podオブジェクトから更新できるようになりました。コードの例については、PODベースのインデックスの構成を参照してください。
2.xへのアップグレード:Pineconeの新しいサーバーレスインデックスの提供をサポートするために、このリリースで多くの変更が行われました。変更については、 V2移行ガイドで詳しく説明しています。サーバーレスインデックスは、 2.xリリースバージョン以上でのみ使用できます。1.xにアップグレード:このリリースは、SDKをベータ版から正式に移動しました0.xバージョンからアップグレードする際に対処する必要がある多くの壊れた変更があります。詳細については、 V1移行ガイドを参照してください。 Pinecone TypeScript SDKは、TypeScript> = 4.1およびNode> = 18.xと互換性があります。
npm install @pinecone-database/pinecone
Pinecone TypeScript SDKは、サーバー側の使用のみを目的としています。ブラウザコンテキスト内でSDKを使用すると、APIキーが公開される可能性があります。ブラウザでSDKを生産に展開した場合は、 APIキーを回転させてください。
クライアントを初期化するには、APIキーが必要です。環境変数を使用して、または構成オブジェクトを介してコードを使用して渡すことができます。コンソールでAPIキーを取得します。
クライアントのAPIキーを構成するために使用される環境変数は次のとおりです。
PINECONE_API_KEY= " your_api_key " PINECONE_API_KEYは唯一の必要な変数です。この環境変数が設定されている場合、クライアントコンストラクターは追加の引数を必要としません。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ; コードで構成を渡すことを好む場合、コンストラクターはapiKey値を含む構成オブジェクトを受け入れます。これは、再生可能な操作( upsert 、 update 、 configureIndex )のmaxRetries (デフォルトは3 )などのプロパティを渡すオブジェクトです。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( {
apiKey : 'your_api_key' ,
maxRetries : 5 ,
} ) ;ネットワークのセットアップでは、プロキシを介してPineconeと対話する必要がある場合は、 undiciライブラリからカスタムProxyAgentを渡すことができます。以下は、Pinecone /indexes Endpointを押しながらmitmプロキシサーバーを介してネットワークトラフィックをルーティングするundici ProxyAgentを構築する方法の例です。
注:次の戦略は、ノードV16でリリースされ、ノードV21で安定したノードのネイティブfetch実装に依存しています。ノードバージョン18-21を実行している場合、機能の不安定性に起因する問題が発生する可能性があります。現在、ノードv18+のプロキシに関連する既知の問題はありません。
import {
Pinecone ,
type PineconeConfiguration ,
} from '@pinecone-database/pinecone' ;
import { Dispatcher , ProxyAgent } from 'undici' ;
import * as fs from 'fs' ;
const cert = fs . readFileSync ( 'path-to-your-mitm-proxy-cert-pem-file' ) ;
const client = new ProxyAgent ( {
uri : '<your proxy server URI>' ,
requestTls : {
port : '<your proxy server port>' ,
ca : cert ,
host : '<your proxy server host>' ,
} ,
} ) ;
const customFetch = (
input : string | URL | Request ,
init : RequestInit | undefined
) => {
return fetch ( input , {
... init ,
dispatcher : client as Dispatcher ,
keepalive : true , # optional
} ) ;
} ;
const config : PineconeConfiguration = {
apiKey :
'<your Pinecone API key, available in your dashboard at app.pinecone.io>' ,
fetchApi : customFetch ,
} ;
const pc = new Pinecone ( config ) ;
const indexes = async ( ) => {
return await pc . listIndexes ( ) ;
} ;
indexes ( ) . then ( ( response ) => {
console . log ( 'My indexes: ' , response ) ;
} ) ; 少なくとも、サーバーレスインデックスを作成するには、 name 、 dimension 、およびspecを指定する必要があります。 dimension 、インデックスに保存するベクトルのサイズを示します。たとえば、OpenaiのTextembedding-aad-002モデルで生成された埋め込み(ベクター)を保存してクエリすることを意図している場合、そのモデルの出力と一致するようにディメンション1536のインデックスを作成する必要があります。
spec 、インデックスの展開方法を構成します。サーバーレスインデックスの場合、インデックスをホストする必要があるクラウドと領域のみを定義します。ポッドベースのインデックスの場合、インデックスをホストする環境、使用するポッドタイプとサイズ、およびその他のインデックス特性を定義します。サーバーレスおよび地域の可用性の詳細については、理解の理解を参照してください。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . createIndex ( {
name : 'sample-index' ,
dimension : 1536 ,
spec : {
serverless : {
cloud : 'aws' ,
region : 'us-west-2' ,
} ,
} ,
tags : { team : 'data-science' } ,
} ) ; ポッドベースのインデックスを作成するには、インデックスをホストするenvironmentと使用するpodTypeとpodsサイズを含むspecオブジェクトにpodを定義します。多くのオプションの構成フィールドにより、ハードウェアリソースと可用性をより強く制御できます。これらのフィールドの目的の詳細については、インデックスを理解し、ポッドベースのインデックスをスケールしてください。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . createIndex ( {
name : 'sample-index-2' ,
dimension : 1536 ,
metric : 'dotproduct' ,
spec : {
pod : {
environment : 'us-east4-gcp' ,
pods : 2 ,
podType : 'p1.x2' ,
metadataConfig : {
indexed : [ 'product_type' ] ,
} ,
} ,
tags : { team : 'data-science' } ,
} ,
// This option tells the client not to throw if the index already exists.
suppressConflicts : true ,
// This option tells the client not to resolve the promise until the
// index is ready.
waitUntilReady : true ,
} ) ; createIndexメソッドは、迅速に返すAPIへの作成要求を発行しますが、結果のインデックスは他のデータ操作の上昇、クエリ、または実行の準備がすぐにありません。 describeIndexメソッドを使用して、インデックスのステータスを見つけて、使用の準備ができているかどうかを確認できます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . describeIndex ( 'serverless-index' ) ;
// {
// name: 'serverless-index',
// dimension: 1536,
// metric: 'cosine',
// host: 'serverless-index-4zo0ijk.svc.us-west2-aws.pinecone.io',
// deletionProtection: 'disabled',
// spec: {
// serverless: {
// cloud: 'aws',
// region: 'us-west-2'
// }
// },
// status: {
// ready: false,
// state: 'Initializing'
// }
// } waitUntilReadyオプションに合格すると、クライアントは新しく作成されたインデックスのステータス更新のポーリングを処理します。 createIndexによって返される約束は、インデックスステータスがデータ操作を処理する準備ができていることを示すまで解決されません。これは、セットアップステップでのインデックスの作成がすぐにデータ操作が続く統合テストに特に役立ちます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . createIndex ( {
name : 'serverless-index' ,
dimension : 1536 ,
spec : {
serverless : {
cloud : 'aws' ,
region : 'us-west-2' ,
} ,
} ,
waitUntilReady : true ,
} ) ; 注記
サーバーレスとスターターのインデックスは、コレクションをサポートしていません。
より多くのものにPineconeを使用するため、同じベクトルデータを使用してさまざまなインデックス構成を調査することをお勧めします。コレクションは、これを行う簡単な方法を提供します。こちらのコレクションを操作するための他のクライアント方法をご覧ください。
既存のコレクションがあることを考えると、
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . describeCollection ( 'product-description-embeddings' ) ;
// {
// name: 'product-description-embeddings',
// size: 543427063,
// status: 'Ready',
// dimension: 2,
// vectorCount: 10001498,
// environment: 'us-east4-gcp'
// }注:ポッドベースのインデックスの場合、インデックスを作成するためのsourceCollectionを指定できます。コレクションは、インデックスと同じ環境にある必要があります。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . createIndex ( {
name : 'product-description-p1x1' ,
dimension : 256 ,
metric : 'cosine' ,
spec : {
pod : {
environment : 'us-east4-gcp' ,
pods : 1 ,
podType : 'p1.x1' ,
sourceCollection : 'product-description-embeddings' ,
} ,
} ,
} ) ;新しいインデックスの準備ができたら、コレクション内にあるすべてのデータが含まれている必要があります。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . index ( 'product-description-p2x2' ) . describeIndexStats ( ) ;
// {
// namespaces: { '': { recordCount: 78000 } },
// dimension: 256,
// indexFullness: 0.9,
// totalRecordCount: 78000
// } deletionProtection場合、サーバーレスインデックスとPODインデックスの両方を構成できます。このプロパティを'enabled'に設定するインデックスは、削除できません。デフォルトでは、 createIndex要求の一部として提供されていない場合、 deletionProtection 'disabled'ように設定されます。 deletionProtection有効にするには、 createIndex呼び出す際に値を渡すことができます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . createIndex ( {
name : 'deletion-protected-index' ,
dimension : 1536 ,
metric : 'cosine' ,
deletionProtection : 'enabled' ,
spec : {
serverless : {
cloud : 'aws' ,
region : 'us-west-2' ,
} ,
} ,
} ) ;削除保護を無効にするには、 configureIndex操作を使用できます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . configureIndex ( 'deletion-protected-index' , {
deletionProtection : 'disabled' ,
} ) ; タグでサーバーレスおよびポッドインデックスを作成または構成できます。インデックスは、チームの所有権、プロジェクト、またはその他の関連情報など、インデックスオブジェクト自体に添付したいメタデータを概説する任意の数のタグを保持できます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
// Create index with tag
await pc . createIndex ( {
name : 'tag-index' ,
dimension : 1536 ,
metric : 'cosine' ,
spec : {
serverless : {
cloud : 'aws' ,
region : 'us-west-2' ,
} ,
} ,
tags : { team : 'data-science' } , // index tag
} ) ;
// Configure index with a new tag
await pc . configureIndex ( 'tag-index' , {
tags : { project : 'recommendation' } , // new index tag
} ) ;
// Delete an existing tag
await pc . configureIndex ( 'tag-index' , {
tags : { project : '' } , // Pass an empty string to an existing key to delete a tag; this will delete the `project` tag
} ) ;describeIndexを使用して、任意のインデックスの説明を名前で取得できます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . describeIndex ( 'serverless-index' ) ;
// {
// name: 'serverless-index',
// dimension: 1536,
// metric: 'cosine',
// host: 'serverless-index-4zo0ijk.svc.us-west2-aws.pinecone.io',
// deletionProtection: 'disabled',
// spec: {
// serverless: {
// cloud: 'aws',
// region: 'us-west-2'
// },
// },
// status: {
// ready: true,
// state: 'Ready'
// }
// }注記
このセクションは、ポッドベースのインデックスのみに適用されます。サーバーレスインデックスを使用すると、計算リソースまたはストレージリソースを構成しません。代わりに、サーバーレスインデックスは、使用量に基づいて自動的にスケールします。
レプリカまたはスケールの数をより大きなポッドサイズ( podTypeで指定)に調整できます。スケールポッドベースのインデックスを参照してください。ポッドサイズをダウングレードしたり、ベースポッドタイプを変更したりすることはできません。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . configureIndex ( 'pod-index' , {
spec : {
pod : {
replicas : 2 ,
podType : 'p1.x4' ,
} ,
} ,
} ) ;
const config = await pc . describeIndex ( 'pod-index' ) ;
// {
// name: 'pod-index',
// dimension: 1536,
// metric: 'cosine',
// host: 'pod-index-4zo0ijk.svc.us-east1-gcp.pinecone.io',
// deletionProtection: 'disabled',
// spec: {
// pod: {
// environment: 'us-east1-gcp',
// replicas: 2,
// shards: 2,
// podType: 'p1.x4',
// pods: 4,
// metadataConfig: [Object],
// sourceCollection: undefined
// }
// },
// status: {
// ready: true,
// state: 'ScalingUpPodSize'
// }
// }インデックスは名前で削除されます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . deleteIndex ( 'sample-index' ) ;listIndexesコマンドは、 indexesの下にある一連のインデックスモデルを持つオブジェクトを返します。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . listIndexes ( ) ;
// {
// indexes: [
// {
// name: 'serverless-index',
// dimension: 1536,
// metric: 'cosine',
// host: 'serverless-index-4zo0ijk.svc.us-west2-aws.pinecone.io',
// deletionProtection: 'disabled',
// spec: {
// serverless: {
// cloud: 'aws',
// region: 'us-west-2',
// },
// },
// status: {
// ready: true,
// state: 'Ready',
// },
// },
// {
// name: 'pod-index',
// dimension: 1536,
// metric: 'cosine',
// host: 'pod-index-4zo0ijk.svc.us-west2-aws.pinecone.io',
// deletionProtection: 'disabled',
// spec: {
// pod: {
// environment: 'us-west2-aws',
// replicas: 1,
// shards: 1,
// podType: 'p1.x1',
// pods: 1,
// },
// },
// status: {
// ready: true,
// state: 'Ready',
// },
// },
// ],
// } 注記
サーバーレスとスターターのインデックスは、コレクションをサポートしていません。
コレクションは、バックアップの作成、インデックスのコピーの作成、異なるインデックス構成の実験を実行するために使用できるポッドベースのインデックスの静的コピーです。 Pineconeコレクションの詳細については、コレクションの理解を参照してください。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . createCollection ( {
name : 'collection-name' ,
source : 'index-name' ,
} ) ;このAPI呼び出しは迅速に返されるはずですが、コレクションの作成は、ソースインデックスのサイズとインデックスの構成に応じて数分から数時間かかる場合があります。 describeCollectionを使用して、コレクションのステータスを確認します。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . deleteCollection ( 'collection-name' ) ; listCollectionsを使用して削除を確認できます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const describeCollection = await pc . describeCollection ( 'collection3' ) ;
// {
// name: 'collection3',
// size: 3126700,
// status: 'Ready',
// dimension: 3,
// vectorCount: 1234,
// environment: 'us-east1-gcp',
// }listCollectionsコマンドは、 collectionsの下にある一連のコレクションモデルを備えたオブジェクトを返します。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const list = await pc . listCollections ( ) ;
// {
// collections: [
// {
// name: 'collection1',
// size: 3089687,
// status: 'Ready',
// dimension: 3,
// vectorCount: 17378,
// environment: 'us-west1-gcp',
// },
// {
// name: 'collection2',
// size: 208309,
// status: 'Ready',
// dimension: 3,
// vectorCount: 1000,
// environment: 'us-east4-gcp',
// },
// ];
// } Pineconeインデックスは、UPSERT、クエリ、フェッチ、削除などの操作を使用して、ベクターデータを操作するための操作をサポートします。
インデックスでデータ操作を実行するには、 indexメソッドを使用してターゲットにします。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'test-index' ) ;
// Now perform index operations
await index . fetch ( [ '1' ] ) ;最初の引数は、ターゲットとしているインデックスの名前です。インデックスホストのオーバーライドを提供するためのオプションの2番目の引数があります。この2番目の引数を提供することで、提供されたインデックス名を介してインデックスホストを解決するというSDKのデフォルトの動作をバイパスできます。 Pinecone Consoleでインデックスホストを見つけるか、 describeIndexまたはlistIndexes操作を使用して見つけることができます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'test-index' , 'my-index-host-1532-svc.io' ) ;
// Now perform index operations against: https://my-index-host-1532-svc.io
await index . fetch ( [ '1' ] ) ;メタデータをベクトル値と一緒に保存している場合、適切なタイプスクリプトタイプチェックを取得するために、型パラメーターをindex()に渡すことができます。
import { Pinecone , PineconeRecord } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
type MovieMetadata = {
title : string ,
runtime : number ,
genre : 'comedy' | 'horror' | 'drama' | 'action'
}
// Specify a custom metadata type while targeting the index
const index = pc . index < MovieMetadata > ( 'test-index' ) ;
// Now you get type errors if upserting malformed metadata
await index . upsert ( [ {
id : '1234' ,
values : [
... . // embedding values
] ,
metadata : {
genre : 'Gone with the Wind' ,
runtime : 238 ,
genre : 'drama' ,
// @ts-expect-error because category property not in MovieMetadata
category : 'classic'
}
} ] )
const results = await index . query ( {
vector : [
... // query embedding
] ,
filter : { genre : { '$eq' : 'drama' } }
} )
const movie = results . matches [ 0 ] ;
if ( movie . metadata ) {
// Since we passed the MovieMetadata type parameter above,
// we can interact with metadata fields without having to
// do any typecasting.
const { title , runtime , genre } = movie . metadata ;
console . log ( `The best match in drama was ${ title } ` )
}デフォルトでは、すべてのデータ操作は、 ''のデフォルトの名前空間内で行われます。他の非デフォルト名前空間を使用している場合は、 namespace()への呼び出しをチェックすることにより、名前空間をターゲットにすることができます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'test-index' ) . namespace ( 'ns1' ) ;
// Now perform index operations in the targeted index and namespace
await index . fetch ( [ '1' ] ) ;詳細については、名前空間を使用してください。
Pineconeは、インデックスに挿入されたレコードが次の形式を持つことを期待しています。
type PineconeRecord = {
id : string ;
values : Array < number > ;
sparseValues ?: Array < number > ;
metadata ?: object ;
} ;いくつかのベクトルをupSertするには、次のようにクライアントを使用できます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
// Target an index
const index = pc . index ( 'sample-index' ) ;
// Prepare your data. The length of each array
// of vector values must match the dimension of
// the index where you plan to store them.
const vectors = [
{
id : '1' ,
values : [ 0.236 , 0.971 , 0.559 ] ,
sparseValues : { indices : [ 0 , 1 ] , values : [ 0.236 , 0.34 ] } , // Optional; for hybrid search
} ,
{
id : '2' ,
values : [ 0.685 , 0.111 , 0.857 ] ,
sparseValues : { indices : [ 0 , 1 ] , values : [ 0.345 , 0.98 ] } , // Optional; for hybrid search
} ,
] ;
// Upsert the data into your index
await index . upsert ( vectors ) ;これで、オブジェクトストレージからベクトルをマスセルすることができます。 Import 、多くのレコードをPinecone Serverlessインデックスにインポートする長期にわたる非同期操作です。
オブジェクトストレージからベクトルをインポートするには、それらをParquetファイルに保存し、必要なファイル形式に準拠する必要があります。オブジェクトストレージは、必要なディレクトリ構造にも付着する必要があります。
次の例では、アマゾンS3バケットからベクトルをPinecone ServerLessインデックスにインポートします。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const indexName = 'sample-index' ;
await pc . createIndex ( {
name : indexName ,
dimension : 10 ,
spec : {
serverless : {
cloud : 'aws' ,
region : 'eu-west-1' ,
} ,
} ,
} ) ;
const index = pc . Index ( indexName ) ;
const storageURI = 's3://my-bucket/my-directory/' ;
await index . startImport ( storageURI , 'continue' ) ; // "Continue" will avoid aborting the operation if errors are encountered.
// {
// "id": "import-id"
// }すべてまたは1つのインポート操作のステータスを起動、キャンセル、および確認できます。
注:
Import 、サーバーレスインデックスでのみ動作しますImportは公開されていますデータ操作を実験する場合、各名前空間に保存されているレコード/ベクトルの数を知ることが時々役立つことがあります。その場合、インデックスをターゲットにし、 describeIndexStats()コマンドを使用します。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'example-index' ) ;
await index . describeIndexStats ( ) ;
// {
// namespaces: {
// '': { recordCount: 10 }
// foo: { recordCount: 2000 },
// bar: { recordCount: 2000 }
// },
// dimension: 1536,
// indexFullness: 0,
// totalRecordCount: 4010
// }クエリメソッドは、多数のオプションを受け入れます。クエリベクトルの寸法は、インデックスの次元と一致する必要があります。
type QueryOptions = {
topK : number ; // number of results desired
vector ?: Array < number > ; // must match dimension of index
sparseVector ?: {
indices : Array < integer > ; // indices must fall within index dimension
values : Array < number > ; // indices and values arrays must have same length
} ;
id ?: string ;
includeMetadata : boolean ;
includeValues : boolean ;
} ;たとえば、ベクトル値でクエリするには、オプション構成でvector PARAMを渡します。簡潔にするために、この例のクエリベクトルは小さく(次元2)ですが、より現実的なユースケースでは、このクエリベクトルはモデルによって出力されます。サンプルコードを見て、 query使用方法のより現実的な例を確認してください。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'my-index' ) ;
await index . query ( { topK : 3 , vector : [ 0.22 , 0.66 ] } ) ;
// {
// matches: [
// {
// id: '556',
// score: 1.00000012,
// values: [],
// sparseValues: undefined,
// metadata: undefined
// },
// {
// id: '137',
// score: 1.00000012,
// values: [],
// sparseValues: undefined,
// metadata: undefined
// },
// {
// id: '129',
// score: 1.00000012,
// values: [],
// sparseValues: undefined,
// metadata: undefined
// }
// ],
// namespace: '',
// usage: {
// readUnits: 5
// }
// } includeMetadata: trueまたはincludeValues: true 。デフォルトでは、これらは応答ペイロードを小さく保つために返されません。
データ操作はnamespaceのコンテキスト内で行われることに注意してください。そのため、名前空間を操作していて、予想される結果が表示されない場合は、クエリで正しい名前空間をターゲットにしていることを確認する必要があります。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
// Target the index and namespace
const index = pc . index ( 'my-index' ) . namespace ( 'my-namespace' ) ;
const results = await index . query ( { topK : 3 , vector : [ 0.22 , 0.66 ] } ) ; レコードIDを渡すことにより、インデックス内の既存のレコードのベクトル値を使用して照会できます。指定されたIDのレコードは、この操作の応答にある場合があることに注意してください。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'my-index' ) ;
const results = await index . query ( { topK : 10 , id : '1' } ) ; スパース密度の高いベクトルを使用している場合は、スパースベクトル値を追加してハイブリッド検索を実行できます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . createIndex ( {
name : 'hybrid-search-index' ,
metric : 'dotproduct' , // Note: dot product is the only distance metric supported for hybrid search
dimension : 2 ,
spec : {
pod : {
environment : 'us-west4-gcp' ,
podType : 'p2.x1' ,
} ,
} ,
waitUntilReady : true ,
} ) ;
const index = pc . index ( 'hybrid-search-index' ) ;
const hybridRecords = [
{
id : '1' ,
values : [ 0.236 , 0.971 ] , // dense vectors
sparseValues : { indices : [ 0 , 1 ] , values : [ 0.236 , 0.34 ] } , // sparse vectors
} ,
{
id : '2' ,
values : [ 0.685 , 0.111 ] ,
sparseValues : { indices : [ 0 , 1 ] , values : [ 0.887 , 0.243 ] } ,
} ,
] ;
await index . upsert ( hybridRecords ) ;
const query = 'What is the most popular red dress?' ;
// ... send query to dense vector embedding model and save those values in `denseQueryVector`
// ... send query to sparse vector embedding model and save those values in `sparseQueryVector`
const denseQueryVector = [ 0.236 , 0.971 ] ;
const sparseQueryVector = { indices : [ 0 , 1 ] , values : [ 0.0 , 0.34 ] } ;
// Execute a hybrid search
await index . query ( {
topK : 3 ,
vector : denseQueryVector ,
sparseVector : sparseQueryVector ,
} ) ;ベクトルvalues 、 sparseValues 、またはmetadataを更新することをお勧めします。更新するIDと属性値を指定します。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'imdb-movies' ) ;
await index . update ( {
id : '18593' ,
metadata : { genre : 'romance' } ,
} ) ;listPaginatedメソッドを使用して、特定のIDプレフィックスをパジネート形式で一致させるレコードIDをリストできます。レコードIDの巧妙な割り当てを使用すると、これを使用して、同じドキュメントに関連する複数のチャンクまたはフラグメントの埋め込みがある場合など、異なるレコード間の階層的な関係をモデル化するのに役立ちます。
注:
prefixを指定しない場合、デフォルトのプレフィックスは空の文字列で、インデックス内のすべてのベクトルIDを返しますlimitが指定されていない場合、 100ベクトルIDの厳しい制限があります。その結果、インデックス内の特定のprefixに一致する100未満のベクトルIDがあり、 limitを指定しない場合、 paginationTokenはundefinedになります次の例は、3のlimit 3とdoc1ドキュメントが4ベクトルに充電されていると仮定して、IDがプレフィックスdoc1#を含むベクトルのベクトルIDの両方のページを取得する方法を示しています。
const pc = new Pinecone ( ) ;
const index = pc . index ( 'my-index' ) . namespace ( 'my-namespace' ) ;
// Fetch the 1st 3 vector IDs matching prefix 'doc1#'
const results = await index . listPaginated ( { limit : 3 , prefix : 'doc1#' } ) ;
console . log ( results ) ;
// {
// vectors: [
// { id: 'doc1#01' }
// { id: 'doc1#02' }
// { id: 'doc1#03' }
// ...
// ],
// pagination: {
// next: 'eyJza2lwX3Bhc3QiOiJwcmVUZXN0LS04MCIsInByZWZpeCI6InByZVRlc3QifQ=='
// },
// namespace: 'my-namespace',
// usage: { readUnits: 1 }
// }
// Fetch the final vector ID matching prefix 'doc1#' using the paginationToken returned by the previous call
const nextResults = await index . listPaginated ( {
prefix : 'doc1#' ,
paginationToken : results . pagination ?. next ,
} ) ;
console . log ( nextResults ) ;
// {
// vectors: [
// { id: 'doc1#04' }
// ],
// pagination: undefined,
// namespace: 'my-namespace',
// usage: { readUnits: 1 }
// } import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'my-index' ) ;
const fetchResult = await index . fetch ( [ 'id-1' , 'id-2' ] ) ;便利なため、いくつかの削除関連の方法があります。 describeIndexStats()でrected fetch()たり、インデックスサマリーを調べたりすることにより、削除操作の結果を確認できます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'my-index' ) ;
await index . deleteOne ( 'id-to-delete' ) ; import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'my-index' ) ;
await index . deleteMany ( [ 'id-1' , 'id-2' , 'id-3' ] ) ;注:メタデータフィルターによる削除は、ポッドベースのインデックスにのみ適用されます。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'albums-database' ) ;
await index . deleteMany ( { genre : 'rock' } ) ; 注記
GCP-Starter環境のインデックスは、名前空間をサポートしていません。
ターゲットネームスペースのすべてを核にするには、 deleteAllメソッドを使用します。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'my-index' ) ;
await index . namespace ( 'foo-namespace' ) . deleteAll ( ) ;名前空間を指定しない場合、デフォルトの名前''のレコードが削除されます。
Pineconeの推論APIと対話します(現在公開されています)。 Pinecone Inference APIは、Pineconeのインフラストラクチャでホストされている推論モデルへのアクセスを提供するサービスです。
注:
サポートされているモデル:
テキストをPineconeの推論APIに送信して、ドキュメントとクエリの埋め込みを生成します。
import { Pinecone } from '@pinecone-database/pinecone' ;
const client = new Pinecone ( { apiKey : '<Your API key from app.pinecone.io>' } ) ;
const embeddingModel = 'multilingual-e5-large' ;
const documents = [
'Turkey is a classic meat to eat at American Thanksgiving.' ,
'Many people enjoy the beautiful mosques in Turkey.' ,
] ;
const docParameters = {
inputType : 'passage' ,
truncate : 'END' ,
} ;
async function generateDocEmbeddings ( ) {
try {
return await client . inference . embed (
embeddingModel ,
documents ,
docParameters
) ;
} catch ( error ) {
console . error ( 'Error generating embeddings:' , error ) ;
}
}
generateDocEmbeddings ( ) . then ( ( embeddingsResponse ) => {
if ( embeddingsResponse ) {
console . log ( embeddingsResponse ) ;
}
} ) ;
// << Upsert documents into Pinecone >>
const userQuery = [ 'How should I prepare my turkey?' ] ;
const queryParameters = {
inputType : 'query' ,
truncate : 'END' ,
} ;
async function generateQueryEmbeddings ( ) {
try {
return await client . inference . embed (
embeddingModel ,
userQuery ,
queryParameters
) ;
} catch ( error ) {
console . error ( 'Error generating embeddings:' , error ) ;
}
}
generateQueryEmbeddings ( ) . then ( ( embeddingsResponse ) => {
if ( embeddingsResponse ) {
console . log ( embeddingsResponse ) ;
}
} ) ;
// << Send query to Pinecone to retrieve similar documents >> クエリに対して関連する順序を下ることで文書を再表示します。
注: score 、特定のクエリとパッセージペアの関連性の絶対的な尺度を表します。 [0、1]の間で正規化されたscore 、特定のアイテムとクエリがどれほど密接に関連するかを表し、スコアは1に近いことを示しています。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const rerankingModel = 'bge-reranker-v2-m3' ;
const myQuery = 'What are some good Turkey dishes for Thanksgiving?' ;
// Option 1: Documents as an array of strings
const myDocsStrings = [
'I love turkey sandwiches with pastrami' ,
'A lemon brined Turkey with apple sausage stuffing is a classic Thanksgiving main' ,
'My favorite Thanksgiving dish is pumpkin pie' ,
'Turkey is a great source of protein' ,
] ;
// Option 1 response
const response = await pc . inference . rerank (
rerankingModel ,
myQuery ,
myDocsStrings
) ;
console . log ( response ) ;
// {
// model: 'bge-reranker-v2-m3',
// data: [
// { index: 1, score: 0.5633179, document: [Object] },
// { index: 2, score: 0.02013874, document: [Object] },
// { index: 3, score: 0.00035419367, document: [Object] },
// { index: 0, score: 0.00021485926, document: [Object] }
// ],
// usage: { rerankUnits: 1 }
// }
// Option 2: Documents as an array of objects
const myDocsObjs = [
{
title : 'Turkey Sandwiches' ,
body : 'I love turkey sandwiches with pastrami' ,
} ,
{
title : 'Lemon Turkey' ,
body : 'A lemon brined Turkey with apple sausage stuffing is a classic Thanksgiving main' ,
} ,
{
title : 'Thanksgiving' ,
body : 'My favorite Thanksgiving dish is pumpkin pie' ,
} ,
{
title : 'Protein Sources' ,
body : 'Turkey is a great source of protein' ,
} ,
] ;
// Option 2: Options object declaring which custom key to rerank on
// Note: If no custom key is passed via `rankFields`, each doc must contain a `text` key, and that will act as the default)
const rerankOptions = {
topN : 3 ,
returnDocuments : false ,
rankFields : [ 'body' ] ,
parameters : {
inputType : 'passage' ,
truncate : 'END' ,
} ,
} ;
// Option 2 response
const response = await pc . inference . rerank (
rerankingModel ,
myQuery ,
myDocsObjs ,
rerankOptions
) ;
console . log ( response ) ;
// {
// model: 'bge-reranker-v2-m3',
// data: [
// { index: 1, score: 0.5633179, document: undefined },
// { index: 2, score: 0.02013874, document: undefined },
// { index: 3, score: 0.00035419367, document: undefined },
// ],
// usage: { rerankUnits: 1 }
//} すべてのテストはCIで自動的に行われ、このレポの.githubディレクトリにあるGithubアクションとワークフローを使用して構成されます。
詳細については、Converting.mdを参照してください。