Skip to main content
The query method is designed to retrieve the most similar vectors from the index, using the specific distance metric defined for your index. This method supports a variety of options to configure the query to your needs.
The dimension of the query vector must match the dimension of your index.
The score returned from query requests is a normalized value between 0 and 1, where 1 indicates the highest similarity and 0 the lowest regardless of the similarity function used.

Arguments

Payload
QueryCommandPayload
required
Options
QueryCommandOptions

Response

Response
QueryResult
required
await index.query({
  topK: 2,
  vector: [ ... ],
  includeMetadata: true,
  includeVectors: true
}, { namespace: "my-namespace" })
/*
[
  {
    id: '6345',
    score: 0.85,
    vector: [],
    metadata: {
      sentence: "Upstash is great."
    }
  },
  {
    id: '1233',
    score: 0.75,
    vector: [],
    metadata: undefined
  },
]
*/
const results = await index.query({
  data: "Movie about an adventure of a hobbit in a fantasy world.",
  includeVectors: true,
  includeMetadata: true,
  topK: 1,
  filter: "genre = 'fantasy' and title = 'Lord of the Rings'",
});
/*
[
  {
    id: "1234",
    vector: [0.1, 0.2, 0.3, 0.4, 0.5],
    score: 0.9999999,
    metadata: {
      title: "Lord of The Rings",
      genre: "fantasy",
      category: "classic",
    },
  }
]
*/
type Metadata = {
  title: string,
  genre: 'sci-fi' | 'fantasy' | 'horror' | 'action'
}

const results = await index.query<Metadata>({
  vector: [
    ... // query embedding
  ],
  includeVectors: true,
  topK: 1,
  filter: "genre = 'fantasy' and title = 'Lord of the Rings'"
})

if (results[0].metadata) {
  // Since we passed the Metadata type parameter above,
  // we can interact with metadata fields without having to
  // do any typecasting.
  const { title, genre } = results[0].metadata;
  console.log(`The best match in fantasy was ${title}`)
}