Modeling E-commerce Catalogs: Handling Hierarchical Attributes
In this lesson, you will learn how to efficiently store and query diverse, hierarchical product attributes within a document-based e-commerce catalog using the "Attribute Pattern."
When building an e-commerce catalog, you inevitably face the "sparse attributes" problem. A laptop has RAM and CPU Speed, while a shirt has Material and Size. Storing these in a rigid relational table leads to massive amounts of NULL values. In a document model, we solve this by flattening attributes into a standardized array of objects, which allows us to index them effectively.
The Attribute Pattern
Instead of storing attributes as individual keys (which makes indexing and querying difficult if the schema varies), we store them as an array of key-value pairs.
Consider this product document:
{
"product_name": "Ultra-Slim Laptop",
"attributes": [
{ "k": "RAM", "v": "16GB", "u": "size" },
{ "k": "CPU", "v": "Intel i7", "u": "spec" },
{ "k": "Color", "v": "Space Gray", "u": "aesthetic" }
]
}
Why Indexing Matters
If you query for "RAM equals 16GB" using a standard document search, you might be tempted to look at the whole document. However, by using the Attribute Pattern, you can create a multikey index on the attributes field:
db.products.createIndex({ "attributes.k": 1, "attributes.v": 1 })
This index allows the database engine to perform a highly efficient range or equality scan specifically on the attribute metadata. Because the attributes are stored in a predictable array format, the index remains compact even if thousands of unique attribute types exist across your entire catalog.
When you need to perform a filtered search (e.g., "Find all laptops with 16GB RAM"), the database doesn't have to scan the entire collection. It simply traverses the index tree for the k (key) and v (value) pairs, drastically reducing I/O and latency. This approach provides the flexibility of a document store while retaining the search performance expected of a high-traffic e-commerce platform.
Key Takeaway: By normalizing disparate attributes into a consistent k/v array structure, you enable the use of multikey indexing to query high-cardinality product data without the overhead of rigid schema constraints.