Prerequisites

  • Sign up for a Pinecone account at Pinecone.io.
  • Get your Pinecone API key from the Pinecone dashboard.

Setup

  1. Add your Pinecone API key to the .env file.
.env
PINECONE_API_KEY=your-pinecone-api-key
  1. The boilerplate already includes the necessary configuration for Pinecone in src/lib/ai/pinecone.ts. This file initializes the Pinecone client.

Usage

To use Pinecone in your application, you can create an API route that interacts with the Pinecone vector database. Here’s an example of how to set up a route that uses Pinecone for similarity search:

import { kv } from '@vercel/kv';
import { pc } from '@/lib/ai/pinecone';
import { Ratelimit } from '@upstash/ratelimit';
import { NextRequest, NextResponse } from 'next/server';
// Allow responses up to 30 seconds
export const maxDuration = 30;

// Create Rate limit
const ratelimit = new Ratelimit({
    redis: kv,
    limiter: Ratelimit.fixedWindow(5, '30s'),
});

export async function POST(req: NextRequest) {
    // call ratelimit with request ip
    const { success, remaining } = await ratelimit.limit(req.ip ?? 'ip');

    // block the request if unsuccessful
    if (!success) return new Response('Rate limit exceeded', { status: 429 });

    const { vector, topK } = await req.json();

    try {
        // Assuming you have an index named 'my-index'
        const index = pc.Index(process.env.PINECONE_INDEX);

        const queryResponse = await index.query({
            vector,
            topK,
            includeMetadata: true,
        });

        return NextResponse.json({ results: queryResponse.matches });
    } catch (error) {
        console.error('Error querying Pinecone:', error);
        return NextResponse.json({ error: 'Failed to query Pinecone' }, { status: 500 });
    }
}

Common Operations

Pinecone offers various features for vector database management. Here are a few examples:

Upserting Vectors

const index = pc.Index(process.env.PINECONE_INDEX);

await index.upsert([
  {
    id: 'vec1',
    values: [0.1, 0.2, 0.3, 0.4, 0.5],
    metadata: { text: 'This is a sample vector' }
  },
  // Add more vectors as needed
]);

Deleting Vectors

const index = pc.Index(process.env.PINECONE_INDEX);

await index.deleteOne('vec1');
// Or delete multiple vectors
// await index.deleteMany(['vec1', 'vec2', 'vec3']);

Fetching Vectors

const index = pc.Index(process.env.PINECONE_INDEX);

const fetchResponse = await index.fetch(['vec1', 'vec2']);
console.log(fetchResponse.vectors);

Was this page helpful?