هذا هو Node.js SDK الرسمي لـ Pinecone ، مكتوب في TypeScript.
v0.x ، تحقق من دليل الترحيل V1 .v1.x ، تحقق من دليل ترحيل V2 .المقتطفات الموضحة في هذه القراءة تهدف إلى أن تكون موجزة. للحصول على أمثلة أكثر واقعية ، استكشف هذه الأمثلة:
2.x إلى 3.x هناك تغيير كسر يتضمن عملية configureIndex في هذا التحديث. تم تغيير هيكل الكائن الذي تم تمريره عند تكوين فهرس ليشمل deletionProtection . يمكن الآن تحديث حقول podType و replicas من خلال كائن spec.pod . انظر تكوين الفهارس المستندة إلى POD للحصول على مثال على الرمز.
2.x : كان هناك العديد من التغييرات التي تم إجراؤها في هذا الإصدار لدعم عرض فهرس Pinecone الجديد بدون خادم. يتم تغطية التغييرات بالتفصيل في دليل ترحيل V2 . تتوفر فهارس الخوادم فقط في إصدارات الإصدار 2.x أو أكبر.1.x : قام هذا الإصدار رسميًا بنقل SDK من الإصدار التجريبي ، وهناك عدد من التغييرات المكسورة التي يجب معالجتها عند الترقية من إصدار 0.x انظر دليل الترحيل V1 للحصول على التفاصيل. يتوافق Pinecone TypeScript SDK مع TypeScript> = 4.1 و Node> = 18.x.
npm install @pinecone-database/pinecone
يهدف Pinecone TypeScript SDK للاستخدام من جانب الخادم فقط . يمكن أن يؤدي استخدام SDK داخل سياق المتصفح إلى فضح مفتاح (مفتاح) API . إذا قمت بنشر SDK على الإنتاج في متصفح ، فيرجى تدوير مفاتيح API.
مطلوب مفتاح API لتهيئة العميل. يمكن تمريره باستخدام متغير البيئة أو في الكود من خلال كائن التكوين. احصل على مفتاح API في وحدة التحكم.
متغير البيئة المستخدم لتكوين مفتاح API للعميل هو ما يلي:
PINECONE_API_KEY= " your_api_key " PINECONE_API_KEY هو المتغير الوحيد المطلوب. عندما يتم تعيين متغير البيئة هذا ، لا يتطلب مُنشئ العميل أي وسيطات إضافية.
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ; إذا كنت تفضل تمرير التكوين في التعليمات البرمجية ، يقبل المُنشئ كائن تكوين يحتوي على قيمة apiKey . هذا هو الكائن الذي تقوم فيه بتمرير خصائص مثل maxRetries (الافتراضيات إلى 3 ) للعمليات القابلة لإعادة المحاولة ( upsert ، update ، و configureIndex ).
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( {
apiKey : 'your_api_key' ,
maxRetries : 5 ,
} ) ; إذا كان إعداد شبكتك يتطلب منك التفاعل مع Pinecone عبر وكيل ، فيمكنك تمرير ProxyAgent مخصص من مكتبة undici . فيما يلي مثال على كيفية إنشاء ProxyAgent undici الذي يوجه حركة مرور الشبكة من خلال خادم وكيل mitm أثناء ضرب نقطة نهاية Pinecone /indexes .
ملاحظة: تعتمد الاستراتيجية التالية على تطبيق fetch الأصلي للعقدة ، الذي تم إصداره في العقدة V16 واستقر في العقدة V21. إذا كنت تقوم بتشغيل إصدارات العقدة 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 -AD-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 ، يمكنك تحديد pod في كائن spec الذي يحتوي على environment التي يجب استضافة الفهرس ، وحجم podType و pods للاستخدام. تتيح العديد من حقول التكوين الاختيارية تحكمًا أكبر في موارد الأجهزة وتوافرها. لمعرفة المزيد حول الغرض من هذه الحقول ، راجع فهم الفهارس والفهجة المستندة إلى جراب النطاق.
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 طلب إنشاء إلى واجهة برمجة التطبيقات التي تُرجع بسرعة ، ولكن الفهرس الناتج غير جاهز على الفور لتربية عمليات البيانات أو الاستعلام عنها أو تنفيذها. يمكنك استخدام طريقة 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 ,
} ) ; ملحوظة
فهارس Serverless و Starter لا تدعم المجموعات.
أثناء استخدامك 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
// } يمكنك تكوين كل من فهارس Serverless و POD مع deletionProtection . لن يتمكن أي فهرس مع هذه الخاصية التي تم تعيينها على 'enabled' من حذفها. افتراضيًا ، سيتم تعيين deletionProtection على 'disabled' إذا لم يتم توفيره كجزء من طلب createIndex . لتمكين 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' ,
} ) ; يمكنك إنشاء أو تكوين فهارس Serverless و 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 فقط. مع فهارس الخادم ، لا تقوم بتكوين أي موارد حسابية أو تخزين. بدلاً من ذلك ، مقياس الفهارس بدون خادم بناءً على الاستخدام تلقائيًا.
يمكنك ضبط عدد النسخ المتماثلة أو المقياس إلى حجم جراب أكبر (محدد مع 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',
// },
// },
// ],
// } ملحوظة
فهارس Serverless و Starter لا تدعم المجموعات.
المجموعة هي نسخة ثابتة من فهرس يستند إلى 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() من أجل الحصول على typeChecking 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 عملية طويلة الأمد غير متزامنة تستورد أعدادًا كبيرة من السجلات إلى فهرس بدون خادم pinecone.
من أجل استيراد المتجهات من تخزين الكائنات ، يجب تخزينها في ملفات 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 في تكوين الخيارات. من أجل الإيجاز ، يكون هذا المثال متجه الاستعلام صغيرًا (البعد 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 ] } ) ; يمكنك الاستعلام باستخدام قيم المتجهات لسجل موجود في الفهرس عن طريق تمرير معرف السجل. يرجى ملاحظة أن السجل مع المعرف المحدد قد يكون في استجابة هذه العملية.
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 . حدد المعرف وقيمة السمة التي تريد تحديثها.
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 لإدراج معرفات السجل التي تطابق بادئة معرف معينة بتنسيق متصفح. مع تعيين ذكي لمعرفات السجلات ، يمكن استخدام هذا للمساعدة في تصميم العلاقات الهرمية بين السجلات المختلفة مثل عندما تكون هناك تضمينات لقطع أو شظايا متعددة تتعلق بنفس المستند.
ملحوظات:
prefix ، فإن البادئة الافتراضية هي سلسلة فارغة ، والتي تُرجع جميع معرفات المتجه في الفهرس100 معرفات متجه إذا لم يتم تحديد limit . وبالتالي ، إذا كان هناك أقل من 100 معرفات متجه تتطابق مع prefix معينة في الفهرس الخاص بك ، ولم تحدد limit ، فسيكون paginationToken undefined يوضح المثال التالي كيفية إحضار كلا صفحتين من معرفات المتجهات للمتجهات التي تحتوي معرفاتها على Prefix doc1# ، على افتراض وجود 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-Starter لا تدعم مساحات الأسماء.
لتشويه كل شيء في مساحة الاسم المستهدفة ، استخدم طريقة deleteAll .
import { Pinecone } from '@pinecone-database/pinecone' ;
const pc = new Pinecone ( ) ;
const index = pc . index ( 'my-index' ) ;
await index . namespace ( 'foo-namespace' ) . deleteAll ( ) ; إذا لم تحدد مساحة اسم ، فسيتم حذف السجلات الموجودة في مساحة الاسم الافتراضية '' .
التفاعل مع API استدلال Pinecone (حاليًا في المعاينة العامة). API Pinecone Inference API هي خدمة تتيح لك الوصول إلى نماذج الاستدلال المستضافة على البنية التحتية لـ Pinecone.
ملحوظات:
النماذج المدعومة:
أرسل نصًا إلى واجهة برمجة تطبيقات استدلال Pinecone لإنشاء تضمينات للوثائق والاستعلامات.
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 >> توثيق Rerank في ترتيب الأهمية ضد الاستعلام.
ملاحظة: تمثل 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 لهذا الريبو.
انظر المساهمة. md لمزيد من المعلومات.