DEV Community

Anton Makasin
Anton Makasin

Posted on

One Table, Many Categories: Indexable Attributes in a Single `ads` Table

Our marketplace has vehicles, real estate, services, and other categories. A car has mileage and fuel type. A house has bedrooms and area. A service has neither. Their shared listing data lives in one table, while category-specific attributes live in JSONB.

The Design Choice

We considered three approaches:

  1. Separate tables (vehicles, properties, services) — stronger database typing, but more duplicated paths for shared listing behavior.
  2. EAV (entity-attribute-value) — flexible, but multi-attribute filtering often needs repeated joins or grouped conditions.
  3. One table with JSONB — common columns stay relational, with a category discriminator and an attributes object for category-specific data.

We went with option 3.

The Schema

This is a simplified version of the schema:

CREATE TABLE ads (
    id                       BIGINT PRIMARY KEY,
    marketplace_category_id BIGINT NOT NULL,
    title                    VARCHAR(255) NOT NULL,
    currency                 VARCHAR(8) NOT NULL,
    attributes               JSONB,
    -- Other common fields omitted.
    is_published             BOOLEAN NOT NULL DEFAULT false
);
Enter fullscreen mode Exit fullscreen mode

If the application requires an object for every row, NOT NULL, a default, and a jsonb_typeof(attributes) = 'object' check can enforce that invariant. Our read paths also tolerate a missing value.

A vehicle's attributes:

{
    "brand_id": 17,
    "model": "rav4",
    "year": 2023,
    "fuel_id": 1,
    "trans_id": 2,
    "mileage": 45000,
    "features": ["leather_seats", "abs"]
}
Enter fullscreen mode Exit fullscreen mode

A real estate listing:

{
    "bedrooms": 3,
    "bathrooms": 2,
    "area_m2": 150,
    "features": ["pool", "parking"]
}
Enter fullscreen mode Exit fullscreen mode

Index the Query Shape

One blanket GIN index is not automatically the best answer. Our feature filter queries the nested array directly, so it gets an expression GIN index:

CREATE INDEX idx_ads_attributes_features
    ON ads USING GIN ((attributes->'features') jsonb_path_ops);
Enter fullscreen mode Exit fullscreen mode

The matching query uses containment:

SELECT id, title
FROM ads
WHERE marketplace_category_id = $1
  AND is_published = true
  AND attributes->'features' @> '["leather_seats", "abs"]'::jsonb;
Enter fullscreen mode Exit fullscreen mode

For scalar values and ranges, expression indexes are often a better match:

CREATE INDEX idx_ads_attributes_brand_id
    ON ads (((attributes->>'brand_id')::integer));

CREATE INDEX idx_ads_attributes_year
    ON ads (((attributes->>'year')::integer));
Enter fullscreen mode Exit fullscreen mode

A full-column GIN (attributes jsonb_path_ops) can be effective for attributes @> ... and JSONPath queries. Compared with the default jsonb_ops class, jsonb_path_ops supports fewer operators but usually produces a smaller, more specific index for the operators it does support. The PostgreSQL JSON documentation covers the trade-off.

Indexes should also account for relational predicates such as category and publication state. Use EXPLAIN (ANALYZE, BUFFERS) to verify that PostgreSQL combines or chooses the indexes as expected. The DDL above demonstrates index shape, not a production migration procedure: for large live tables, plan for locking and consider concurrent index creation.

Allowlisted Filters in Go

The HTTP layer maps public filter names to trusted SQL expressions and validated values. User input never becomes a column name or SQL fragment:

func applyFilter(q *gorm.DB, key, value string) *gorm.DB {
    switch key {
    case "brand":
        id, err := strconv.Atoi(value)
        if err != nil || id <= 0 {
            return q
        }
        return q.Where("(ads.attributes->>'brand_id')::int = ?", id)

    case "year_from":
        year, err := strconv.Atoi(value)
        if err != nil || year < 1900 {
            return q
        }
        return q.Where("(ads.attributes->>'year')::int >= ?", year)

    default:
        return q
    }
}
Enter fullscreen mode Exit fullscreen mode

Silently dropping an unknown key is not, by itself, SQL-injection protection. The protection comes from allowlisting SQL expressions, parsing values into expected types, and binding values as parameters.

The Features Array

Some attributes are arrays: features: ["leather_seats", "abs"]. We query these with containment:

-- Listings that contain both features
WHERE attributes->'features' @> '["leather_seats", "abs"]'::jsonb
Enter fullscreen mode Exit fullscreen mode

At the HTTP boundary, stored codes can map to localized, human-readable slugs. Only allowlisted slugs should map back to database codes; the remaining filters can stay in query parameters.

Trade-Offs

Pro: Adding an attribute does not require a new table column.

Con: It still requires application validation, form and rendering changes, and possibly an index migration. Without additional CHECK constraints, PostgreSQL will not stop a vehicle from containing bedrooms.

Pro: Shared listing, moderation, and publication workflows can operate on one table without UNION.

Con: JSONB values have weaker built-in typing than dedicated columns. Cast-based indexes and queries also require stored values to have a valid shape.

Con: Frequently queried or constrained attributes may eventually deserve real columns. JSONB should not become a reason to avoid schema design.

For diverse and evolving listing types, a hybrid design—relational common fields plus validated JSONB attributes—can be a practical middle ground. The key is to index actual query shapes and keep the application-level schema explicit.


This article is based on lessons from building Towami, a multi-country marketplace and white-label storefront platform. Follow for more practical notes on Go, HTMX, infrastructure, and SaaS.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The trade-off table is what sold me — especially the honest con that JSONB will not stop a vehicle from containing bedrooms, and that adding an attribute still costs you application validation, form changes, and possibly an index migration. The index advice is the part I would steal: a blanket GIN is not the answer, and the expression index on (attributes->>'brand_id')::integer is exactly the kind of targeted index that only works if the stored type is always an integer, which brings the validation point right back. What is the trigger in practice that promotes an attribute out of JSONB into a real column — query frequency, a CHECK constraint you cannot express in JSONB, or a slow query in EXPLAIN ANALYZE? And when that promotion happens, how do you clean up the rows that already stored the old shape?