Building a Smarter Image Search with Gemini and Elasticsearch
From the publisher’s feed, collected in the ZeroLabs newsroom.
A guide to enhancing vector-based Search and Recommendations using Multimodal AI and Filtered KNNImage by the author — Generated with ChatGPT.I recently published a story describing how to build an image-based recommendation system and search engine using the ResNet model as an embedding model, and Elasticsearch as a vector database. While the recommendation system performs well overall, we found that some recommended items do not belong to the same category as the query item. To address this, we used Elasticsearch’s filtered KNN to improve recommendation relevance. We observed a similar issue in the search engine results, as illustrated in the image below.The goal of this story is to address this limitation by first applying a classification model to identify the query image's category and then using that category to perform a filtered KNN search in Elasticsearch.Image by the author.In this story, I leverage the Gemini Multimodal API to prototype an image classifier, as training an image classifier might require more data, time, and resourcesBefore we begin, please note that this story is closely related to the one below. I recommend reading that first, as this version builds upon and improves it.Building an Image-Based Recommendation System and Search Engine with Deep Learning and…1. Strategies Image ClassificationWe can use two main strategies to build an image classifier:👉 Using Fine Tuning: train a classification model on the source dataset.👉 Using Multimodal APIs: call GenAI APIs with well-crafted prompts and contexts.1.1. Using Multimodal APIsUsing Multimodal APIs for image classification means sending images and a text prompt to foundation models, such as Gemini and ChatGPT, asking them to classify the images. This solution has several advantages, and the two main advantages for our usecase are the following:Few-Shot Learning: no need for massive labeled datasets. A few examples help the model learn to differentiate and classify the provided images.Flexibility: deploying a new category requires just updating the prompt and the context—no need to retrain the overall model.However, this solution also has limitations:Cost. If there are tens of thousands of images to classify a day, the API bill will skyrocket.Latency: GenAI APIs like Gemini or ChatGPT are general-purpose models; they are not specialized for pure image classification, resulting in longer inference times. Additionally, potential network overhead might increase inference latency.1.2. Fine-Tuning for Image ClassificationFine-tuning an image classification model involves taking a model like ResNet [2], MobileNet [3], or CLIP [4], pre-trained on millions of images like ImageNet [6], and retraining just the final layers to recognize the specific target categories. The advantages of fine-tuning a pretrained model are the following:Performance: A fine-tuned model like ResNet [2] or MobileNet [3] can classify images in milliseconds. It is a task-specific model, built for speed.Cost-Effective at Scale: Once trained, model inference is highly cost-effective. Compared to multimodal APIs, the cost does not scale linearly with every single query or classification task.Deterministic & Consistent: If the model detects a specific visual feature, it will output the exact label it was trained on.On the other hand, fine-tuning a model has its own limitations:Data Hungry: Even with transfer learning and fine-tuning, hundreds or thousands of high-quality, labeled images for each category are required to get good accuracy.Engineering Overhead: it requires expertise and time to prepare data, tune hyperparameters, train the model (usually requiring GPUs), and expose the model through an API.Rigidity: Adding a new category to the model requires collecting the related data and retraining the entire model.This story leverages the Gemini multimodal API to perform image classification tasks. The two main reasons for this choice are that it is easy to prototype and that few-shot learning is sufficient to have a functional image classifier (my current dataset lacks the volume required for effective fine-tuning).2. Image Classification with Gemini APIsThe complete source code related to this story is available in this GitHub repository.2.1. Create Gemini API KeyFollow the steps below to create a Gemini API key:Go to https://aistudio.google.com/ and log in with your Google account,From the bottom left menu, click the “Get API Key” link,On the top right, click the “Create API Key” button,Set the name of the API Key and choose a GCP Project. If no project exists, create a new project, then end by clicking the “Create key” button.Note that you should enable billing for the newly created API key before using it. Otherwise, you will get an unauthorized error message when using the key.2.2. Preparing the Classifier Knowledge-basedFor Gemini to classify images with my specific label, I have created this document in a PDF format that I used as a reference or context for my classifier. The file presents the categories with a few examples of representative images (see the screenshot below).Classifier knowledge-base saved in PDF format — Image by the author.For prototyping purposes, I have only represented a few categories of my dataset.The code snippet below uploads the classifier knowledge base, in PDF format, to Gemini. Later on, the file will be used as context for the classifier. Find all the source code in this notebook.from dotenv import load_dotenvfrom google import genaifrom google.genai import errors# create and load the GEMINI_API_KEY env variables from the credential fileload_dotenv(dotenv_path=os.path.join(PROJECT_DIR, ".env"))# initialize the gemini client using the GEMINI_API_KEY env variablesclient = genai.Client(api_key=os.getenv('GEMINI_API_KEY'))# Set the classification knowledge base for the gemini apiCLASSIFIER_KB_PATH = "./classifier_kb.pdf"CLASSIFIER_KB_FILE_NAME = "files/ibrs-classifier-kb"# Upload the knowledge base if it doesn't existtry: CLASSIFIER_KB = client.files.upload( file=CLASSIFIER_KB_PATH, config={ "name": CLASSIFIER_KB_FILE_NAME, "display_name": "Image Classifier Knowledge Base", "mime_type": "application/pdf" } )except errors.ClientError as e: if e.code == 409: print(f"Knowledge-base {CLASSIFIER_KB_FILE_NAME} already exists.") CLASSIFIER_KB = client.files.get(name=CLASSIFIER_KB_FILE_NAME) else: raise e2.3. Use The Gemini Python SDK for Image ClassificationThe code snippet below defines the instruction for the gemini-2.0-flash model and uses the knowledge base, previously uploaded, to generate/predict the category of the new image with the classify_with_gemini() method. Find the complete code in this notebook from the GitHub repository.# set the model to useMODEL_NAME = "gemini-2.0-flash"# define instructions for the modelINSTRUCTIONS = """You are an expert e-commerce item classifier.The provided knowledge base contains the category definitions and four visual examples in a PDF format.Study the knowledge base to understand the visual features of each category.Your Goal is to classify each provided image into exactly one category defined in the knowledge base."""def classify_with_gemini(query_img_path, CLASSIFIER_KB=CLASSIFIER_KB): # Load user query image with open(query_img_path, "rb") as f: query_image_bytes = f.read() # Build Prompt prompt_parts = [ # adding the classifier knowledge base as context of the prompt CLASSIFIER_KB, # specify the instruction INSTRUCTIONS, # add the new image to classify types.Part.from_bytes( data=query_image_bytes, mime_type='image/jpeg' ), # Task """ Analyze the above image and assign it to exactly one category defined in the knowledge. """ ] # Call Gemini the generate/predict the category response = client.models.generate_content( model=MODEL_NAME, contents=prompt_parts, config=types.GenerateContentConfig( response_mime_type="application/json", response_schema={ "type": "object", "properties": { "category": { "type": "string", "enum": categories # pick only one category. } }, "required": ["category"] } ) ) return response.parsed2.4. Use the CachedContent SDK instead of the File UploadFor optimal performance, the Gemini Context Caching API is the preferred choice. By caching precomputed input tokens, you can reuse the same context — such as your image classification knowledge base — across multiple requests. At scale, this strategy significantly reduces both latency and API costs.However, Gemini’s context caching requires a minimum threshold of 4096 tokens to be active. Since my classifier knowledge base currently contains only 323 tokens, it does not meet the technical requirement for caching. Consequently, I opted for the standard File Upload API; while this approach is less cost-efficient at scale, it provides a functional and straightforward solution for this prototype’s smaller context size.Below are useful docs for more details on how to use the context caching with Gemini:https://ai.google.dev/api/cachinghttps://googleapis.github.io/python-genai/genai.html#module-genai.caches3. Enhanced RecommendationsNow that the classify_with_gemini() method works, we can use it to enhance the image_based_search() method defined in the previous story. The enhanced_image_based_search() method below uses Gemini to predict the category of the query image, then uses the predicted category to perform an Elasticsearch filtered query.def enhanced_image_based_search(src_img_path, k=10, num_candidates=100): # Use Gemini to get the category of the query image predicted_category = classify_with_gemini(src_img_path) # extract embeddings of the source image src_vector = extract_embeddings_batch(paths=[src_img_path]) # build the filtered knn query. knn_query = { "knn": { "field": "image_features", "query_vector": src_vector[0], "k": k, "num_candidates": num_candidates, "filter": { "term": { # use the predicted category to filter the search "category": predicted_category['category'] } } } } # execute the elasticsearch knn query res = es.search(index=index_name, query=knn_query) knn_results = res['hits']['hits'] return knn_resultsBelow are two examples of search results with and without image classification. The first search result, from my previous story, includes items with the red squares that are not semantically similar to the query image. Using image classification helped enhance the search results (rf. Search Results 2).Search Results 1: Image-search without classification — Image by the author.Search Results 2: Image-search with classification — Image by the author.What next?While these results show significant progress, further optimizations are possible. Specifically, replacing ResNet with models like CLIP [4] or Vision Transformers [5] could yield even higher accuracy, as these architectures excel at understanding the semantic context of an image. I plan to explore these different embedding models in a future story, comparing the efficiency of various APIs and open source models in both classified and non-classified search workflows.Thanks for reading, and stay tuned 🙏.If you found this story useful, encourage me to produce such content by:👉 Following me on Medium,👉 Connecting with me on LinkedIn and GitHub,References[1] C. Wenga, Building an Image-Based Recommendation System and Search Engine with Deep Learning and Elasticsearch — Medium, 2026.[2] K. He et al. (2016). Deep Residual Learning for Image Recognition. Microsoft Research — In CVPR, 2016[3] Andrew G. Howard et al. (2017). MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications — Google Inc.[4] A. Radford et al (2021). Learning Transferable Visual Models From Natural Language Supervision — OpenAI.[5] A. Dosovitskiy et al. (2020). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. Google Research.[6] ImageNet ChallengeBuilding a Smarter Image Search with Gemini and Elasticsearch was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.