datasocial.ai
Searching Video by What It Looks Like
Pipeline notes · SigLIP2 · Elasticsearch

Searching Video by What It Looks Like

I wanted to type "girl dancing in a supermarket aisle" and get back videos that look like that, out of a corpus where most of the captions are emoji, hashtags or nothing at all. The picture is the only reliable description of a video, and nothing about a picture is searchable until you turn it into numbers. This is what that cost: the encoding pipeline, the two designs I tried for storing the vectors, and the scoring bug I shipped twice in the same codebase.

What I wanted

The product is a discovery tool for short video. You describe the kind of content you are looking for and it returns videos that match, filtered by the usual things: view count, engagement rate, country, how recently it was posted, whether it is sponsored.

Every filter in that list is a number or a keyword, and those were solved. The description was not. "A girl dancing in a supermarket aisle" is not a field in any table, and no amount of indexing the data I already had was going to produce it.

Why the captions are useless

The obvious move is to search the caption, and it fails for a reason that is specific to this platform rather than a general truth about text search.

A caption on a short video is not a description of the video. It is a hook, a joke, a list of hashtags chosen for reach, an emoji, or empty. When it does describe something, that something is as likely to be the sound as the picture. Across the corpus the caption is populated on roughly 84% of posts, and the fraction of those that would let you find the video by what it looks like is far smaller than that.

So the searchable description has to be generated, and the only honest source for it is the frame itself.

The first version

The first build was the textbook one, and on paper it is still the advice you will get: encode the images with CLIP, put the vectors in a vector database, query it, join the ids back to your real data.

ModelOpenCLIP ViT-B-32
Dimensions512
Encoding hardwareCPU, 32 worker threads
Vector storeQdrant, cosine distance
Batch sizes10,000 read, 1,000 upsert

It worked. I could encode a query, get neighbours back, and the neighbours were genuinely similar. For a few hundred thousand thumbnails that is the whole job, and if that is your scale you should stop reading and go build this.

Where it broke

Three separate things, and only the first one was obvious in advance.

CPU encoding does not reach a hundred million

Encoding on CPU is fine for a backfill you run once and forget. It is not fine when the corpus grows by hundreds of thousands of videos a day and every one of them needs a forward pass through a vision model. That part was a hardware problem with a hardware answer, and it is the easy one.

The id list is a recall ceiling

The real problem is what "join the ids back to your real data" means once there are filters involved. The vector store knows about vectors. It does not know the view count, the country or whether the account is sponsored. Those live in the search index. So the query becomes three hops:

encode query vector store, top 10,000 terms clause of 10,000 ids filters, page similarity order is lost here, so the app re-sorts the page it got back Anything similar but ranked 10,001st is invisible, whatever the filters say. Re-sorting after the index paginated only reorders the current twenty rows. Three round trips, one of them carrying ten thousand ids.
The fan-out is not a performance problem. It is a correctness ceiling.

Ten thousand is the limit that fits in a query without embarrassment, and it is the wrong ten thousand. The vector store picks the most visually similar ten thousand across the entire corpus, and then the filters throw most of them away. Ask for videos that look like a supermarket aisle and come from the Philippines and have over a million views, and you may get nothing back, not because nothing matches but because the visual top ten thousand happened to be somewhere else.

Ordering does not survive pagination

The last one is the quietest. The search index paginates, so it returns twenty rows. The app then re-sorts those twenty by their position in the vector store's ranking. That looks correct on page one and is meaningless by page three, because the ordering is being applied after the cut rather than before it.

Encoding a hundred million frames

The rebuild moved the vectors into Elasticsearch next to the filters, which is the subject of the rest of this article. First the boring half: getting a hundred million thumbnails through a vision model.

downloader Go, 5,000 in flight oEmbed, then CDN local disk, zipped 100 MB multipart to object storage GPU encoder SigLIP2, 1152 dims separate host .f16.mmap plus a paths list, one pair per zip ClickHouse the record, 50k rows per insert Elasticsearch the index, 5k docs per bulk
The encoder is the only GPU in the system, and it is deliberately not in the request path.

Two details in the download stage are worth copying. Getting a thumbnail is two hops, not one: an oEmbed call to resolve the video id into a thumbnail URL, then a direct fetch from the CDN. The first goes through rotating proxies because it is a platform endpoint. The second does not, because it is a plain CDN and paying proxy bandwidth for image bytes is money set on fire.

The work list is an anti-join against a table of what has already been downloaded, restricted to videos above ten thousand views. Encoding the long tail is most of the cost and none of the value, since nobody searches for content nobody watched.

Everything moves in zips. A GPU that stops to fetch one image at a time is a GPU you are renting to do network waits, so the encoder takes an archive, produces one memory-mapped float16 array plus the list of paths it corresponds to, and the loader reads that back with a single reshape.

vectors = np.fromfile(path, dtype=np.float16).reshape(n, 1152)

Keeping the rows aligned

Some images fail. The CDN has expired the file, the bytes are truncated, the format is something the decoder will not take. In a batch of ten thousand you get a handful of these, and the obvious response is to skip them.

Skipping them silently corrupts the entire batch. The encoder writes a flat array of vectors and a separate list of paths, and the only thing binding a vector to the video it came from is its position. Drop row 4,000 from the array and every vector after it is attributed to the wrong video, with no error and nothing in the data that looks wrong.

So a failed image is written as a row of NaN rather than not written at all. Row order survives, the loader drops the NaN rows after the join, and a misalignment becomes impossible rather than unlikely.

paths.txt 7345...001 7345...002 7345...003 7345...004 written as NaN, stays aligned [0.021, -0.11, ...] [0.004, 0.37, ...] [NaN, NaN, ...] [0.190, -0.05, ...] dropped after the join, nothing shifts skipped, everything below shifts up [0.021, -0.11, ...] [0.004, 0.37, ...] [0.190, -0.05, ...] wrong video [0.771, 0.02, ...] wrong video silent, and permanent once it is indexed
One skipped row poisons every row after it in the batch.

What a vector costs

1152 dimensions at four bytes each is 4.6 KB per video before any overhead, which is the number that decides most of the architecture around it.

Dimensions1152
On the wire from the encoder, float162.3 KB
In ClickHouse, Float32 with ZSTD(3)~4.6 KB raw
In Elasticsearch, per document~4.5 KB
Documents per bulk request5,000
Resulting bulk body~22 MB
Index buildHNSW, m 16, ef_construction 200

The bulk size is the one people get wrong. Everywhere else in this system a bulk of 25,000 documents is reasonable, because documents are a few hundred bytes. At 4.5 KB each, 5,000 is already a 22 MB request, and going to 25,000 means a 110 MB body that will time out and be retried in full.

The mapping is the other half of the cost:

embedding: {
  type: 'dense_vector',
  dims: 1152,
  index: true,
  similarity: 'cosine',
  index_options: { type: 'hnsw', m: 16, ef_construction: 200 },
}

Vectors are written as an update against an existing document rather than an insert, with upsert explicitly disabled. A vector whose video has not been indexed yet comes back as not-found and is skipped, instead of creating a document that is nothing but a vector and has no caption, no view count and no country to filter on.

The loader also checks length on read and drops anything that is not exactly 1152 numbers. A wrong-length vector is a mapping error at index time rather than a bad result at query time, and the row it came from is worth losing.

Searching pictures with words

Nothing so far explains how typing English finds a picture. The answer is the part of these models that is easy to miss: they have two encoders, and both of them produce vectors in the same space.

thumbnail image tower once, offline, on a GPU "supermarket aisle" text tower per query, 64 tokens, milliseconds one 1152-dimension space cosine distance between a sentence and a picture is a meaningful number, which is the whole trick
The image side runs once per video. The text side runs once per keystroke.

The query path is a small self-hosted service holding the text half of the same model. It tokenises to a maximum of 64 tokens, takes the pooled output and normalises it to unit length, which takes milliseconds and no GPU worth mentioning. The result goes straight into a kNN query against vectors produced months earlier by the image half.

Using the same model on both sides is not a detail. It is the entire assumption the system rests on, and breaking it silently is the worst bug in this article.

Filters and vectors together

With the vectors living in the same index as the filters, the three hop query collapses into one, and the ten thousand id ceiling disappears with it. The important part is where the filters go.

// every constraint moves into the knn filter, so vector search only
// considers documents that already match the text and range criteria
const knnFilterClauses = [...filter];
if (must.length > 0) knnFilterClauses.push(...must);
if (knnFilterClauses.length > 0) searchParams.knn.filter = { bool: { must: knnFilterClauses } };

// with everything on the knn, a separate text query would only dilute it
searchParams.query = { match_all: {} };

Pushing the filters into knn.filter rather than leaving them beside the kNN as a normal query is the difference between filtering before and after the nearest-neighbour search. Before means the graph traversal only walks documents that can appear in the result. After means it walks the whole corpus, picks the visually closest, and then discards most of them, which is the id list problem again wearing a different hat.

One consequence worth understanding before you copy this. The same text clauses behave differently in the two modes: in keyword mode they score, and in vector mode they move into the filter and stop scoring. Sorting is also disabled in vector mode, because any sort would overwrite the kNN ordering with a metadata ordering and quietly turn the feature off.

For a "more like this video" rail the two are combined rather than swapped. A kNN clause runs alongside a keyword similarity query, with constant-score boosts for matching niche and matching country, and Elasticsearch adds the scores. The result is re-ranked once in the application by blending similarity with recency:

score = similarity * 0.85 + recency * 0.15
cutoff = 0.68
Similarity alone surfaces perfect matches from two years ago, which nobody wants from a discovery tool.

kNN has no offset

A normal Elasticsearch query takes from and size. A kNN query takes k, and there is no offset. You cannot ask for neighbours 101 through 120.

So paging through image search results means asking for the whole prefix every time and throwing away the part you already showed:

page 1 k = 20 page 5 k = 100, 80 discarded page 25 k = 500, 480 discarded page 50 k = 1,000, of which 980 are thrown away in the client candidate pool never drops below 1,000 regardless, so page 1 over-fetches too
Accent is the twenty rows the user sees. Grey is refetched work.

This is survivable because nobody pages to fifty in a discovery tool, and the fix is a cap rather than cleverness: the product stops offering pages past a hundred. It is worth knowing before you promise infinite scroll over a vector search.

The candidate pool has a floor as well. Every kNN query asks for at least a thousand candidates to traverse, even when it only needs twenty results, because HNSW recall degrades badly when the candidate list is tight. Page one of an image search over-fetches by a factor of fifty and it is still the fastest part of the request.

Rewriting the query first

There is a gap between what people type and what the image half of the model understands. Somebody searching a creator tool types "fitness". The thumbnails that should come back contain a person exercising in a gym, and the text tower does noticeably better when it is handed the second phrasing.

So a language model sits in front, and its job is narrower than it sounds. It turns one query into two channels:

ChannelGetsUsed for
keywordcaption-relevant words onlyordinary text matching
visuala description of what is in framethe text tower, then kNN
filtersranges and enumerated valuesfilter context

The prompt is explicit that these do not overlap, because the failure mode is handing visual descriptions to the keyword channel and getting zero results: captions do not contain the words "person exercising working out in gym".

Two things make this reliable enough to ship. The list of valid niches is interpolated into the prompt, so the model can only emit values that exist as keywords in the index. And everything it returns goes through deterministic repair afterwards: a synonym table, a location table matched on word boundaries so that "us" does not match inside "music", and a range parser that understands "1.5m" and "10k to 100k".

The model never writes query DSL. It emits the same filter object the checkboxes and sliders produce, so a parsed query and a hand-built one are indistinguishable downstream and the user can edit the result.

Changing model, changing dimensions

Vectors from one model are meaningless to another. Upgrading the encoder is therefore not a deploy, it is a re-encode of the entire corpus, and the dimension count changes with it, which means the mapping changes, which means a new index.

GenerationModelDimsStore
firstOpenCLIP ViT-B-32512Qdrant
secondSigLIP2768Elasticsearch
thirdSigLIP2, larger1152Elasticsearch

The 768 to 1152 move was done server side rather than by replaying the loader, which would have meant re-reading every vector out of ClickHouse and back over the network. The reindex API copies documents between indices with a script that strips the field that is about to become invalid:

// the old vectors are the wrong width for the new mapping
ctx._source.remove('embedding');

Run with completion waiting turned off, then polled. Everything else about the document survives, the embeddings refill from the GPU pipeline over the following days, and search degrades to keyword only in the meantime rather than breaking.

Failure modes

The same score, normalised two different ways

Elasticsearch does not return a cosine similarity from a kNN query. It returns a score derived from it, and the derivation is easy to get wrong because it is plausible either way.

One module in this codebase subtracts one from the score, with a comment saying kNN returns one plus the cosine. Another module pulls the raw vectors back out of the documents, recomputes the cosine in the application, and divides by two. Both cannot be right. The scores they produce differ by a factor of two, and both feed the same similarity cutoff.

Nothing crashes. The cutoff is simply doing something different depending on which code path served the request, which surfaces as "similar videos sometimes returns nothing" and gets dismissed as the corpus being thin.

Pick one normalisation, put it in one function, and write the test that asserts an identical vector scores exactly 1.0.

A fallback path on the wrong model version

The query encoder has a fallback that calls a hosted inference API when the local service is unavailable. The fallback was pointed at SigLIP version 1. The index was built with version 2.

Two models with the same output width and completely different spaces. The fallback returns 1152 numbers, Elasticsearch accepts them, HNSW happily finds the nearest neighbours to a point that means nothing, and the user gets twenty unrelated videos with confident-looking scores. There is no error anywhere in that chain.

A model identifier belongs in the index name or in a field on every document, and the query path should refuse to run when it does not match.

Shipping the vectors to the browser

Nothing excluded embedding from _source, so every search result carried 4.5 KB of floats that the front end has no use for. Twenty results is 90 KB of wasted payload per request, and the only reason it was not worse is that one module actually wanted them, to recompute the cosine described above.

Exclude the field in the mapping or in the query. Both are one line.

What I would keep

The architecture question at the top of this article, whether vectors go in a dedicated vector database or in the search index you already run, has a clear answer once there are filters involved, and it is not the answer most tutorials give.

  • Put the vectors where the filters are. A separate vector database is the better tool right up until the first time somebody wants "similar, but only from this country, above this view count". Then it becomes an id list with a ceiling, and the ceiling is a correctness bug rather than a slowdown.
  • Filter before the search, not after. One field in the kNN query decides whether the graph walks only eligible documents or walks everything and then throws the results away.
  • Never let a failed input shift a batch. Write the NaN row. The alternative is a corpus where an unknown fraction of vectors point at the wrong video, which you will find out about from a user.
  • Tie the model version to the index. Encoder and index are one unit. Anything that can encode a query with a different model than built the index will eventually do exactly that, at three in the morning, during a fallback.

What comes after the vectors, the daily sync that keeps this index in step with the record, is in Querying Billions of Rows in Milliseconds.