Prompt Chain

Build Semantic Search with MongoDB Atlas Vector Search

OpenAI notebook building a semantic movie-search app with MongoDB Atlas Vector Search over the sample_mflix dataset.

Works with openaimongodb

92
Spark score
out of 100
Updated 29 days ago
Version 1.0.0
Models

Add to Favorites

Why it matters

Leverage OpenAI embeddings and MongoDB Atlas Vector Search to build a powerful semantic search application. This asset guides you through setting up your environment, generating embeddings, and querying your data for intent-based search results.

Outcomes

What it gets done

01

Set up MongoDB Atlas cluster and OpenAI API key.

02

Generate vector embeddings for your data using OpenAI.

03

Create and configure a vector search index in MongoDB Atlas.

04

Perform semantic searches on your data using vector similarity.

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/oai-semanticsearchusingmongodbatlasvectorsearch | bash

Steps

Steps in the chain

01
Step 1: Setup the environment
02
Step 2: Setup embeddings generation function
03
Step 3: Create and store embeddings
04
Step 4: Create a vector search index
05
Step 5: Query your data

Overview

Step 1: Setup the environment

OpenAI notebook building semantic movie search on MongoDB Atlas by embedding plot text with OpenAI's API, indexing it with Atlas Vector Search (UI or PyMongo), and querying by meaning instead of keywords. Use when adding semantic search to an existing MongoDB Atlas-backed application without standing up a separate vector database.

What it does

This OpenAI notebook builds a semantic search application using MongoDB Atlas Vector Search over the sample_mflix sample dataset's movies collection, where each document has fields like title, plot, genres, cast, and directors. After setting up a MongoDB Atlas cluster (version 6.0.11+ is required to use the $vectorSearch aggregation operator, and a free-tier cluster works) and an OpenAI API key, it generates a vector embedding for each movie's plot field using the OpenAI embeddings endpoint and stores it back on the document in a new embedding field - restricted to 500 documents in the demo for speed, though the notebook notes the full 23,000+ document dataset is also available, or you can instead use the pre-populated sample_mflix.embedded_movies collection whose plot_embedding field was already generated with OpenAI's text-embedding-3-small model. It then creates an Atlas Vector Search index on the embedding field to enable Approximate k-NN search, covering two paths: manually through the Atlas UI's JSON index editor (specifying 1536 dimensions to match text-embedding-ada-002, dot-product similarity, and the knnVector field type), or programmatically via the PyMongo driver's create_search_index method (requiring a recent PyMongo driver version and MongoDB server 7.0+ on Atlas). Finally, it queries the indexed collection to find movies whose plots are semantically similar to a natural-language query string - matching on meaning rather than exact keyword overlap.

When to use - and when NOT to

Use this notebook when you want to add semantic (meaning-based) search to a MongoDB Atlas-backed application without introducing a separate dedicated vector database - for example enriching an existing movies, articles, or product catalog with intent-based search. It is not the right guide if you are starting from a non-MongoDB stack, need advanced vector index tuning beyond dimension/similarity/type configuration, or need a dataset larger than what a free-tier Atlas cluster comfortably supports for the initial embedding pass.

Inputs and outputs

Input is a MongoDB Atlas collection (here, sample_mflix.movies) with a text field to embed (plot) and a natural-language search query at query time. Output is the same collection enriched with an embedding vector field per document, an Atlas Vector Search index over that field, and a ranked list of documents semantically similar to the query.

Integrations

Built on MongoDB Atlas (6.0.11+) and its $vectorSearch aggregation operator and Atlas Vector Search index (configurable via the Atlas UI or the PyMongo driver), OpenAI's embeddings API (text-embedding-ada-002 / text-embedding-3-small), and the MongoDB sample_mflix sample dataset.

{
  "mappings": {
    "dynamic": true,
    "fields": {
      "embedding": {
        "dimensions": 1536,
        "similarity": "dotProduct",
        "type": "knnVector"
      }
    }
  }
}

Who it's for

Developers already using or evaluating MongoDB Atlas who want to add OpenAI-embedding-powered semantic search to an existing collection without standing up a separate vector database.

Source README

This notebook demonstrates how to build a semantic search application using OpenAI and MongoDB Atlas vector search

Step 1: Setup the environment

There are 2 pre-requisites for this:

  1. MongoDB Atlas cluster: To create a forever free MongoDB Atlas cluster, first, you need to create a MongoDB Atlas account if you don't already have one. Visit the MongoDB Atlas website and click on “Register.” Visit the MongoDB Atlas dashboard and set up your cluster. In order to take advantage of the $vectorSearch operator in an aggregation pipeline, you need to run MongoDB Atlas 6.0.11 or higher. This tutorial can be built using a free cluster. When you’re setting up your deployment, you’ll be prompted to set up a database user and rules for your network connection. Please ensure you save your username and password somewhere safe and have the correct IP address rules in place so your cluster can connect properly. If you need more help getting started, check out our tutorial on MongoDB Atlas.

  2. OpenAI API key To create your OpenAI key, you'll need to create an account. Once you have that, visit the OpenAI platform. Click on your profile icon in the top right of the screen to get the dropdown menu and select “View API keys”.

Note: After executing the step above you will be prompted to enter the credentials.

For this tutorial, we will be using the
MongoDB sample dataset. Load the sample dataset using the Atlas UI. We'll be using the “sample_mflix” database, which contains a “movies” collection where each document contains fields like title, plot, genres, cast, directors, etc.

Step 2: Setup embeddings generation function

Step 3: Create and store embeddings

Each document in the sample dataset sample_mflix.movies corresponds to a movie; we will execute an operation to create a vector embedding for the data in the "plot" field and store it in the database. Creating vector embeddings using OpenAI embeddings endpoint is necessary for performing a similarity search based on intent.

After executing the above, the documents in "movies" collection will contain an additional field of "embedding", as defined by the EMBEDDDING_FIELD_NAME variable, apart from already existing fields like title, plot, genres, cast, directors, etc.

Note: We are restricting this to just 500 documents in the interest of time. If you want to do this over the entire dataset of 23,000+ documents in our sample_mflix database, it will take a little while. Alternatively, you can use the sample_mflix.embedded_movies collection which includes a pre-populated plot_embedding field that contains embeddings created using OpenAI's text-embedding-3-small embedding model that you can use with the Atlas Search vector search feature.

Step 4: Create a vector search index

We will create Atlas Vector Search Index on this collection which will allow us to perform the Approximate KNN search, which powers the semantic search.
We will cover 2 ways to create this index - Atlas UI and using MongoDB python driver.

(Optional) Documentation: Create a Vector Search Index

Now head over to Atlas UI and create an Atlas Vector Search index using the steps descibed here. The 'dimensions' field with value 1536, corresponds to openAI text-embedding-ada002.

Use the definition given below in the JSON editor on the Atlas UI.

{
  "mappings": {
    "dynamic": true,
    "fields": {
      "embedding": {
        "dimensions": 1536,
        "similarity": "dotProduct",
        "type": "knnVector"
      }
    }
  }
}

(Optional) Alternatively, we can use pymongo driver to create these vector search indexes programatically
The python command given in the cell below will create the index (this only works for the most recent version of the Python Driver for MongoDB and MongoDB server version 7.0+ Atlas cluster).

Step 5: Query your data

The results for the query here finds movies which have semantically similar plots to the text captured in the query string, rather than being based on the keyword search.

(Optional) Documentation: Run Vector Search Queries

FAQ

Common questions

Discussion

Questions & comments · 0

Sign In Sign in to leave a comment.