Overview
In this guide, you can learn how to use Mongoid to run MongoDB Vector Search queries. MongoDB Vector Search allows you to query your documents based on their semantic meaning by using vector embeddings.
Mongoid provides the vector_search method, which builds and runs a $vectorSearch aggregation stage for you. To learn more about the $vectorSearch aggregation stage, see the Aggregation Operations guide.
Note
Deployment Compatibility
To use MongoDB Vector Search, you must connect to a MongoDB Atlas cluster or a self-managed deployment running MongoDB 8.2 or later.
To learn more about MongoDB Vector Search, see the MongoDB Vector Search Overview in the Atlas documentation.
Prerequisites
Before you can run a MongoDB Vector Search query, you must define a vector field and a vector search index on your model, and then create the index on your collection. To learn how to declare and create vector search indexes, see the MongoDB Vector Search Indexes section of the Indexes guide.
The examples in this guide use the following Movie model, which maps to the embedded_movies collection in the sample_mflix database. The plot_embedding field stores vector embeddings of each movie's plot.
class Movie include Mongoid::Document store_in collection: "embedded_movies", database: "sample_mflix" field :title, type: String field :plot, type: String field :year, type: Integer field :plot_embedding, type: Array # Declare a vector search index on the `plot_embedding` field. The `_id` # and `year` filter fields enable instance-level and filtered queries. vector_search_index :plot_embedding_index, fields: [ { type: "vector", path: "plot_embedding", numDimensions: 1536, similarity: "cosine" }, { type: "filter", path: "_id" }, { type: "filter", path: "year" } ] end
Tip
Atlas Sample Data
To learn how to load the sample_mflix sample data, see the Load Data into Atlas tutorial in the Atlas documentation.
Run a Vector Search Query
To run a MongoDB Vector Search query, call the vector_search class method on your model and pass a query vector as the first argument. The query vector is a vector embedding that represents your search input.
The following code example runs a MongoDB Vector Search query on the plot_embedding field and prints the title of each matching movie. Because the Movie model declares only one vector search index, Mongoid automatically selects the index and vector field to use.
# The query vector must have the same number of dimensions as the # vector search index (1536, in this example). query_vector = [ -0.0016261312, -0.028070757, -0.011342932, ..., -0.009710136 ] movies = Movie.vector_search(query_vector, limit: 5) movies.each do |movie| puts movie.title end
Thrill Seekers About Time The Time Machine Timecop Crusade in Jeans
The vector_search method returns an array of Movie documents. By default, it returns the 10 most similar documents. To change the number of results, set the limit option. The preceding example specifies a limit of 5 results.
Vector Search Score
Each document that vector_search returns has a vector_search_score attribute, which describes how well the document matches the query vector. A higher score indicates a closer match.
The following code runs the same query as the preceding example, but prints the title and score of each matching movie:
movies = Movie.vector_search(query_vector, limit: 5) movies.each do |movie| puts "#{movie.title}: #{movie.vector_search_score}" end
Thrill Seekers: 0.9253387451171875 About Time: 0.9246978759765625 The Time Machine: 0.9229583740234375 Timecop: 0.9228057861328125 Crusade in Jeans: 0.9222259521484375
Search for Similar Documents
You can also call the vector_search method on a document instance to find documents that are similar to that document. When you call vector_search on a document, Mongoid uses the document's own stored vector as the query vector and excludes the document itself from the results.
The following code finds the five movies most similar to an existing Movie document:
movie = Movie.find_by(title: "About Time") neighbors = movie.vector_search(limit: 5) neighbors.each do |neighbor| puts neighbor.title end
Thrill Seekers The Time Machine Timecop Crusade in Jeans Frequency
Vector Search Options
You can pass the following keyword arguments to the vector_search method to customize your query:
Option | Type | Description | Default Value |
|---|---|---|---|
|
| Name of the vector search index to use. Required only if the model declares more than one vector search index. | Inferred from the model |
|
| Field that contains the vector embeddings. Required only if the vector field can't be inferred from the index definition. | Inferred from the index |
|
| Maximum number of documents to return. |
|
|
| Number of nearest neighbors to consider during the search. |
|
|
| Query used to pre-filter documents before the search. | No filtering |
|
| Additional aggregation stages to append after the vector search. | No additional stages |
The following code runs a MongoDB Vector Search query that considers 150 candidates and returns only movies released after the year 2000:
movies = Movie.vector_search( query_vector, limit: 5, num_candidates: 150, filter: { year: { "$gt" => 2000 } } )
To learn more about these options, see the Fields section of the $vectorSearch operator reference in the Atlas documentation.
Additional Information
To learn how to declare and create vector search indexes, see the MongoDB Vector Search Indexes section of the Indexes guide.
To learn more about the concepts mentioned in this guide, see the following pages in the Atlas documentation:
API Documentation
To learn more about the methods mentioned in this guide, see the following API documentation: