這是用打字稿編寫的Pinecone的官方Node.js SDK。
v0.x升級,請查看V1遷移指南。v1.x升級,請查看V2遷移指南。此讀數中顯示的摘要旨在簡潔。有關更現實的示例,請探討以下示例:
2.x升級到3.x在此更新中,涉及configureIndex操作的變化有一個破壞的變化。配置索引時傳遞的對象的結構已更改為包括deletionProtection 。現在可以通過spec.pod對象更新podType和replicas字段。有關代碼的示例,請參見配置基於POD的索引。
2.x :此版本中進行了許多更改,以支持Pinecone的新無服務器索引產品。 V2遷移指南中詳細介紹了更改。無服務器索引僅在2.x版本版本或更大的版本中可用。1.x :此版本正式將SDK從Beta中移出,並且從0.x版本升級時需要解決許多破壞更改。有關詳細信息,請參見V1遷移指南。 Pinecone TypeScript SDK與TypeScript> = 4.1和Node> = 18.x兼容。
npm install @pinecone-database/pinecone
Pinecone tumpecript 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值的配置對象。這是您將maxRetries (默認值為3 )之類的屬性進行重試操作( upsert , update和configureIndex )之類的對象。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( {
apiKey : 'your_api_key' ,
maxRetries : 5 ,
} ) ;如果您的網絡設置要求您通過代理與Pinecone進行交互,則可以從undici庫中傳遞自定義的ProxyAgent 。以下是如何構建undici ProxyAgent一個示例,該前端可以通過mitm代理服務器路由網絡流量,同時鍵入Pinecone /indexes端點。
注意:以下策略依賴於節點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-Aada-002型號生成的嵌入(向量),則您需要創建一個具有Dimension 1536的索引來匹配該模型的輸出。
該spec配置了應如何部署索引。對於無服務器索引,您僅定義應託管索引的雲和區域。對於基於POD的索引,您可以定義應託管索引的環境,使用的POD類型和大小以及其他索引特性。有關無服務器和區域可用性的更多信息,請參見理解索引。
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' } ,
} ) ; 要創建基於POD的索引,您可以在spec對像中定義pod ,其中包含應託管索引的environment以及要使用的podType和pods大小。許多可選的配置字段允許對硬件資源和可用性進行更大的控制。要了解有關這些領域目的的更多信息,請參閱理解索引和基於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'
// }注意:對於基於POD的索引,您可以指定從中創建索引的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' ,
} ) ; 您可以使用標籤創建或配置無服務器和POD索引。索引可以保留概述您希望將元數據附加到索引對象本身的元數據的任意標籤,例如團隊所有權,項目或任何其他相關信息。
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'
// }
// }筆記
本節僅適用於基於POD的索引。使用無服務器索引,您不會配置任何計算或存儲資源。取而代之的是,無服務器索引根據用法自動自動索引比例。
您可以將復製品數量或比例調整為較大的POD尺寸(用podType指定)。請參閱基於比例POD的索引。您不能降級吊艙大小或更改基本吊艙類型。
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',
// },
// },
// ],
// } 筆記
無服務器和入門索引不支持集合。
集合是基於POD的索引的靜態副本,可用於創建備份,創建索引的副本或執行具有不同索引配置的實驗。要了解有關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' ] ) ;第一個參數是您要定位的索引的名稱。提供了一個可選的第二個論點,用於提供索引主機覆蓋。提供第二個參數使您可以繞過SDK通過提供的索引名稱解決索引主機的默認行為。您可以在Pinecone控制台中找到索引主機,或者通過使用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() ,以獲取適當的Typescript Typechecking。
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 ;
} ;為了提高一些向量,您可以這樣使用客戶:
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是一種長期運行的異步操作,可將大量記錄導入無原服務器索引。
為了從對象存儲中導入向量,必須將它們存儲在parquet文件中,並遵守必要的文件格式。您的對象存儲還必須遵守必要的目錄結構。
以下示例將從Amazon S3存儲桶中的向量導入到無Pinecone無服務器索引中:
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"
// }您可以啟動,取消並檢查全部或一個導入操作的狀態。
筆記:
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參數。為了簡潔起見,此示例查詢向量很小(dimension 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時,默認前綴是一個空字符串,它返回索引中的所有向量IDlimit ,則硬度限制為100向量ID。因此,如果與索引中給定prefix匹配的較少100向量ID,並且您沒有指定limit ,那麼您的paginationToken將undefined下面的示例顯示瞭如何為iD包含前綴doc1#的向量的向量ID的兩個頁面,假設limit為3和doc1文檔的限制為4向量。
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' ] ) ;為方便起見,有幾種與刪除相關的方法。您可以通過嘗試fetch()錄製或查看使用describeIndexStats()查看索引摘要來驗證刪除操作的結果。
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' ] ) ;注意:元數據過濾器的刪除僅適用於基於POD的索引。
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'albums-database' ) ;
await index . deleteMany ( { genre : 'rock' } ) ; 筆記
GCP啟動環境中的索引不支持名稱空間。
要核定目標名稱空間中的所有內容,請使用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推斷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操作和工作流程配置。
有關更多信息,請參見貢獻。