Ini adalah Node.js SDK resmi untuk Pinecone, ditulis dalam TypeScript.
v0.x , lihat Panduan Migrasi V1 .v1.x , lihat Panduan Migrasi V2 .Cuplikan yang ditunjukkan dalam readme ini dimaksudkan untuk menjadi ringkas. Untuk contoh yang lebih realistis, jelajahi contoh -contoh ini:
2.x ke 3.x Ada perubahan besar yang melibatkan operasi configureIndex dalam pembaruan ini. Struktur objek yang dilewati saat mengonfigurasi indeks telah berubah untuk memasukkan deletionProtection . Bidang podType dan replicas sekarang dapat diperbarui melalui objek spec.pod . Lihat Konfigurasikan indeks berbasis pod untuk contoh kode.
2.x : Ada banyak perubahan yang dibuat dalam rilis ini untuk mendukung penawaran indeks serverless baru Pinecone. Perubahan dibahas secara rinci dalam Panduan Migrasi V2 . Indeks tanpa server hanya tersedia dalam versi rilis 2.x atau lebih besar.1.x : Rilis ini secara resmi memindahkan SDK dari beta, dan ada sejumlah perubahan yang perlu ditangani saat meningkatkan dari versi 0.x Lihat Panduan Migrasi V1 untuk detailnya. Pinecone TypeScript SDK kompatibel dengan TypeScript> = 4.1 dan node> = 18.x.
npm install @pinecone-database/pinecone
Pinecone TypeScript SDK dimaksudkan hanya untuk penggunaan sisi server . Menggunakan SDK dalam konteks browser dapat mengekspos kunci API Anda . Jika Anda telah menggunakan SDK ke produksi di browser, silakan putar kunci API Anda.
Kunci API diperlukan untuk menginisialisasi klien. Ini dapat dilewatkan menggunakan variabel lingkungan atau dalam kode melalui objek konfigurasi. Dapatkan kunci API di konsol.
Variabel lingkungan yang digunakan untuk mengonfigurasi kunci API untuk klien adalah sebagai berikut:
PINECONE_API_KEY= " your_api_key " PINECONE_API_KEY adalah satu -satunya variabel yang diperlukan. Ketika variabel lingkungan ini ditetapkan, konstruktor klien tidak memerlukan argumen tambahan.
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ; Jika Anda lebih suka meneruskan konfigurasi dalam kode, konstruktor menerima objek konfigurasi yang berisi nilai apiKey . Ini adalah objek di mana Anda akan melewati properti seperti maxRetries (default ke 3 ) untuk operasi yang dapat dikembalikan ( upsert , update , dan configureIndex ).
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( {
apiKey : 'your_api_key' ,
maxRetries : 5 ,
} ) ; Jika pengaturan jaringan Anda mengharuskan Anda untuk berinteraksi dengan Pinecone melalui proxy, Anda dapat melewati ProxyAgent khusus dari perpustakaan undici . Di bawah ini adalah contoh cara membangun ProxyAgent undici yang merutekan lalu lintas jaringan melalui server proxy mitm sambil memukul titik akhir Pinecone /indexes .
Catatan: Strategi berikut bergantung pada implementasi fetch asli Node, dirilis dalam Node V16 dan distabilkan dalam Node V21. Jika Anda menjalankan versi Node 18-21, Anda mungkin mengalami masalah yang berasal dari ketidakstabilan fitur. Saat ini tidak ada masalah yang diketahui terkait dengan proksi di Node 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 ) ;
} ) ; Minimal, untuk membuat indeks tanpa server, Anda harus menentukan name , dimension , dan spec . dimension menunjukkan ukuran vektor yang ingin Anda simpan dalam indeks. Misalnya, jika niat Anda adalah untuk menyimpan dan menanyakan embeddings (vektor) yang dihasilkan dengan model openai Textembedding-002, Anda perlu membuat indeks dengan dimensi 1536 agar sesuai dengan output model itu.
spec mengkonfigurasi bagaimana indeks harus digunakan. Untuk indeks tanpa server, Anda hanya mendefinisikan cloud dan wilayah di mana indeks harus di -host. Untuk indeks berbasis pod, Anda mendefinisikan lingkungan di mana indeks harus di-host, jenis dan ukuran pod untuk digunakan, dan karakteristik indeks lainnya. Untuk informasi lebih lanjut tentang ketersediaan tanpa server dan regional, lihat indeks pemahaman.
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' } ,
} ) ; Untuk membuat indeks berbasis pod, Anda mendefinisikan pod dalam objek spec yang berisi environment di mana indeks harus di-host, dan ukuran podType dan pods untuk digunakan. Banyak bidang konfigurasi opsional memungkinkan kontrol yang lebih besar atas sumber daya dan ketersediaan perangkat keras. Untuk mempelajari lebih lanjut tentang tujuan bidang-bidang ini, lihat pemahaman indeks dan skala indeks berbasis 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 ,
} ) ; Metode createIndex mengeluarkan permintaan Buat ke API yang kembali dengan cepat, tetapi indeks yang dihasilkan tidak segera siap untuk meningkatkan, menanyakan, atau melakukan operasi data lainnya. Anda dapat menggunakan metode describeIndex untuk mengetahui status indeks dan melihat apakah itu siap digunakan.
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'
// }
// } Jika Anda lulus opsi waitUntilReady , klien akan menangani polling untuk pembaruan status pada indeks yang baru dibuat. Janji yang dikembalikan oleh createIndex tidak akan diselesaikan sampai status indeks menunjukkan siap untuk menangani operasi data. Ini dapat sangat berguna untuk pengujian integrasi, di mana pembuatan indeks dalam langkah pengaturan akan segera diikuti oleh operasi data.
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 ,
} ) ; Catatan
Indeks tanpa server dan starter tidak mendukung koleksi.
Saat Anda menggunakan Pinecone untuk lebih banyak hal, Anda mungkin ingin menjelajahi konfigurasi indeks yang berbeda dengan data vektor yang sama. Koleksi menyediakan cara mudah untuk melakukan ini. Lihat metode klien lain untuk bekerja dengan koleksi di sini.
Mengingat bahwa Anda memiliki koleksi yang ada:
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'
// } Catatan: Untuk indeks berbasis pod, Anda dapat menentukan penagihan sourceCollection untuk membuat indeks. Koleksi harus berada di lingkungan yang sama dengan indeks.
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' ,
} ,
} ,
} ) ;Ketika indeks baru siap, itu harus berisi semua data yang ada dalam pengumpulan, siap untuk ditanya.
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
// } Anda dapat mengonfigurasi indeks tanpa server dan pod dengan deletionProtection . Indeks apa pun dengan properti ini diatur ke 'enabled' tidak akan dapat dihapus. Secara default, deletionProtection akan diatur untuk 'disabled' jika tidak disediakan sebagai bagian dari permintaan createIndex . Untuk mengaktifkan deletionProtection Anda dapat memberikan nilainya saat memanggil 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' ,
} ,
} ,
} ) ; Untuk menonaktifkan perlindungan penghapusan, Anda dapat menggunakan operasi configureIndex .
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . configureIndex ( 'deletion-protected-index' , {
deletionProtection : 'disabled' ,
} ) ; Anda dapat membuat atau mengonfigurasi indeks serverless dan pod dengan tag. Indeks dapat memegang jumlah tag yang sewenang -wenang yang menguraikan metadata yang ingin Anda lampirkan pada objek indeks itu sendiri, seperti kepemilikan tim, proyek, atau informasi lain yang relevan.
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
} ) ; Anda dapat mengambil deskripsi indeks apa pun dengan nama menggunakan 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'
// }
// }Catatan
Bagian ini hanya berlaku untuk indeks berbasis pod. Dengan indeks tanpa server, Anda tidak mengkonfigurasi sumber daya komputasi atau penyimpanan. Sebaliknya, skala indeks tanpa server secara otomatis berdasarkan penggunaan.
Anda dapat menyesuaikan jumlah replika atau skala ke ukuran pod yang lebih besar (ditentukan dengan podType ). Lihat indeks berbasis pod skala. Anda tidak dapat menurunkan ukuran pod atau mengubah jenis pod dasar.
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'
// }
// }Indeks dihapus berdasarkan nama.
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . deleteIndex ( 'sample-index' ) ; Perintah listIndexes mengembalikan objek dengan array model indeks di bawah 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',
// },
// },
// ],
// } Catatan
Indeks tanpa server dan starter tidak mendukung koleksi.
Koleksi adalah salinan statis dari indeks berbasis pod yang dapat digunakan untuk membuat cadangan, untuk membuat salinan indeks, atau untuk melakukan percobaan dengan konfigurasi indeks yang berbeda. Untuk mempelajari lebih lanjut tentang koleksi Pinecone, lihat pemahaman koleksi.
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . createCollection ( {
name : 'collection-name' ,
source : 'index-name' ,
} ) ; Panggilan API ini harus kembali dengan cepat, tetapi pembuatan koleksi dapat memakan waktu dari menit ke jam tergantung pada ukuran indeks sumber dan konfigurasi indeks. Gunakan describeCollection untuk memeriksa status koleksi.
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
await pc . deleteCollection ( 'collection-name' ) ; Anda dapat menggunakan listCollections untuk mengonfirmasi penghapusan.
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',
// } Perintah listCollections mengembalikan objek dengan serangkaian model koleksi di bawah 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',
// },
// ];
// } Indeks Pinecone mendukung operasi untuk bekerja dengan data vektor menggunakan operasi seperti Upsert, Query, Fetch, dan Delete.
Untuk melakukan operasi data pada indeks, Anda menargetkannya menggunakan metode 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' ] ) ; Argumen pertama adalah nama indeks yang Anda targetkan. Ada argumen kedua opsional untuk memberikan override host indeks. Memberikan argumen kedua ini memungkinkan Anda untuk melewati perilaku default SDK untuk menyelesaikan host indeks Anda melalui nama indeks yang disediakan. Anda dapat menemukan host indeks Anda di Pinecone Console, atau dengan menggunakan Operasi describeIndex atau 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' ] ) ; Jika Anda menyimpan metadata di samping nilai vektor Anda, Anda dapat meneruskan parameter tipe ke index() untuk mendapatkan typeChecking TypeCript yang tepat.
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 } ` )
} Secara default, semua operasi data terjadi di dalam namespace default '' . Jika Anda bekerja dengan ruang nama non-default lainnya, Anda dapat menargetkan namespace dengan merantai panggilan ke 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' ] ) ;Lihat Gunakan ruang nama untuk informasi lebih lanjut.
Pinecone mengharapkan catatan yang dimasukkan ke dalam indeks memiliki formulir berikut:
type PineconeRecord = {
id : string ;
values : Array < number > ;
sparseValues ?: Array < number > ;
metadata ?: object ;
} ;Untuk meningkatkan beberapa vektor, Anda dapat menggunakan klien seperti itu:
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 ) ; Anda sekarang dapat mengimpor vektor secara massal dari penyimpanan objek. Import adalah operasi yang sudah berjalan lama dan asinkron yang mengimpor sejumlah besar catatan ke dalam indeks server tanpa pinus.
Untuk mengimpor vektor dari penyimpanan objek, mereka harus disimpan dalam file parket dan mematuhi format file yang diperlukan. Penyimpanan objek Anda juga harus mematuhi struktur direktori yang diperlukan.
Contoh berikut mengimpor vektor dari ember Amazon S3 ke dalam indeks server tanpa pinus:
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"
// }Anda dapat memulai, membatalkan, dan memeriksa status semua atau satu operasi impor.
Catatan:
Import hanya berfungsi dengan indeks tanpa serverImport dalam pratinjau publik Saat bereksperimen dengan operasi data, kadang -kadang bermanfaat untuk mengetahui berapa banyak catatan/vektor yang disimpan di setiap namespace. Dalam hal ini, targetkan indeks dan gunakan perintah 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
// }Metode kueri menerima sejumlah besar opsi. Dimensi vektor kueri harus cocok dengan dimensi indeks Anda.
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 ;
} ; Misalnya, untuk meminta nilai vektor Anda akan melewati param vector dalam konfigurasi opsi. Demi singkatnya contoh ini vektor kueri kecil (dimensi 2), tetapi dalam kasus penggunaan yang lebih realistis, vektor kueri ini akan menjadi embedding yang dikeluarkan oleh model. Lihatlah kode contoh untuk melihat contoh yang lebih realistis tentang cara menggunakan 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
// }
// } Anda menyertakan opsi untuk includeMetadata: true atau includeValues: true jika Anda memerlukan informasi ini. Secara default, ini tidak dikembalikan untuk menjaga muatan tanggapan kecil.
Ingatlah bahwa operasi data terjadi dalam konteks namespace , jadi jika Anda bekerja dengan ruang nama dan tidak melihat hasil yang diharapkan, Anda harus memeriksa apakah Anda menargetkan namespace yang benar dengan kueri Anda.
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 ] } ) ; Anda dapat meminta menggunakan nilai vektor dari catatan yang ada dalam indeks dengan melewati ID rekaman. Harap dicatat bahwa catatan dengan ID yang ditentukan mungkin ada dalam tanggapan operasi ini.
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' } ) ; Jika Anda bekerja dengan vektor padat yang jarang, Anda dapat menambahkan nilai vektor yang jarang untuk melakukan pencarian hibrida.
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 ,
} ) ; Anda mungkin ingin memperbarui values vektor, sparseValues , atau metadata . Tentukan ID dan nilai atribut yang ingin Anda perbarui.
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'imdb-movies' ) ;
await index . update ( {
id : '18593' ,
metadata : { genre : 'romance' } ,
} ) ; Metode listPaginated dapat digunakan untuk mendaftar ID rekaman yang cocok dengan awalan ID tertentu dalam format paginasi. Dengan penugasan yang cerdas dari ID catatan, ini dapat digunakan untuk membantu memodelkan hubungan hierarkis antara catatan yang berbeda seperti ketika ada embedding untuk beberapa potongan atau fragmen yang terkait dengan dokumen yang sama.
Catatan:
prefix , awalan default adalah string kosong, yang mengembalikan semua ID vektor dalam indeks Anda100 ID vektor jika tidak ada limit yang ditentukan. Akibatnya, jika ada kurang dari 100 ID vektor yang cocok dengan prefix yang diberikan dalam indeks Anda, dan Anda tidak menentukan limit , paginationToken Anda tidak akan undefined Contoh berikut menunjukkan cara mengambil kedua halaman ID vektor untuk vektor yang IDnya berisi awalan doc1# , dengan asumsi limit 3 dan dokumen doc1 dipotong menjadi 4 vektor.
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' ] ) ; Untuk kenyamanan ada beberapa metode yang berhubungan dengan penghapusan. Anda dapat memverifikasi hasil operasi penghapusan dengan mencoba fetch() catatan atau melihat ringkasan indeks dengan 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' ] ) ;Catatan: Penghapusan dengan filter metadata hanya berlaku untuk indeks berbasis pod.
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'albums-database' ) ;
await index . deleteMany ( { genre : 'rock' } ) ; CATATAN
Indeks di lingkungan GCP-starter tidak mendukung ruang nama.
Untuk nuklir semuanya dalam namespace yang ditargetkan, gunakan metode deleteAll .
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'my-index' ) ;
await index . namespace ( 'foo-namespace' ) . deleteAll ( ) ; Jika Anda tidak menentukan namespace, catatan di namespace default '' akan dihapus.
Berinteraksi dengan Pinecone's Inference API (saat ini dalam pratinjau publik). Pinecone Inference API adalah layanan yang memberi Anda akses ke model inferensi yang dihosting pada infrastruktur Pinecone.
Catatan:
Model yang Didukung:
Kirim teks ke API inferensi Pinecone untuk menghasilkan embeddings untuk dokumen dan pertanyaan.
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 >> Dokumen rerank dalam descending relevance-order terhadap kueri.
Catatan: score tersebut merupakan ukuran absolut relevansi dari kueri dan pasangan yang diberikan. Dinormalisasi antara [0, 1], score tersebut mewakili seberapa dekat item dan kueri tertentu, dengan skor lebih dekat ke 1 menunjukkan relevansi yang lebih tinggi.
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 }
//} Semua pengujian berlangsung secara otomatis di CI dan dikonfigurasi menggunakan tindakan dan alur kerja GitHub, yang terletak di direktori .github repo ini.
Lihat Kontribusi.MD untuk informasi lebih lanjut.