Search & Analytics#

Most applications eventually need full-text search, analytics dashboards, or both. This section covers the systems and patterns for indexing, querying, and analysing large datasets — from Elasticsearch to data lake architectures.


Why Not Just SQL LIKE?#

SELECT * FROM products WHERE name LIKE '%wireless headphones%';
ProblemExplanation
No relevance rankingResults are unordered — no way to rank “best match”
No fuzzy matching“headphnes” won’t match “headphones”
No stemming“running” won’t match “run”
Full table scanLIKE '%term%' cannot use indexes — O(n)
No synonym support“laptop” won’t match “notebook”

Search Engine Architecture#

Documents → Analyser (tokenise, stem, normalise) → Inverted Index → Query → Ranked Results

Inverted index: maps each term to the list of documents containing it:

"wireless"    → [doc1, doc3, doc7]
"headphone"   → [doc1, doc5, doc9]
"bluetooth"   → [doc1, doc3, doc5]

Elasticsearch / OpenSearch#

ConceptDescription
IndexCollection of documents (like a database table)
DocumentJSON object (like a row)
MappingSchema definition (field types, analysers)
ShardHorizontal partition of an index
ReplicaCopy of a shard for redundancy and read scaling
AnalyserPipeline: character filter → tokeniser → token filters

When to Use Search vs Database#

Use Search EngineUse Database
Full-text search with relevanceExact lookups by ID or key
Fuzzy matching, typo toleranceStructured queries (joins, aggregations)
Faceted navigation (filters + counts)Transactions, ACID
Log aggregation and analysisPrimary data store
Autocomplete / suggestionsSource of truth

Rule: The database is the source of truth. The search index is a derived, eventually consistent view.


OLTP vs OLAP#

OLTPOLAP
PurposeServe transactionsAnalyse data
QueriesSimple, by primary keyComplex, aggregating millions of rows
SchemaNormalised (3NF)Denormalised (star/snowflake schema)
LatencyMillisecondsSeconds to minutes
ExamplesPostgreSQL, MySQL, DynamoDBBigQuery, Redshift, Snowflake, ClickHouse
Optimised forWrites + point readsColumnar scans + aggregations

Column-Oriented Storage#

OLAP databases store data by column, not by row:

Row-oriented (OLTP):
[id:1, name:"Alice", amount:100] [id:2, name:"Bob", amount:200] ...

Column-oriented (OLAP):
id:     [1, 2, 3, 4, ...]
name:   ["Alice", "Bob", "Carol", ...]
amount: [100, 200, 150, 300, ...]

Benefits: better compression (similar values together), only read columns needed for the query, vectorised processing.


Analytics Pipeline#

The Modern Data Stack#

Sources → Ingestion → Storage → Transformation → Serving → Visualisation
StageTools
IngestionKafka, Kinesis, Firehose, Debezium (CDC), Airbyte
StorageS3 (data lake), Snowflake, BigQuery, Redshift
Transformationdbt, Spark, Airflow
ServingMaterialised views, OLAP cubes, pre-aggregated tables
VisualisationGrafana, Metabase, Looker, Tableau

Batch vs Stream Processing#

BatchStream
LatencyMinutes to hoursSeconds to milliseconds
CompletenessFull datasetPartial (windows, watermarks)
ToolsSpark, dbt, AirflowKafka Streams, Flink, Kinesis
Use caseDaily reports, ML trainingReal-time dashboards, alerting
ComplexityLowerHigher (ordering, exactly-once)

Time-Series Databases#

Optimised for timestamped data (metrics, IoT, financial data):

DatabaseUse Case
InfluxDBMetrics, IoT
TimescaleDBPostgreSQL extension for time-series
PrometheusInfrastructure metrics (pull-based)
ClickHouseAnalytics + time-series at scale
Amazon TimestreamManaged AWS time-series

Design Patterns#

  • Downsampling: Aggregate old data (1s → 1min → 1h) to reduce storage
  • Retention policies: Auto-delete data older than N days
  • Tag-based queries: Filter by dimensions (host, service, region) before aggregating

Data Lake Architecture#

LayerContentsFormat
Raw (Bronze)Unprocessed source dataJSON, CSV, Parquet
Cleaned (Silver)Validated, deduplicated, typedParquet, Delta Lake
Curated (Gold)Business-ready aggregatesParquet, materialised views

Lake vs Warehouse#

Data LakeData Warehouse
SchemaSchema-on-read (flexible)Schema-on-write (enforced)
Data typesStructured + unstructuredStructured only
CostLow (object storage)Higher (compute + storage)
Query speedSlower (unless indexed)Fast (optimised engine)
Use caseML training, raw archivesBI dashboards, reports

Lakehouse (Delta Lake, Apache Iceberg): combines lake flexibility with warehouse features (ACID, time travel, schema evolution).


Key Takeaways#

  • Full-text search requires an inverted index (Elasticsearch/OpenSearch). SQL LIKE does not scale.
  • Search engines are derived views, not sources of truth. Sync from the database.
  • OLTP (PostgreSQL) for transactions, OLAP (BigQuery/ClickHouse) for analytics. Different tools for different jobs.
  • Column-oriented storage makes analytical queries orders of magnitude faster than row-oriented.
  • Batch processing for completeness, stream processing for freshness. Most systems need both.
  • Data lake (cheap, flexible) → data warehouse (fast, structured) → lakehouse (both).