KatInterview

Build an In-Memory Database with Querying and Indexing

Data Structure DesignModel answer
MediumModel answerData Structure Designin-memory-dbindexingdata-structures

Last updated

Design and write code for an in-memory document store that supports dynamic schemas, predicate filtering, projection, ordering, and index optimization.

Create a lightweight, in-memory database engine supporting flexible schema storage, record insertion, querying with predicates, column projection, and custom sorting.

Requirements

  1. Insertion: insert(table, record)

    • Stores a record represented as key-value pairs (e.g., Python dict).
    • Tables are schema-agnostic (different records can have distinct keys). Missing keys evaluate as non-matches during conditional evaluations and output None when projected.
  2. Querying: query(table, projection=None, filters=None, sort_by=None)

    • projection: List of fields to extract. If omitted or equal to ["*"], all fields of matching records are returned.
    • filters: A list of criteria in the form (field, operator, target_value). Supported operators: =, !=, <, <=, >, >=.
      • Multiple filters are combined using logical AND.
      • Null values (None) or missing attributes fail comparisons.
    • sort_by: Tuple (field_list, ascending_flag) specifying fields to sort on and a boolean indicating direction. Missing values are sorted last when ascending and first when descending.
  3. Indexing Capabilities:

    • Support secondary index generation via create_index(table, field, index_type) with types "hash" and "range".
    • Utilize existing indices during query execution to eliminate unnecessary full table scans (index-based selection and index-backed sorting).

Example Usage

db = RelationalStore()
db.insert("users", {"id": 1, "name": "Alice", "score": 90})
db.insert("users", {"id": 2, "name": "Bob", "score": 75})

db.create_index("users", "score", index_type="range")

# Fetch name and score for users with score >= 80, ordered by score descending
res = db.query(
    "users",
    projection=["name", "score"],
    filters=[("score", ">=", 80)],
    sort_by=(["score"], False)
)
# Expected output: [{"name": "Alice", "score": 90}]

Hints

Hint 1

Assign each record a stable auto-incrementing integer key (row_id) upon insertion so indices store record references rather than full object duplicates.

Hint 2

When executing queries with multiple filter criteria, compute the candidate row IDs by intersecting the sets returned by indexed field lookups.

Hint 3

Consider using standard binary search utilities (like `bisect` in Python) to implement range lookups on sorted key arrays.