Data Modeling for Multi-Valued Attributes: Index Design Practices Using Gemini as a Sample Dataset

    This article uses the Gemini zodiac dataset as a sample to show how to model entities whose attributes have no fixed cardinality. It covers a four-way attribute classification, three storage options for multi-valued fields (junction tables, array or JSON columns, and bitmap compression), closed-interval date and derived-field rules, validation for metrics with undefined calculation logic, query patterns with matching index strategies, and caching plus batch-write practices. Readers will get a reusable, extensible, and observable design approach for any dataset where one entity maps to many values and metric definitions are not yet confirmed.

    1. Why Gemini Is Worth Modeling

    Gemini (May 21 to June 21) has one striking trait in the source material: almost none of its attributes are single-valued. It has two ruling planets, Mercury and the Moon; the metal is mercury; there are five lucky numbers (1, 5, 9, 19, 25); the lucky colors are yellow and orange; it rules the third house, its modality is mutable, its polarity is positive, and its ruling deity is Mercury; the body parts it governs are the shoulders, arms, and lungs; the sign is further split into Gemini I, Gemini II, and Gemini III; and the opposite sign is Sagittarius. On top of that come quantitative fields such as rank, base value, four relationship scores (friendship, love, marriage, family), index 80, and a proposed correction of -12, plus a set of nine boolean compatibility flags (appreciation, learning, work, attention, coordination, same-kind, lover, friend, colleague), of which only “friend” is checked.

    For developers, the difficulty is not the number of fields but the unfixed cardinality: one entity may map to zero, one, or N values. The intuitive “one attribute, one column” design immediately runs into three problems: column explosion, query conditions that cannot be enumerated, and a schema change every time a new value appears. Using this dataset as a sample, this article presents a reusable modeling and querying approach.

    2. Attribute Classification: Splitting Mixed Fields into Four Groups

    The first step is normalization: group all information into four semantic categories so that enums, measures, and booleans do not end up mixed in one wide table.

    • Single-valued enums: foreign name, element (air), modality (mutable), polarity (positive), main ruling planet (Mercury), ruling deity, ruling house (third house), opposite sign, lucky weekday, Chinese name.
    • Multi-valued sets: ruling planet set, lucky number set, lucky color set, body part set, decan set, metal set.
    • Measures: rank, base value, four relationship scores, index, proposed correction.
    • Boolean flags: the checked state of the nine compatibility dimensions.

    The immediate payoff is clear: enums suit low-cardinality indexes and lookup tables; sets need a dedicated relational structure; measures suit range queries and aggregation; booleans suit bitmap or bitwise compression.

    3. Three Storage Forms for Multi-Valued Fields and Their Trade-offs

    Multi-valued sets are the core of this article. Three common engineering options exist, each with its own boundaries.

    Option A: Junction tables (normalized modeling). Create one relation table per multi-valued attribute, forming a one-to-many relationship between the entity table and the values. It supports exact filtering on any value, indexing, and adding new values without schema changes; the cost is joins on read and transactions to keep writes consistent.

    1. -- Entity main table: single values and measures only
    2. CREATE TABLE entity_profile (
    3. entity_id BIGINT PRIMARY KEY,
    4. name_cn VARCHAR(32) NOT NULL, -- Gemini (Chinese name)
    5. name_en VARCHAR(32) NOT NULL, -- Gemini
    6. element_type VARCHAR(16) NOT NULL, -- Air sign
    7. modality VARCHAR(16) NOT NULL, -- Mutable
    8. polarity VARCHAR(8) NOT NULL, -- Positive
    9. ruling_house VARCHAR(16) NOT NULL, -- Third house
    10. opposite_sign VARCHAR(32) NOT NULL, -- Sagittarius
    11. lucky_weekday VARCHAR(16) NOT NULL, -- Tuesday
    12. rank_no INT, -- Rank
    13. base_value INT, -- Base value
    14. index_score INT, -- Index
    15. correction INT -- Proposed correction
    16. );
    17. -- Unified multi-valued attribute table: attribute_code distinguishes the kind
    18. CREATE TABLE entity_attr (
    19. entity_id BIGINT NOT NULL,
    20. attribute_code VARCHAR(32) NOT NULL, -- RULED_PLANET / LUCKY_NUMBER ...
    21. attr_value VARCHAR(64) NOT NULL,
    22. value_weight DECIMAL(6,3) DEFAULT 1.000,
    23. PRIMARY KEY (entity_id, attribute_code, attr_value)
    24. );
    25. CREATE INDEX idx_attr_lookup ON entity_attr (attribute_code, attr_value);

    Option B: Array or JSON column. Store the whole set in one column and read all values at once. It fits “read whole, write whole, rarely filter by element” scenarios. The downsides are weak element-level filtering, limited index support, and no natural way to express per-value weights.

    Option C: Bitmap compression. This is highly efficient for the boolean flags (nine compatibility dimensions): nine bits express every combination, and bitwise operations can test several conditions at once.

    1. bit0 appreciation | bit1 learning | bit2 work | bit3 attention | bit4 coordination
    2. bit5 same-kind | bit6 lover | bit7 friend | bit8 colleague
    3. Sample "only friend is true" => 0b100000000 => 256

    In practice, mix them: sets go with Option A, booleans go with Option C, and a display-only snapshot can keep a redundant copy in Option B form to reduce read amplification.

    4. Modeling Date Ranges and Decans

    The birth date range May 21 to June 21 is a closed interval that is safe across year boundaries, but comparing it as strings is risky. The proper approach is to store month-day offsets or reference dates under a unified year, and to declare the boundary-inclusive rule explicitly:

    1. from datetime import date
    2. START = (5, 21)
    3. END = (6, 21)
    4. def in_gemini(d: date) -> bool:
    5. md = (d.month, d.day)
    6. return START <= md <= END # Tuple comparison avoids cross-year issues
    7. # Decans (three segments) are derived by linear mapping over the interval
    8. def decan(d: date) -> int:
    9. total = (END[0] - START[0]) * 31 + (END[1] - START[1])
    10. offset = (d.month - START[0]) * 31 + (d.day - START[1])
    11. return min(3, offset * 3 // total + 1) # Gemini I / II / III

    Three points matter: boundary ownership must be unique, so May 21 and June 21 cannot both fall into two intervals; timezone and calendar must be unified, with normalization done before insertion; and derived fields such as decans should be marked as recomputable rather than treated as the single source of truth.

    5. Validating Quantitative Fields and the “Proposed Correction”

    Rank, base value, the four scores, index, and proposed correction form a set of measures. Their risk is undefined semantics: the source material never gives the calculation rule linking index 80 to the four scores of 5 each, nor the direction in which the -12 correction applies. The correct engineering stance is not to invent formulas, but to tag these fields with their source and confidence, and to expose a replaceable calculation strategy interface in the service layer:

    1. class ScorePolicy:
    2. def compose(self, base: int, dims: dict, correction: int) -> int:
    3. raise NotImplementedError

    Also build three layers of data quality checks: type and value-domain validation (scores constrained to the agreed range), consistency validation (whether derived metrics conflict with raw ones), and drift monitoring (alert when repeated collections of the same entity differ beyond a threshold). This keeps the system usable when definitions are missing, instead of hardcoding uncertain rules into business logic.

    6. Query Patterns and Index Design

    Four typical query classes map to different index strategies:

    1. Filtering on a single-valued enum (air sign, third house): low cardinality, suitable as a leading column in a composite index or a separate lookup table.
    2. Filtering on a set element (ruling planet includes the Moon, lucky number includes 9): use the (attribute_code, attr_value) index on the junction table, then fetch the entity.
    3. Multi-condition intersection (matching both yellow and 5): intersect across attributes, filtering the highest-selectivity condition first to shrink the intermediate result set.
    4. Measure sorting and pagination (index descending): index the sort column and use cursor pagination instead of deep offsets to avoid scan amplification from large offsets.

    Sample query:

    1. SELECT p.entity_id, p.name_cn
    2. FROM entity_attr a
    3. JOIN entity_profile p ON p.entity_id = a.entity_id
    4. WHERE a.attribute_code = 'LUCKY_NUMBER' AND a.attr_value = '9'
    5. INTERSECT
    6. SELECT p.entity_id, p.name_cn
    7. FROM entity_attr a
    8. JOIN entity_profile p ON p.entity_id = a.entity_id
    9. WHERE a.attribute_code = 'LUCKY_COLOR' AND a.attr_value = 'yellow'
    10. ORDER BY p.index_score DESC
    11. LIMIT 20;

    7. Caching, Batch Writes, and Cloud Deployment

    Read-heavy, write-light is the typical profile of this kind of reference data, so multi-level caching fits: a local cache holds hot enum dictionaries, a distributed cache holds assembled entity results, and an attribute version number drives invalidation to avoid the churn of expiring keys one by one. For bulk import, write grouped by attribute, cap the batch size, make failures replayable, and keep repeated runs idempotent.

    On Baidu AI Cloud, you can compose only generic product categories: a relational database for the normalized model, object storage for raw collected files and snapshots, a message queue for peak shaving and asynchronous index building, logging plus monitoring and alerting for data quality and query latency, and a container platform for stateless query services that scale elastically. All capabilities are described in generic category terms; concrete choices should be evaluated against data volume and consistency requirements.

    8. Common Pitfalls

    • Packing multi-valued attributes into comma-separated strings, which breaks both indexing and validation.
    • Comparing date ranges as strings, ignoring boundary inclusivity and calendar unification.
    • Inventing formulas for quantitative fields whose semantics are unclear, creating hidden business risk.
    • Conflating derived fields (decan, index) with raw fields, with no recomputation entry point.
    • Expressing boolean flags as multiple columns, forcing a schema change whenever a dimension is added.
    • Unbounded deep pagination, which causes a performance cliff as data grows.

    9. Summary

    Starting from Gemini, a seemingly scattered dataset, a general path emerges: classify attributes first, then choose the right form for multi-valued sets among junction tables, arrays, and bitmaps, then fix the rules for dates and derived fields, and finally design indexes and caching around the four query patterns. When metric definitions are incomplete, keep room to evolve with strategy interfaces and quality checks instead of hardcoding assumptions. With this method, any dataset with “one entity, many values, and unconfirmed metric definitions” can be turned into a clear, extensible, and observable implementation quickly.