이것은 TypeScript로 작성된 Pinecone 용 공식 Node.js SDK입니다.
v0.x 에서 업그레이드하는 경우 V1 마이그레이션 안내서를 확인하십시오.v1.x 에서 업그레이드하는 경우 V2 마이그레이션 안내서를 확인하십시오.이 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
PENECONE TYPESCRICT 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-ADA-002 모델로 생성 된 쿼리 임베딩 (벡터)을 저장하고 쿼리 임베딩 (벡터)을 저장하려는 경우 해당 모델의 출력과 일치하는 Dimension 1536 의 색인을 작성해야합니다.
spec 인덱스를 배포하는 방법을 구성합니다. 서버리스 인덱스의 경우 인덱스를 호스팅 해야하는 클라우드와 영역 만 정의합니다. 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' } ,
} ) ; 포드 기반 색인을 만들려면 인덱스가 호스팅되어야하는 environment 포함 된 spec 객체와 사용할 podType 및 pods 크기가 포함 된 pod 정의합니다. 많은 선택적 구성 필드를 통해 하드웨어 리소스 및 가용성을 더 잘 제어 할 수 있습니다. 이러한 필드의 목적에 대한 자세한 내용은 인덱스 이해 및 척도 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 으로 서버리스 및 포드 인덱스를 모두 구성 할 수 있습니다. 이 속성이 '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'
// }
// }메모
이 섹션은 POD 기반 인덱스에만 적용됩니다. 서버리스 인덱스를 사용하면 컴퓨팅 또는 스토리지 리소스를 구성하지 않습니다. 대신 서버리스 인덱스는 사용량에 따라 자동으로 스케일입니다.
복제본 또는 스케일의 수를 더 큰 포드 크기 ( 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',
// },
// },
// ],
// } 메모
서버리스 및 스타터 인덱스는 컬렉션을 지원하지 않습니다.
컬렉션은 백업을 생성하거나 인덱스 사본을 생성하거나 다른 인덱스 구성으로 실험을 수행하는 데 사용될 수있는 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 Indexes는 Upsert, Query, Fetch 및 Delete와 같은 작업을 사용하여 벡터 데이터 작업을위한 작업을 지원합니다.
인덱스에서 데이터 작업을 수행하려면 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 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' ] ) ; 벡터 값과 함께 메타 데이터를 저장하는 경우 적절한 TypeScript를 얻으려면 유형 매개 변수를 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 ;
} ;일부 벡터를 업시하려면 다음과 같은 클라이언트를 사용할 수 있습니다.
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 Index로 가져 오는 장기적으로 실행되는 비동기 조작입니다.
객체 스토리지에서 벡터를 가져 오려면 Parquet 파일에 저장되고 필요한 파일 형식을 준수해야합니다. 객체 저장소는 필요한 디렉토리 구조를 준수해야합니다.
다음 예제는 Amazon 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"
// }전체 또는 하나의 가져 오기 작업의 상태를 시작, 취소 및 확인할 수 있습니다.
참고 :
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 파라를 전달합니다. Brevity Sake이 예제 Query 벡터는 작지만 (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 지정하지 않으면 기본 접두사는 빈 문자열이며 인덱스의 모든 벡터 ID를 반환합니다.limit 지정되지 않은 경우 100 벡터 ID의 단단한 제한이 있습니다. 결과적으로 인덱스에 주어진 prefix 와 일치하는 벡터 ID가 100 미만이고 limit 지정하지 않으면 paginationToken 이 undefined 되지 않습니다. 다음 예제는 3 의 limit 4 벡터로 뭉친 것으로 가정 할 때 접두사 doc1 doc1# 포함하는 벡터 ID의 두 페이지를 벡터 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' ] ) ; 편의를 위해 몇 가지 삭제 관련 방법이 있습니다. 레코드를 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 (현재 공개 미리보기)와 상호 작용하십시오. PENECONE 추론 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에서 자동으로 이루어 지며이 repo의 .github 디렉토리에있는 GitHub 동작 및 워크 플로를 사용하여 구성됩니다.
자세한 내용은 Contributing.md를 참조하십시오.