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' } } },
]);| Option | Value | Notes |
|---|---|---|
vector | array of numbers, required | Same length as the field's dimensions |
count | positive integer, default 10 | How many nearest documents to return |
metric | 'euclidean' (default), 'cosine', 'dot' | See metrics |
maxDistance | number >= 0 | Only 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 } } },
]);| Option | Value | Notes |
|---|---|---|
vector | array of numbers, required | Same length as the field's dimensions |
minSimilarity | number from -1 to 1, required | 1: same direction, 0: unrelated, -1: opposite |
count | positive integer | Keep only the most similar ones |
A vector of zeros has no direction: it never matches $direction or cosine $neighbors.
Metrics
| Metric | Closest means | Use it when |
|---|---|---|
euclidean | smallest straight-line distance | The values are measurements (coordinates, features) where the size of the vector matters |
cosine | smallest 1 - cosine similarity (only the direction counts) | Text and image embeddings: the usual choice |
dot | highest 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.
$neighborsand$directionin one condition: documents matching both.- A sort replaces the similarity order;
skipandlimitapply after it.