Working with Node.js Client
1. Installing Node.js SDK
| Step | Command |
|---|---|
| Install | npm install @pinecone-database/pinecone |
| Node version | ≥ 20 LTS |
| TypeScript | Types included |
2. Initializing Pinecone
Example: Init
import { Pinecone } from "@pinecone-database/pinecone";
const pc = new Pinecone({ apiKey: process.env.PINECONE_API_KEY! });
const index = pc.index("products");
3. Using Promises
Example: async/await
const res = await index.query({
vector: qv,
topK: 10,
includeMetadata: true,
});
console.log(res.matches);
4. Implementing Error Handling
Example: Try/Catch
import { PineconeNotFoundError } from "@pinecone-database/pinecone";
try {
await index.upsert(vectors);
} catch (err) {
if (err instanceof PineconeNotFoundError) console.error("Index missing");
else throw err;
}
| Error | Cause |
|---|---|
PineconeNotFoundError | Index not found |
PineconeAuthorizationError | Bad API key |
PineconeBadRequestError | Invalid input |
PineconeInternalServerError | 5xx |
5. Using TypeScript Types
Example: Typed Metadata
type DocMeta = { source: string; page: number; tags: string[] };
const index = pc.index<DocMeta>("products");
await index.upsert([{ id: "1", values: dense,
metadata: { source: "wiki", page: 1, tags: ["ml"] } }]);
6. Implementing Streaming Operations
Example: Stream IDs
// listPaginated for serverless
let next: string | undefined;
do {
const page = await index.listPaginated({ limit: 100, paginationToken: next });
for (const v of page.vectors ?? []) console.log(v.id);
next = page.pagination?.next;
} while (next);
7. Implementing Batch Processing
Example: Chunked Upsert
const chunkSize = 100;
for (let i = 0; i < vectors.length; i += chunkSize) {
await index.upsert(vectors.slice(i, i + chunkSize));
}
8. Managing Connection Lifecycle
| Pattern | Detail |
|---|---|
| Singleton client | One new Pinecone(...) per process |
| Index handle | Cheap; reuse OK |
| No explicit close | HTTP keep-alive managed |
9. Optimizing Node.js Performance
| Tip | Effect |
|---|---|
| Promise.all batches | Parallel upserts |
| HTTP keep-alive | Reuse TCP connections |
| Stream large reads | listPaginated |
| Avoid blocking event loop | Offload CPU work to workers |
10. Integrating with Express and Fastify
Example: Express Route
import express from "express";
import { Pinecone } from "@pinecone-database/pinecone";
const app = express();
const pc = new Pinecone({ apiKey: process.env.PINECONE_API_KEY! });
const index = pc.index("products");
app.post("/search", express.json(), async (req, res) => {
const result = await index.query({
vector: req.body.vector,
topK: 10,
includeMetadata: true,
});
res.json(result.matches);
});
app.listen(3000);