Magento 2 RAG Product Search — Vector-Based AI Search (2026)
Implement Magento 2 RAG product search using retrieval-augmented generation — embed product data, vector store, semantic query, and AI-ranked results via REST API.
Standard Magento 2 search is keyword-based — it matches tokens in product names and descriptions. A customer searching for “something warm for winter hiking” gets zero results because no product contains those exact words. Magento 2 RAG product search solves this with retrieval-augmented generation: products are embedded as semantic vectors, and natural language queries are matched by meaning rather than keyword overlap. This guide builds a complete Magento 2 RAG product search implementation using OpenAI embeddings, a pgvector or Pinecone vector store, and a Magento REST API endpoint that returns AI-ranked results for any natural language query.

Magento 2 RAG Product Search: Architecture Overview
The Magento 2 RAG product search architecture has two phases. The indexing phase runs on product save or via a CLI command: product data is assembled into a text representation, passed to an embedding API to generate a vector, and stored in a vector database alongside the Magento product ID. The query phase runs at search time: the customer’s query is embedded using the same model, and a cosine similarity search against the vector store returns the most semantically similar products.
Magento 2 RAG Product Search: Embedding Products on Save
<?php
namespace VendorRagSearchObserver;
use MagentoFrameworkEventObserverInterface;
use MagentoCatalogModelProduct;
class ProductSaveAfter implements ObserverInterface
{
public function __construct(
private readonly VendorRagSearchModelEmbeddingService $embeddingService
) {}
public function execute( MagentoFrameworkEventObserver $observer ): void
{
$product = $observer->getEvent()->getProduct();
if ( ! $product instanceof Product ) return;
// Build text for Magento 2 RAG product search embedding
$text = implode( ' ', array_filter([
$product->getName(),
$product->getShortDescription(),
strip_tags( $product->getDescription() ),
implode( ' ', $product->getCategoryIds() ),
]));
// Generate and store embedding asynchronously
$this->embeddingService->embedAndStore( (int) $product->getId(), $text );
}
}
// EmbeddingService.php
class EmbeddingService
{
public function embedAndStore( int $productId, string $text ): void
{
$response = $this->httpClient->post( 'https://api.openai.com/v1/embeddings', [
'model' => 'text-embedding-3-small',
'input' => substr( $text, 0, 8000 ), // token limit
]);
$vector = $response['data'][0]['embedding'];
// Store in Magento 2 RAG product search vector table
$this->connection->insertOnDuplicate(
'caz_product_embeddings',
[ 'product_id' => $productId, 'embedding' => json_encode( $vector ) ]
);
}
}Magento 2 RAG Product Search: Semantic Query Endpoint
<?php
// Semantic search: embed query, find similar products via cosine similarity
public function search( string $query, int $limit = 10 ): array
{
// Embed the customer query for Magento 2 RAG product search
$queryVector = $this->getEmbedding( $query );
// Fetch all stored embeddings (use pgvector or Pinecone for production scale)
$rows = $this->connection->fetchAll(
"SELECT product_id, embedding FROM caz_product_embeddings"
);
$scores = [];
foreach ( $rows as $row ) {
$productVector = json_decode( $row['embedding'], true );
$scores[ $row['product_id'] ] = $this->cosineSimilarity( $queryVector, $productVector );
}
arsort( $scores );
return array_keys( array_slice( $scores, 0, $limit, true ) );
}
private function cosineSimilarity( array $a, array $b ): float
{
$dot = array_sum( array_map( fn( $x, $y ) => $x * $y, $a, $b ) );
$magA = sqrt( array_sum( array_map( fn( $x ) => $x * $x, $a ) ) );
$magB = sqrt( array_sum( array_map( fn( $x ) => $x * $x, $b ) ) );
return $magA && $magB ? $dot / ( $magA * $magB ) : 0.0;
}💡 For production-scale Magento 2 RAG product search with 10,000+ products, replace the PHP cosine similarity loop with pgvector’s native <=> cosine distance operator: SELECT product_id FROM caz_product_embeddings ORDER BY embedding <=> '[query_vector]' LIMIT 10. This runs in milliseconds on an indexed vector column versus seconds for PHP-loop similarity across a large catalogue.
The OpenAI Embeddings guide covers the text-embedding-3-small model used for Magento 2 RAG product search indexing. The pgvector PostgreSQL extension provides native vector similarity search for production-scale Magento 2 RAG product search deployments. See our Magento 2 developer guide for the module and observer architecture, and our Magento 2 development services for custom AI search implementations.
Frequently Asked Questions — Magento 2 RAG Product Search
What is Magento 2 RAG product search?
Magento 2 RAG product search is retrieval-augmented generation applied to product discovery. Products are converted to vector embeddings using an AI model like OpenAI text-embedding-3-small. When a customer searches, their query is embedded using the same model and matched against product vectors by cosine similarity. This returns semantically relevant products for natural language queries that standard keyword search misses entirely.
How do I store product embeddings for Magento 2 RAG product search?
For small catalogues (under 5,000 products), store embeddings in a custom Magento database table as JSON-encoded vectors and run cosine similarity in PHP. For larger catalogues, use pgvector (a PostgreSQL extension) which supports native vector indexing and similarity queries. For very large catalogues or managed infrastructure, use Pinecone or Weaviate as dedicated vector stores. The Magento 2 RAG product search module stores the product ID alongside the embedding for result lookup.
Which embedding model should I use for Magento 2 RAG product search?
OpenAI text-embedding-3-small is the recommended starting model for Magento 2 RAG product search — it produces 1536-dimensional vectors, costs $0.02 per million tokens (under $1 to embed a 10,000-product catalogue), and delivers excellent semantic similarity for e-commerce product descriptions. Text-embedding-3-large provides higher quality at 3x the cost for stores where search quality is critical. Use the same model for both indexing and query embedding.
How does Magento 2 RAG product search handle product updates?
Hook into the catalog_product_save_after event using a Magento observer. When a product is saved, re-generate its embedding and update the vector store. For bulk changes (price imports, category reassignments), run a CLI command that re-embeds all affected products. The Magento 2 RAG product search index stays current because embeddings are regenerated whenever the product data that informs them changes.
Can Magento 2 RAG product search replace Elasticsearch?
Magento 2 RAG product search complements rather than replaces Elasticsearch. Elasticsearch excels at fast keyword matching, faceted filtering, and exact attribute queries (show all products in category X under price Y). RAG search excels at natural language queries and semantic matching. The best production approach is hybrid: use Elasticsearch for structured filtering and facets, and Magento 2 RAG product search for the semantic ranking layer that re-orders or augments Elasticsearch results.
How much does Magento 2 RAG product search cost to run?
The main cost is the OpenAI Embeddings API. Embedding a 10,000-product catalogue at 500 tokens per product costs approximately $0.10 with text-embedding-3-small. Each customer search query costs a fraction of a cent to embed. For a store with 1,000 daily searches, the Magento 2 RAG product search embedding cost is under $1 per month. The vector storage cost (pgvector on your existing database server, or Pinecone free tier for under 1 million vectors) is minimal for most catalogue sizes.
Need AI-Powered Search for Your Magento 2 Store?
CodeAtoZ implements Magento 2 RAG product search — vector embedding pipeline, pgvector integration, semantic query API, and hybrid Elasticsearch + RAG architecture.