Databases
Model, index, query, aggregate and operate Elasticsearch clusters, from mappings to vector search.
A path through Elasticsearch for backend engineers: cluster architecture, mappings and field types, the document APIs, Query DSL and other query languages, aggregations, relevance tuning, and running a cluster safely in production. Each subject links the official Elastic documentation.
The subjects follow the roadmap.sh Elasticsearch roadmap.
Elasticsearch is a distributed search and analytics engine built on Apache Lucene, driven entirely through a JSON-over-HTTP API. Before indexing anything, get comfortable with JSON, REST semantics and where a search engine fits next to your primary database.
Every request body, document and response in Elasticsearch is JSON. Know objects, arrays, nesting and the fact that JSON has no date type, so dates travel as strings or epoch numbers.
Elasticsearch speaks HTTP: PUT creates or replaces, POST creates with a generated ID or runs an action, GET reads, DELETE removes. Status codes like 404 and 409 tell you what went wrong.
A relational database is the source of truth with transactions and joins; Elasticsearch is near-real-time, denormalised and tuned for relevance ranking and aggregations. Most systems keep both and sync data into the index.
Elasticsearch stores and searches, Logstash (or Beats and Elastic Agent) ships and transforms data, and Kibana visualises it. The combination is the classic self-hosted log and metrics platform.
Full-text site and product search, log and metrics analytics, security event analysis, autocomplete, geo search and, more recently, vector retrieval for RAG applications.
Get a cluster you can break: a single-node container locally, or a hosted deployment. Security is on by default in 8.x, so expect TLS and an elastic password from the first start.
Run the official image with discovery.type=single-node for development. Give it enough memory, and raise vm.max_map_count on Linux hosts or the node refuses to start in production mode.
Elastic's managed service, available as hosted deployments or a serverless offering. It handles upgrades, snapshots and scaling, which removes most of the operations work from a learning setup.
Dev Tools in Kibana gives an editor for raw requests with autocompletion, and can copy them as cURL. It is the fastest way to experiment with queries and mappings.
The objects you name in API calls. The database analogies in the labels help at first, but break down quickly: an index has no joins, and documents are schemaless JSON governed by a mapping.
One or more nodes sharing a cluster.name, with one elected master managing state. Health is green, yellow (replicas unassigned) or red (a primary is missing).
A single running Elasticsearch process. Each node has roles that decide whether it stores data, can become master, or only routes requests.
A named collection of documents with one mapping, split into shards. Aliases and data streams let applications point at a stable name while the indices behind it change.
A JSON object stored in an index, with metadata such as _index, _id and _source. Documents are immutable on disk; an update writes a new version and marks the old one deleted.
The _id uniquely identifies a document in an index. Supply your own to make writes idempotent, or let Elasticsearch generate one for faster append-only ingestion.
Node roles decide how work is spread across machines. Small clusters let every node do everything; larger ones dedicate nodes to master duties, data tiers or coordination.
Nodes that can be elected to manage cluster state: index creation, shard allocation, membership. Run three dedicated ones in production so a quorum survives losing one.
Hold shards and execute indexing, search and aggregations, so they need the most CPU, memory and disk. Specialised roles like data_hot and data_warm place data by age.
Every node can receive a request, fan it out to the shards involved and merge the results. A node with no roles does only this, offloading heavy reduce work in big clusters.
An index is split into primary shards, each a self-contained Lucene index, and copied into replicas. Shard count and size are the main levers for throughput and recovery time.
Every document lives in exactly one primary, chosen by hashing its routing value. The count is fixed at index creation; change it with the split, shrink or reindex APIs.
Copies of a primary on other nodes that provide failover and extra search capacity. number_of_replicas can be changed at any time; a single node cannot host its own replicas.
Two halves of a partitioned cluster each electing a master and diverging. Since 7.0, voting configurations and quorums prevent it automatically; the old minimum_master_nodes setting is gone.
A mapping is the schema of an index: which fields exist, their types and how text is analysed. Most field types cannot be changed once data is indexed, so getting the mapping right early saves a reindex later.
Define fields up front with PUT /index and a mappings block, or add new ones with the put mapping API. Pair it with index templates so new indices get the same schema.
Elasticsearch guesses types for unseen fields: strings become text with a keyword sub-field. Control it with dynamic: strict, false or runtime, and with dynamic templates.
Indexing documents with arbitrary keys creates thousands of fields and bloats cluster state. index.mapping.total_fields.limit guards it; the fix is usually flattened or a key/value structure.
Field types decide how values are indexed and which queries work on them. The biggest decision is text versus keyword; the next is how to model objects and arrays.
long, integer, double, float, scaled_float and more. Identifiers you never range-query are often better as keyword, which is faster for term lookups.
Accepts true/false and the strings "true"/"false". Useful for filters and terms aggregations, which return 1 and 0 as keys.
Stored internally as UTC epoch milliseconds; the format parameter controls what strings are accepted. Use date_nanos when millisecond precision is not enough.
Latitude/longitude pairs for distance and bounding-box queries, sorting by distance and geo aggregations. Beware that array form is [lon, lat].
Analysed into terms for full-text search. Not usable for sorting or aggregations without enabling fielddata, which is why dynamic mapping adds a keyword sub-field.
Indexed as one exact term, for IDs, tags, status codes and email addresses. Supports term queries, sorting and aggregations through doc values; a normalizer can lowercase it.
Inner JSON objects are flattened into dotted field paths. Arrays of objects lose the link between fields of the same element, so a query can match values from different elements.
Indexes each array element as a hidden separate document so fields stay correlated. Requires nested queries and aggregations, and costs more at index and query time.
Maps a whole object as a single field whose leaf values are keywords. Ideal for unpredictable labels or metadata where you only need exact matching.
The document and index APIs you use daily. Writes are visible to search only after a refresh (one second by default), though a get by ID is real-time.
PUT /my-index with optional settings, mappings and aliases. Shard count is set here; index templates apply defaults to indices matching a pattern.
DELETE /my-index removes the index and all its data immediately. Deleting by wildcard can be disabled with action.destructive_requires_name.
PUT /idx/_doc/1 writes or replaces a document; POST /idx/_doc generates an ID; _create fails if it already exists. refresh=wait_for makes the write visible before returning.
GET /idx/_doc/1 returns the source and metadata in real time. _source_includes trims the response; _mget fetches many in one round trip.
POST /idx/_update/1 with a partial doc or a Painless script. It is a reindex under the hood; retry_on_conflict and if_seq_no/if_primary_term handle concurrent writers.
DELETE /idx/_doc/1 marks a document deleted; space is reclaimed when segments merge. For many documents at once, use delete by query.
Ingesting one document per request wastes most of the time on round trips. The bulk API batches many operations in one newline-delimited request and is how every client library loads data.
NDJSON pairs of an action line (index, create, update, delete) and a source line, ending with a newline. Always check the errors flag, since individual items can fail inside a 200 response.
Tune batch size by measurement (a few MB is a common start), send from parallel workers, raise refresh_interval or set it to -1 during big loads, and drop replicas temporarily.
Because mappings are mostly immutable, changing a field type means copying data into a new index. These APIs run server-side as tasks you can monitor, throttle and cancel.
Copies documents from a source index (or a remote cluster) into a destination with a new mapping, optionally transforming them via a script or ingest pipeline. Swap an alias afterwards for zero downtime.
Rewrites every matching document in place, with a script or just to pick up a newly added mapping field. Use conflicts=proceed and wait_for_completion=false on large indices.
Deletes every document matching a query. For time-based data, dropping whole indices is far cheaper than deleting documents out of them.
Elasticsearch accepts several ways to ask questions. Query DSL is the full-power JSON format; the others trade flexibility for familiarity or suit a specific job like piping analytics or hunting event sequences.
The JSON query language sent to _search. Queries nest freely, and every feature (scoring, aggregations, highlighting) is available here first.
A piped query language (FROM logs | WHERE status >= 500 | STATS count(*) BY host) executed by a dedicated engine. Great for analytics and exploration in Kibana.
Event Query Language for time-ordered event data, with sequence queries that find ordered chains of events. Built for security threat hunting.
A read-only SQL interface over indices via _sql, plus JDBC/ODBC drivers for BI tools. The translate API shows the Query DSL it generates.
Kibana Query Language, the simple filter syntax in Kibana search bars: status:500 and not host:web-1. It filters only and does not affect scoring.
The classic query string syntax with field prefixes, boolean operators, wildcards and fuzziness. Exposed through the query_string query; prefer simple_query_string for user input.
Every query clause runs either in query context, where it contributes to the relevance score, or in filter context, where it is a yes/no match. Putting exact-match conditions in filters is the most common performance win.
Clauses that answer "how well does this match?" and add to _score, such as match on a text field. Use them for the parts of a search that should rank results.
Clauses that only include or exclude documents, with no scoring. Filter results can be cached, so they suit dates, statuses, tenant IDs and other exact conditions.
Leaf queries look for a value in a field; compound queries wrap other queries to combine or adjust them. Most real searches are a bool compound query full of leaf clauses.
The standard full-text query: analyses the input and finds documents containing the terms. operator: and, minimum_should_match and fuzziness tune it.
Exact match against the indexed term with no analysis. Use it on keyword, numeric and boolean fields; on a text field it usually finds nothing because of lowercasing.
gt, gte, lt, lte on numbers, dates and keywords. Date ranges accept math like now-7d/d, and rounding improves cache hits.
Matches documents with an indexed, non-null value for a field. Wrap it in must_not to find documents missing the field.
The ids query matches documents by _id. Useful inside a bool query; for plain fetching, _mget is simpler.
Matches terms starting with a prefix. For autocomplete on large data, index_prefixes or the search_as_you_type field type is faster.
Patterns with * and ?. A leading wildcard scans every term in the field and is slow; the wildcard field type exists for grep-like searches.
The bool query combines clauses with four occurrence types, two scoring and two non-scoring. Nesting bools expresses any AND/OR/NOT logic.
Clauses that must match and add to the score. Use for the full-text part of a search.
Optional clauses that boost the score when they match. With no must or filter, at least one should clause has to match; minimum_should_match changes that.
Excludes documents matching any clause. Runs in filter context, so it never affects scores.
Required clauses that run in filter context: they must match but do not score, and can be cached. Put every exact-match condition here.
Shaping what _search returns: which page, in what order, with which fields, and with matches marked up for display.
from/size works for shallow pages but is capped by max_result_window (10,000). Go deeper with search_after plus a point-in-time for stable ordering.
Sort by score, by keyword, numeric or date fields, or by geo distance. Sorting on a text field fails unless you use its keyword sub-field.
Trim the returned JSON with _source includes/excludes, or request specific values with the fields option, which also returns runtime and formatted values.
Returns snippets with matched terms wrapped in tags. The unified highlighter is the default; storing offsets in the mapping speeds it up on long fields.
Aggregations compute summaries over the documents a query matches, in the same request. Metric aggregations produce numbers; they usually sit inside bucket aggregations.
Counts how many values a field has across matching documents, counting each element of an array. Not the same as distinct values.
Single-value numeric metrics over a field or script. A missing value decides how documents without the field are treated.
Approximate distinct count using HyperLogLog++. Exact up to precision_threshold, then trades a small error for constant memory.
stats returns count, min, max, avg and sum in one go; extended_stats adds variance, standard deviation and bounds.
Bucket aggregations group documents (by value, range or time) and can hold sub-aggregations, much like SQL GROUP BY. roadmap.sh labels this group "Bulk Aggregations".
One bucket per distinct value of a keyword or numeric field, top size by count. Counts are approximate across shards; shard_size improves accuracy.
Buckets for ranges you define, such as price bands. date_range accepts date math like now-1M/M.
Fixed-width numeric buckets; date_histogram does the same over time with calendar or fixed intervals and time zones. The backbone of every time chart.
filter narrows one bucket by a query, and filters creates named buckets for several queries, like errors versus warnings side by side.
Aggregating over nested documents and computing metrics on top of other aggregations' outputs.
The nested aggregation steps into nested fields so sub-aggregations see each element separately; reverse_nested steps back out to the parent.
Work on other aggregations' results via buckets_path: derivatives, cumulative sums, moving functions, bucket_sort and bucket_selector.
Transforms run continuously or in batch to turn event-centric indices into entity-centric summary indices, so dashboards query small precomputed data instead of aggregating raw events every time.
Under each shard sits Lucene: an inverted index for finding documents by term and columnar doc values for sorting and aggregating. Knowing which structure a feature uses explains its cost.
A map from each term to the list of documents (and positions) containing it. Built from analysed text, it makes term lookups fast regardless of collection size.
On-disk column store built at index time for most non-text fields. Powers sorting, aggregations and scripts; disable it on fields you never aggregate to save disk.
An in-heap structure that lets text fields be sorted or aggregated. Off by default because it can exhaust memory; a keyword sub-field is almost always the better answer.
An analyzer is a chain of character filters, one tokenizer and token filters that turns text into terms. The same analysis must apply at index and search time, or queries miss documents they should find.
POST _analyze shows the exact tokens an analyzer or a field produces. The first tool to reach for when a match query behaves unexpectedly.
The default: Unicode word-boundary tokenisation plus lowercasing, without stemming or stop words. Fine for many languages, weak for stemming-heavy ones.
Define your own in index settings, combining tokenizers like ngram or edge_ngram with filters such as asciifolding, stemmers and synonyms. Set a separate search_analyzer when needed.
Relevance scores rank results in query context. Reading explain: true output turns scoring from magic into arithmetic you can tune.
The similarity module defines how a field is scored. BM25 is the default; boolean scores just by match, and custom scripted similarities are possible per field.
Scores by term frequency with saturation (k1), rarity of the term across the index (IDF) and field-length normalisation (b). Scores are per shard, which can skew small indices.
Tools for pushing the right documents to the top: demoting, custom scoring functions, phrase matching and synonyms.
The boosting query demotes documents matching a negative query instead of excluding them. Per-clause boost values are the other everyday lever.
Modifies scores with functions such as field_value_factor (popularity), decay functions (recency, distance) or scripts. Consider the simpler rank_feature query for static signals.
Requires terms in order and adjacent, with slop allowing gaps. Often added as a should clause to reward exact phrases.
The synonym_graph token filter handles multi-word synonyms correctly at search time. Manage sets through the synonyms API to update them without reindexing.
Elasticsearch doubles as a vector database: dense embeddings stored in HNSW graphs, models hosted in or outside the cluster, and rank fusion to blend semantic and keyword results.
dense_vector fields with approximate kNN search via HNSW. Tune num_candidates for recall versus speed, and quantization to cut memory.
Searching by meaning instead of keywords, using embeddings from an inference endpoint. The semantic_text field type handles chunking and embedding automatically.
Runs a lexical BM25 query and a vector query together and merges them, typically with reciprocal rank fusion through retrievers, which needs no score calibration.
Keeping a cluster healthy: watching shards, disk and heap, controlling merges, and replicating or scaling across deployments.
Human-readable tables for quick diagnosis: _cat/health, _cat/nodes?v, _cat/shards, _cat/indices?s=store.size:desc, _cat/allocation. Not meant for programs.
Lucene writes small immutable segments and merges them in the background, purging deleted documents. Force-merge only read-only indices, ideally down to one segment.
Ship metrics and logs to a separate monitoring cluster with Elastic Agent or Metricbeat, and alert on heap pressure, disk watermarks, rejected thread pools and unassigned shards.
Follower indices in another cluster replicate a leader index asynchronously, for disaster recovery or serving reads close to users. A paid-tier feature.
Policies that report required capacity per node role so an orchestrator (Elastic Cloud or ECK) adds or removes nodes. Not available for self-managed clusters on bare VMs.
Time-series data loses value with age. Lifecycle tooling rolls indices over, moves them to cheaper hardware and finally deletes them without manual work.
Index Lifecycle Management moves indices through hot, warm, cold, frozen and delete phases with actions like rollover, shrink, force-merge and searchable snapshots.
Start a new backing index when the current one hits max_primary_shard_size, max_age or a document count. Keeps shards evenly sized for data streams and aliases.
Node roles data_hot, data_warm, data_cold, data_frozen and data_content let ILM migrate indices onto progressively cheaper storage.
Replicas protect against node loss, not against deleted indices or bad mappings. Snapshots are the only real backup.
Incremental, segment-level backups to a repository such as S3, GCS, Azure or a shared filesystem. Restore whole clusters, single indices or renamed copies.
Snapshot Lifecycle Management schedules snapshots with cron expressions and enforces retention rules. Test restores regularly; an untested snapshot is a hope, not a backup.
Since 8.0, security is enabled out of the box with TLS and authentication. Production work is mostly about granting least-privilege roles to people and services.
Realms verify identity: native users, file, LDAP, Active Directory, PKI, SAML, OIDC and JWT. Realms are tried in order until one succeeds.
Roles grant cluster privileges and index privileges, down to document- and field-level security. Users or mapped external groups receive roles.
Long-lived credentials for services, sent as Authorization: ApiKey <base64>. Scope them with role_descriptors, set an expiry and invalidate them when rotated.