Building a Reverse Video Search System With Mixpeek & PostgreSQL
In case you missed the pgai Vectorizer launch, learn why vector databases are the wrong abstraction and how you can create AI embeddings right within your PostgreSQL database.
Until recently, searching through unstructured data—like text, images, and videos—was a nontrivial problem. Traditional search methods struggled with interpreting the meaning behind this content, making it difficult to extract relevant information efficiently. Enter embeddings: a way of representing data in n-dimensional space that enables computers to recognize patterns and context within this unstructured data.
In this blog post, you’ll learn how to build a reverse video search system using Mixpeek for video processing & embedding generation, combined with PostgreSQL as a vector database (powered by pgvector and pgvectorscale) hosted on Timescale Cloud. This system will allow you to query video data using both video and text queries to retrieve relevant video segments based on semantic similarity.
Reverse Video System Overview
Before discussing implementation details, let’s explore the overall architecture of the reverse video system we’re building.
Video ingestion process
The ingestion process involves inputting the source video data into a vector database. Here is how it works:
- Source video: The process starts with uploading a source video.
- Video chunks: The video is split into chunks for optimized embedding creation using Mixpeek’s video indexing tool.
- Embeddings: Mixpeek’s indexing tool extracts video features from each video chunk to generate vector embeddings using one of the embedding models integrated with it.
This indexing tool can also pull other useful features, such as text and emotions, extracted as structured JSON. Therefore, Mixpeek enables both semantic and hybrid search!
- Vector database: The generated vector embeddings are stored in a database that supports vector similarity search—in this case, PostgreSQL with pgvector and pgvectorscale and hosted on Timescale Cloud. This database not only handles vector similarity searches but also enables you to store metadata, such as start and end times, alongside their embeddings
Video retrieval process
- Query: the user submits a text or video query.
- Query embeddings: Mixpeek converts the query into embeddings to capture its semantic meaning.
- Vector search: these embeddings are then compared against the stored embeddings in the vector database to retrieve the closest matches using vector similarity search.
The Timescale and Mixpeek tech stacks complement each other. Mixpeek generates the vector embeddings, while Timescale’s PostgreSQL database—powered by pgvector and pgvectorscale—ensures optimized storage, management, and retrieval of the video data and its embeddings.
Implementation
Now that we have covered the architecture of the reverse video search system, let's move on to the implementation. To make this tutorial more digestible, I divided the implementation into several sections. You can also follow along with this notebook.
Imports and setup
Setting up environment variables
In this section, we first create a .env
file to store our environment variables. Let’s first get these variables:
- Obtain a Mixpeek API key from your Mixpeek account. If you don’t have an account yet, you must sign up for one through this page.
- Then, create a PostgreSQL service for your data and embeddings by signing up for Timescale Cloud (it’s free for 30 days). Follow the setup instructions in the Getting Started with Timescale guide.
After creating your database service, get the connection string provided in the dashboard.
Store these variables in the .env
file as follows:
MIXPEEK_API_KEY='...'
DATABASE_CONNECTION_STRING='...'
Installing libraries
To get started, let’s install the required libraries:
psycopg2
enables the connection to PostgreSQL. python-dotenv
lets you read the values stored in your environment while requests allows you to send HTTP requests easily.
Then, you can import the libraries and load the environment variables as follows:
Mixpeek workflow
In this section, we define different functions related to video indexing, feature extraction, and retrieving video chunks & their embeddings using Mixpeek’s API. Then, we demonstrate how to get embeddings using a video.
Video indexing and feature extraction
In the index_video_file
function, we use Mixpeek’s Index Video Url endpoint to process the source video and divide it into chunks. For each video chunk, this tool does the following:
- Reads on-screen text using the
video-descriptor-v1
model. - Generates a 1408-dimensional vector embedding with the
multimodal-v1
model - Transcribes the audio in the video chunk using the
polyglot-v1
model - Creates a comprehensive description of the chunk, including the screenplay and sound details
Let's use the task_id
associated with the indexing process to check its status through the Get Task endpoint.
Retrieving video chunks and embeddings
In this part, we access the metadata (start_time
and end_time
) and feature_ids
of the video chunks created using the Get Asset With Features endpoint and the asset_id
from the response from the Get Task endpoint.
Then using the feature_id
, let's access the generated vector embedding from each video chunk through the Get Feature endpoint.
Example
Let's now combine all these parts into one function, get_mixpeek_embeddings
, and demonstrate using a video file.
PostgreSQL workflow
Connecting to PostgreSQL using Timescale Cloud
In this tutorial, we'll use PostgreSQL with the pgvector and pgvectorscale extensions as our vector database. This database instance is hosted on Timescale Cloud.
The pgvectorscale extension builds on top of pgvector, enabling PostgreSQL to efficiently store and query vector embeddings. You might wonder why you should upgrade from PostgreSQL with pgvector to Timescale Cloud’s AI stack (pgai, pgvectorscale, and pgai Vectorizer). Here’s why:
- Faster and more cost-effective ANN search: PostgreSQL, powered by pgvector and pgvectorscale, is a faster, more accurate, and more affordable vector database. Compared to popular vector databases like Pinecone, PostgreSQL with pgvector and pgvectorscale achieved 28x lower p95 query latency and 16x higher query throughput for approximate nearest neighbor (ANN) queries at 99 % recall—at only 25 % of Pinecone’s monthly cost.
- High-performance and scalability for your AI Applications: pgvectorscale boosts PostgreSQL’s ANN capabilities with StreamingDiskANN, a disk-based ANN algorithm that outperforms memory-based indexes like pgvector’s IVFFlat. With no
ef_search
cutoffs and its streaming model, it enhances query speed and accuracy, continuously retrieving the “next closest” item, potentially even traversing the entire graph! - A simplified AI stack: Timescale’s AI stack integrates vector embeddings, relational data, and time-series data in one place. This consolidation significantly reduces the complexity of infrastructure management and data synchronization, allowing you to focus on building AI applications.
- Seamless PostgreSQL compatibility: Since Timescale inherits PostgreSQL’s syntax and robustness, developers with PostgreSQL experience can integrate AI capabilities in their application development without a steep learning curve.
Use the code below to connect to your database service and confirm database access:
Creating a table for video chunks
Since we are working with embedding data, we need to ensure our PostgreSQL service can support it. Therefore, we install the pgvector and pgvectorscale extensions before creating the table, video_embeddings
, that stores information about video segments (or chunks) and their embeddings.
Here's a breakdown of the columns:
id
: a unique identifier for each video chunk.embedding
: a 1408-dimensional vector embedding of the video chunk.start_time
: the starting time of the video chunk. For example, if a video is split into segments, this could be each segment's start time (in seconds or another unit).end_time
: the ending time of the video chunk, indicating when the segment finishes.
Data insertion
Let’s ingest the video chunks and their embeddings into our database.
Creating the index on embeddings
Vector search queries will primarily target the embedding
column, so we create an index on this column using StreamingDiskANN. It significantly speeds up vector similarity searches.
Search functions
In this section, we demonstrate two search functions for retrieving relevant video chunks: one based on video input and the other based on text query. The idea is to search for similar video chunks stored in the database by comparing embeddings, allowing us to match the content of the video query or find similar scenes based on descriptive text.
For each query, we first generate vector embeddings and then use them to search for the closest video chunks through the source video embeddings, ranking results by cosine distance. Let’s first define a helper function for vector similarity search.
Video query search
Here are the results of this query:
Text query search
In this part, let's use the Index Text endpoint to generate embeddings for the text query and then use them to perform a vector similarity search.
Here are the results of this query:
This demo uses a single video. However, we can extend the same approach to handle a collection of videos.
Conclusion
Unstructured data, particularly videos, can be challenging to manage, but Mixpeek’s video processing and embedding generation simplify the task, making the data searchable and more accessible. With content creation and generation increasingly in the hands of everyday users, data accumulation will only continue to grow. As a result, search engines need to evolve.
In this article, we covered how to build a reverse video search engine using Mixpeek and Timescale Cloud’s mature PostgreSQL cloud platform. This stack potentially paves the way for many enhancements in multi-modal video analysis and retrieval. We can deploy add-ons to the current system, for example, integrating AI-generated sentiment analysis or treating support queries in several languages.
AI is still in its early stages. Video search and understanding will continue to evolve. If you're interested in implementing these solutions, check out Mixpeek’s API documentation and Timescale’s AI stack to start building your own advanced video search engine.