Back to roadmaps pinecone Course

Executing Similarity Queries in Pinecone

To perform a search, query Pinecone using a search vector. Pinecone will calculate similarity scores and return the closest vector records.


1. Querying the Vector Index

Use the .query() method on the index client instance. Specify the search vector, the number of results to return (topK), and option flags:

import { pc } from "../lib/pinecone";

async function runSemanticSearch(searchVector: number[]) {
  const index = pc.index("knowledge-base");

  const queryResponse = await index.query({
    vector: searchVector,
    topK: 3, // Return top 3 closest matches
    includeValues: false, // Save bandwidth by excluding vector value arrays
    includeMetadata: true, // Include the metadata object (e.g. text content)
  });

  console.log("Found matches:");
  queryResponse.matches?.forEach((match) => {
    console.log(`ID: ${match.id}`);
    console.log(`Score: ${match.score}`); // Cosine similarity score (closer to 1 is better)
    console.log(`Metadata:`, match.metadata);
  });

  return queryResponse.matches;
}

2. Reading the Query Results

The response contains a list of match objects. Each match contains:

  • id: The primary key string of the matching vector.
  • score: The similarity calculation score (based on the distance metric defined in the index, e.g. cosine).
  • metadata: The JSON metadata object associated with the vector row.
  • values: The array of vector numbers (only returned if includeValues was set to true).
Published on Last updated: