这是用打字稿编写的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操作和工作流程配置。
有关更多信息,请参见贡献。