I Added Vectors to My Image Search, Then Found It Wasn't Enough
If all you remember about a picture is roughly what’s in it, but not its filename, how do you find it again? That’s the problem I built PicIndex for.
The idea isn’t complicated: use a multimodal embedding to map images and text into the same vector space, so a search for “cyberpunk rainy street” or “cat sitting by the window” can follow visual semantics to similar pictures.
The demo came together quickly. As soon as I used it as a real tool, the flaws showed up: order numbers in images were missed, a multi-megabyte original image took forever through the model, and the same popular query recomputed its vector every single time.
After a round of tinkering I found that none of these were solved by “switching to a stronger model.” Almost every change that actually mattered in PicIndex happened in the engineering pipeline around the model.
It can find a rainy street, but not an order number
Vector retrieval is very good at fuzzy visual descriptions. You don’t need the filename and you don’t need to tag anything in advance — describe it roughly from memory and it brings the image back. That really was the effect I wanted at first.
But a photo library usually holds another kind of image too: posters with text, screenshots of contracts, expense receipts, equipment nameplates. When people look for those, their need isn’t fuzzy at all — the more exact the better. A multimodal model can tell that two posters are both about a “year-end sale,” but ask it to distinguish order numbers that differ in the last digit and it gets lost.
Rather than expecting one vector to do everything, let specialized tools do specialized jobs. I added an OCR step to the ingest pipeline: at search time, vector retrieval handles “what is this picture roughly,” while Elasticsearch’s BM25 does exact matching inside the text OCR pulled out. Searching “tech product-launch backdrop” leans on the former; searching “order number A20251014” relies entirely on the latter.
With two legs to walk on, both fuzzy impressions and exact phrases were searchable. The new trouble arrived immediately: each leg returns a batch of results, and when you merge them, whose ranking wins?
Merging two result lists: what comes first?
The immediate obstacle is that the two scores don’t live on the same scale. Vector retrieval computes cosine similarity, a value that stays politely inside a fixed range. BM25 scores have no ceiling — nudge word frequency or text length and the score can swing by several times.
Add the two scores directly and BM25’s typical low-teens number instantly drowns a vector score of 0.x. It’s called hybrid retrieval, but in practice the text side does all the talking.
To get both sides onto the same table, I tried two approaches in PicIndex.
The default now is RRF (reciprocal rank fusion). Its logic is blunt: no matter how many points you scored, only your rank on each list matters. An image in the top five on the vector side and top five on the text side will naturally rise in the merged order. That completely sidesteps the scale mismatch, needs no dataset for parameter tuning, and suits a personal project that needs to ship.
The other approach normalizes each side’s scores first, then takes a weighted sum:
1 | final score = α × vector score + β × BM25 score |
The appeal of weighting is that you can lean toward a use case: raise $\alpha$ for stock photography, raise $\beta$ for receipts and archives. But without enough test data for offline evaluation, those two parameters easily become guesswork. So I kept RRF as the safe default and switch to weighting only in scenarios with a very clear intent.
Incidentally, I put the “match percentage” shown in the UI through its own conversion layer. Handing the user Elasticsearch’s raw _score is meaningless, so I map it piecewise into a percentage that feels more intuitive. It’s only a reference to help people see tiers quickly — it does not mean the system is 92% confident that this image is a perfect match.
A slow API doesn’t necessarily mean the model is slacking
When I first wired up the multimodal model, I fed it presigned URLs of the originals in OSS. It worked, but the latency was ugly. A phone snapshot is several megabytes now, at 4000 pixels or more; even if the model service downscales internally, it still has to download those megabytes first.
The obvious fix is to have the backend download and shrink the image before sending it to the model. But that’s volunteering for pain: the application server takes on a file stream for no reason, and memory, CPU, and disk all feel it.
Instead I leaned on OSS’s built-in image processing (x-oss-process). When generating the presigned URL, the backend appends resize, quality, and format parameters. The original stays a single copy in the bucket, but when the model fetches through that URL, the OSS edge node serves the slimmed-down image directly. The application server never touches the image bytes at all.
On my test images, the payload sent to the model shrank by about 85% on average, and the end-to-end time of the embedding API dropped by more than 300 ms. The lesson stuck: when an AI API is slow, don’t blame model inference first — check whether a big file is stuck in the network pipe.
Following the same thread, I moved image uploads to direct-to-OSS from the frontend. The frontend hands the object key to the backend, and the backend drops it into an async queue for OCR, tagging, and embedding at its own pace. The upload endpoint returns instantly, and the server stops being a file mover.
Why cache vectors, but not search results?
Every search first has to send the query to a model to get a vector. For high-frequency queries like “red sports car,” calling an external API every time wastes hundreds of milliseconds and burns tokens for nothing.
Caching is inevitable, but how you cache matters. The easiest thing is to cache “query $\rightarrow$ result list” directly, and that’s a trap in an image library. The library is alive: images arrive and get deleted all the time. Cache the final results and the invalidation strategy becomes a nightmare; miss one edge and the user sees stale data.
So I stepped back: cache only the “query $\rightarrow$ query vector” mapping.
When the same word appears again (or one that matches after trimming spaces and case), pull the previously computed vector from Redis and run a live search in Elasticsearch with it. That skips the slowest external call while always returning the current state of the library.
Measured, hitting Redis drops the time to get a query vector from around 500 ms to under 20 ms. Strictly speaking this is literal-level caching; it doesn’t do semantic caching where “red car” reuses “red sports car.” Semantic caching would mean maintaining a vector index of query terms and accepting the risk of false positives from near-synonyms. Weighing the payoff, I don’t need that extra act right now.
Vectors alone don’t make a usable filter
Turning images into vectors solves only “pull back the ones that look similar.” But people find pictures by narrowing down step by step: they search “weekend camping,” look at a screen of results, and new conditions come to mind — daylight only, must have a tent, no faces.
Hard structured conditions like those are painful to express as vector similarity, and they can’t render as checkboxes on the page. To fill that gap, I added another step to the async ingest job: let a vision model glance at the image and extract scene, style, objects, and shooting time in a fixed format:
1 | { |
After cleanup these extracted terms go into Elasticsearch as keyword fields. Users search in plain language to get close, then click these tags to filter. It feels like shopping on a marketplace and filtering by brand, material, and size — except images don’t come with those attributes, so a vision model has to translate the unstructured picture into structured fields at ingest time.
By this point an image in PicIndex finally stands on three legs: vectors for fuzzy mood, OCR for exact text, structured tags for filtering. Each does its own job, and none of them has to overreach.
Connecting AI from Java isn’t that awkward
Many people’s first reaction to an AI project is that the backend has to be Python. PicIndex is pure Spring Boot end to end, and I never built a Python microservice just to call a model.
The reason is simple: PicIndex uses models, it doesn’t train them. Everything the backend does — direct-upload signing, permission checks, async job orchestration, hybrid ES retrieval, Redis caching, plus calling a few HTTP endpoints — is exactly what Java has always been good at.
What genuinely needs careful handling is not treating an external model like a local method you wrote. It is, in essence, an unstable third-party dependency: slow responses, rate limiting, timeouts, and occasionally JSON that comes back missing a brace.
So structurally I wrapped every model call in a dedicated adapter layer, where timeout control, retries, state machine transitions, and parse fallbacks are all absorbed. Engineering-wise, calling a multimodal model is no different in kind from integrating WeChat Pay or a third-party SMS gateway. The model sets the ceiling on recognition quality; the surrounding engineering decides whether the thing collapses every few days in production. On that front, Java isn’t awkward at all — it’s reassuring.
A last word
PicIndex today is closer to an engineering validation of an idea than a polished production system. The hybrid retrieval weights are still tuned by feel, without a proper labeled set for automated evaluation. The vision model’s extracted tags still go wrong occasionally, and dead-letter compensation for failed async jobs needs work. When the library grows by another order of magnitude, ES shard layout and recall performance will need re-benchmarking too.
The project will keep iterating, but the measuring stick stays the same: whatever new trick I add, I only check three things — is search more accurate, is the code easier to maintain, and is the complexity worth the gain it buys?
Source code: GitHub