Build an In-Memory Database with Querying and Indexing
Data Structure DesignModel answerLast 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
-
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
Nonewhen projected.
- Stores a record represented as key-value pairs (e.g., Python
-
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.
- Multiple filters are combined using logical
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.
-
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).
- Support secondary index generation via
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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Architecture
To construct a performant and well-structured in-memory storage engine, we separate raw data management from query optimization and execution:
-
Storage Engine (Primary Heap & Index Directory):
- Records are stored in a key-value structure mapping a unique integer
row_idto the actual dictionary representation. - Secondary indices do not duplicate record content; instead, they map field values to sets or ordered lists of
row_idvalues.
- Records are stored in a key-value structure mapping a unique integer
-
Index Structures:
- Hash Index: Maps specific field values to a
setof matchingrow_ids. Provides $O(1)$ point lookups for equality conditions (=). - Range Index (Sorted Array / B-Tree equivalent): Maintains keys in sorted order along with associated
row_ids. For binary search operations in standard library Python, parallel sorted lists forkeysandrow_idsallow logarithmic range boundary discovery ($O(\log N)$ point boundary search).
- Hash Index: Maps specific field values to a
-
Query Engine Pipeline:
- Candidate Selection: Evaluate available indices matching query filters. Intersect returned
row_idsets to derive a restricted candidate pool. If no indices are applicable, fall back to a full scan over all primary keys. - Filtering: Perform exact validation on candidate records against all query conditions.
- Sorting: If ordering by a single column with an active range index, traverse the index order directly. Otherwise, apply a standard comparison-based sort using custom key extraction that handles missing (
None) values. - Projection: Construct the final output records containing only the requested keys.
- Candidate Selection: Evaluate available indices matching query filters. Intersect returned
Implementation
import bisect
import operator
from collections import defaultdict
from itertools import chain
# Supported comparison operators
COMPARATORS = {
"=": operator.eq,
"!=": operator.ne,
"<": operator.lt,
"<=": operator.le,
">": operator.gt,
">=": operator.ge,
}
class HashIndex:
"""Hash-based index supporting fast exact equality matching."""
def __init__(self):
self.entry_map = defaultdict(set)
def add(self, key, row_id):
if key is not None:
self.entry_map[key].add(row_id)
def search(self, op, val):
if op == "=":
return set(self.entry_map.get(val, ()))
return None # Hash indices do not support inequality or range searches
class RangeIndex:
"""Sorted array index supporting point and range queries."""
def __init__(self):
self.sorted_keys = []
self.sorted_rids = []
self.null_rids = []
def add(self, key, row_id):
if key is None:
self.null_rids.append(row_id)
return
# Locate position to maintain sorted order
idx = bisect.bisect_right(self.sorted_keys, key)
self.sorted_keys.insert(idx, key)
self.sorted_rids.insert(idx, row_id)
def search(self, op, val):
keys, n = self.sorted_keys, len(self.sorted_keys)
left_idx = lambda: bisect.bisect_left(keys, val)
right_idx = lambda: bisect.bisect_right(keys, val)
# Mapping operators to index slices
if op == "=":
lo, hi = left_idx(), right_idx()
elif op == "<":
lo, hi = 0, left_idx()
elif op == "<=":
lo, hi = 0, right_idx()
elif op == ">":
lo, hi = right_idx(), n
elif op == ">=":
lo, hi = left_idx(), n
else:
return None
return set(self.sorted_rids[lo:hi])
def get_ordered_rids(self, ascending=True):
if ascending:
return chain(self.sorted_rids, self.null_rids)
return chain(self.null_rids, reversed(self.sorted_rids))
class DataTable:
"""Manages table storage, row insertion, indices, and candidate extraction."""
def __init__(self):
self.records = {}
self.current_id = 0
self.hash_indices = {}
self.range_indices = {}
def insert_row(self, record):
rid = self.current_id
self.current_id += 1
stored_dict = dict(record)
self.records[rid] = stored_dict
# Populate defined indices
for field, index in self.hash_indices.items():
index.add(stored_dict.get(field), rid)
for field, index in self.range_indices.items():
index.add(stored_dict.get(field), rid)
return rid
def build_index(self, field, index_type):
if index_type == "hash":
if field in self.hash_indices:
return
index = HashIndex()
self.hash_indices[field] = index
elif index_type == "range":
if field in self.range_indices:
return
index = RangeIndex()
self.range_indices[field] = index
else:
raise ValueError(f"Unsupported index type: {index_type}")
# Backfill index with existing data
for rid, record in self.records.items():
index.add(record.get(field), rid)
def get_candidate_ids(self, filters):
candidate_set = None
for field, op, val in filters:
matched_ids = None
if field in self.hash_indices:
matched_ids = self.hash_indices[field].search(op, val)
if matched_ids is None and field in self.range_indices:
matched_ids = self.range_indices[field].search(op, val)
if matched_ids is not None:
if candidate_set is None:
candidate_set = matched_ids
else:
candidate_set &= matched_ids
return candidate_set
class RelationalStore:
"""Top-level Database interface executing queries and managing tables."""
def __init__(self):
self.tables = {}
def insert(self, table_name, record):
if table_name not in self.tables:
self.tables[table_name] = DataTable()
return self.tables[table_name].insert_row(record)
def create_index(self, table_name, field, index_type="hash"):
if table_name not in self.tables:
self.tables[table_name] = DataTable()
self.tables[table_name].build_index(field, index_type)
def _eval_row(self, row, filters):
for field, op, target in filters:
val = row.get(field)
if val is None or not COMPARATORS[op](val, target):
return False
return True
def query(self, table_name, projection=None, filters=None, sort_by=None):
if table_name not in self.tables:
return []
table = self.tables[table_name]
filters = filters or []
# Step 1: Candidate set retrieval via indices
candidates = table.get_candidate_ids(filters)
# Parse ordering instructions
sort_fields, ascending = sort_by if sort_by else ([], True)
if isinstance(sort_fields, str):
sort_fields = [sort_fields]
# Step 2 & 3: Optimizing candidate retrieval & sorting
if len(sort_fields) == 1 and sort_fields[0] in table.range_indices:
# Index-accelerated sort path
rid_stream = table.range_indices[sort_fields[0]].get_ordered_rids(ascending)
if candidates is not None:
rid_stream = (rid for rid in rid_stream if rid in candidates)
matched_rows = [
table.records[rid]
for rid in rid_stream
if self._eval_row(table.records[rid], filters)
]
else:
# Standard path
rids = candidates if candidates is not None else table.records.keys()
matched_rows = [
table.records[rid]
for rid in rids
if self._eval_row(table.records[rid], filters)
]
if sort_fields:
matched_rows.sort(
key=lambda r: tuple(
(r.get(f) is None, r.get(f)) for f in sort_fields
),
reverse=not ascending,
)
# Step 4: Projection
if not projection or projection == ["*"]:
return [dict(r) for r in matched_rows]
return [
{field: row.get(field) for field in projection} for row in matched_rows
]
Complexity Analysis
- Insert: $O(1)$ record storage plus $O(\log N)$ or $O(1)$ updating time per indexed field, where $N$ is total table rows.
- Index Lookup:
- Hash Index: $O(1)$ lookup time.
- Range Index: $O(\log N + K)$ where $K$ is the number of matching candidate keys.
- Filtering: $O(C \cdot F)$ where $C$ is candidate row count ($C \le N$) and $F$ is number of filter conditions.
- Sorting:
- Accelerated (single indexed range field): $O(C)$.
- In-memory standard fallback: $O(C \log C)$.
- Space Complexity: $O(N \cdot D + I \cdot N)$ where $D$ is key count per record and $I$ is total defined secondary indices.