Similarity Search

A VECTOR field is searched with $neighbors or $direction in a normal filter. Results come closest first, unless the query has a sort. The query vector must have the field's dimensions.

$neighbors: the nearest vectors

const similar = await productModel.find([
  { embedding: { $neighbors: { vector: queryEmbedding, count: 10, metric: 'cosine' } } },
]);
OptionValueNotes
vectorarray of numbers, requiredSame length as the field's dimensions
countpositive integer, default 10How many nearest documents to return
metric'euclidean' (default), 'cosine', 'dot'See metrics
maxDistancenumber >= 0Only documents at most this far away (euclidean and cosine; ignored for dot)

$direction: pointing the same way

Finds every vector whose cosine similarity with vector is at least minSimilarity, most similar first. Use it when you want "everything similar enough" rather than a fixed number of results.

const related = await articleModel.find([
  { embedding: { $direction: { vector: questionEmbedding, minSimilarity: 0.8, count: 50 } } },
]);
OptionValueNotes
vectorarray of numbers, requiredSame length as the field's dimensions
minSimilaritynumber from -1 to 1, required1: same direction, 0: unrelated, -1: opposite
countpositive integerKeep only the most similar ones

A vector of zeros has no direction: it never matches $direction or cosine $neighbors.

Metrics

MetricClosest meansUse it when
euclideansmallest straight-line distanceThe values are measurements (coordinates, features) where the size of the vector matters
cosinesmallest 1 - cosine similarity (only the direction counts)Text and image embeddings: the usual choice
dothighest dot product The model is trained for dot product, or the vectors are normalized and you want the cheapest metric

For normalized vectors (length 1, which most embedding models return or can return) all three metrics give the same order.

Combining with other filters

Other fields in the same filter narrow the similarity result: the nearest count documents are found first, then those that don't match the other fields are dropped. Ask for a larger count when the other filters are selective.

// of the 50 nearest products, those in "shoes" that are in stock, closest first
await productModel.find([
  {
    embedding: { $neighbors: { vector: queryEmbedding, count: 50 } },
    category: 'shoes',
    stock: { $gt: 0 },
  },
]);
  • Several filters in the array are combined with OR, as everywhere in DianaDB: the results of the first filter come first, in its own order, then those of the next one.
  • $neighbors and $direction in one condition: documents matching both.
  • A sort replaces the similarity order; skip and limit apply after it.