<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tanmoy Majumdar on Medium]]></title>
        <description><![CDATA[Stories by Tanmoy Majumdar on Medium]]></description>
        <link>https://medium.com/@t4nmoy2?source=rss-4746ae38308b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Tanmoy Majumdar on Medium</title>
            <link>https://medium.com/@t4nmoy2?source=rss-4746ae38308b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:16:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@t4nmoy2/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[OpenSearch Internals: From Lucene Segments to Production-Grade Index Mappings(Part 1)]]></title>
            <link>https://medium.com/@t4nmoy2/opensearch-internals-from-lucene-segments-to-production-grade-index-mappings-part-1-5e74e44bd94d?source=rss-4746ae38308b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e74e44bd94d</guid>
            <category><![CDATA[aws-opensearch]]></category>
            <category><![CDATA[inverted-index]]></category>
            <category><![CDATA[apache-lucene]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[opensearch]]></category>
            <dc:creator><![CDATA[Tanmoy Majumdar]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 18:21:01 GMT</pubDate>
            <atom:updated>2026-07-10T18:32:42.295Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern search and analytics systems must be domain-aware, operate at lightning speed, and scale to handle petabytes of data. OpenSearch, one of the industry’s most powerful search platforms, is built on Apache Lucene, a highly sophisticated, open-source information retrieval library written in Java. While Lucene provides the core indexing and search mechanisms, OpenSearch builds on this foundation to create a robust, distributed, and highly available RESTful document store designed for massive scale. Understanding how to deploy and tune these systems in a production environment requires examining how Lucene manages data on a single node and how OpenSearch coordinates it across a large cluster.</p><p>To master OpenSearch, we first need to understand how Lucene stores and retrieves data. Unlike relational databases, which store data in mutable tables as rows, Lucene operates on a fundamentally different model.</p><h4><strong>Information retrieval basics</strong></h4><p>Before diving into Lucene’s implementation details, it’s important to understand the information retrieval theory that underlies it. Search, in the context of IR systems, is the art of extracting information that is highly relevant to a given query. Indexing is the process of building inverted indexes from the given text so that queries can be answered efficiently.</p><p>Consider a simple query like: sunshine AND candies AND NOT ghosts. There are two classical approaches to answering this question: linear scanning and inverted indexes.</p><h4><strong>Linear scanning</strong></h4><p>A linear scan sequentially examines every document, checking whether it satisfies the query conditions. This is essentially how Unix’s grep command works. While simple and adequate for small datasets, linear scan breaks down at scale. Performance degrades badly beyond a million medium-sized documents, and it offers no notion of ranked results. Linear scan also cannot support proximity queries (e.g., finding “flower” and “sunshine” within three words of each other) or return results in order of relevance. For the modern data explosion driven by IoT, social media, and connected devices, linear scan is simply not viable.</p><h4><strong>The inverted index — the heart of text search</strong></h4><p>The solution is the <strong>inverted index</strong> — a data structure that maps terms to the documents in which they appear, rather than mapping documents to their words. Any unique term appearing in any document is added to the inverted index.</p><p>The processing pipeline refines the raw input tokens before they hit the index. Two key transformations are stop word removal and stemming.</p><p><strong>A stop list</strong> contains words that form grammatical structure but carry little semantic value — words like “to”, “the”, “is”, and “a”. Filtering them out reduces index size and improves relevance by keeping only meaningful tokens.</p><p><strong>Stemming</strong> is a process that reduces words to their root form. For instance, the words “drive,” “driving,” and “drives” all stem to “drive.” This technique enhances recall — the ability to retrieve a wider range of relevant documents — by allowing a search for “drive” to match documents that contain any of those variations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1tcvGugMdyj6EVqwM44QQ.png" /></figure><p>In the above example, documents are indexed into Lucene’s inverted index. Each document’s content is analyzed and tokenized into terms, which are then indexed to facilitate efficient searching and retrieval.</p><h4><strong>DocValues: column-oriented field storage</strong></h4><p>Lucene’s inverted index is excellent for term lookups, but it cannot efficiently support operations such as sorting, grouping, or faceting. For these, we need to access raw field values for every document, which is the opposite of what an inverted index provides.</p><p><strong>DocValues</strong> solves this by maintaining a separate columnar store that maps document IDs to field values. Because values for the same field are stored contiguously on disk, range scans and sort operations become dramatically more efficient (data is likely already hot in the OS page cache from prior reads).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*NpW2uXVpoF3hFXH6npPh5Q.png" /></figure><h4><strong>Stored fields: row-oriented document storage</strong></h4><p>Stored fields are organized in a row-oriented manner, unlike column-oriented formats. For each document, the values of its fields are combined to form a single row. These rows are then saved sequentially to disk, in the order of their Lucene document IDs. Since documents can have varying numbers of fields and different data types (such as long text), the size of each row can vary. This structure is ideal when a search needs to return the <strong>entire document</strong> with all its fields intact, rather than just pulling a few specific data points. A single field can simultaneously exist in the inverted index, have DocValues enabled, and be saved as a stored field. Below is an example of how stored fields can be laid out on disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W51r0sK2ltXsVwUrZoa4pQ.png" /></figure><h4><strong>Immutability and segments</strong></h4><p>A Lucene index consists of multiple sub-indices called segments. The key point is that segments are strictly immutable: once written to disk, a segment cannot be changed.</p><p>This immutability offers major advantages. It works well with filesystem caching, requires no locking for reads, and enables concurrent query execution. However, it also changes how updates and deletions work.</p><p>When a document is “deleted,” Lucene simply flips a bit in a separate.delbitset file. When a document is “updated,” Lucene marks the old version as deleted and indexes the new version in a new segment. As a result, it should not be treated as a primary transactional database. Frequent updates can create substantial technical debt because deleted documents continue to occupy disk space until a background segment-merge process rewrites the data into larger, consolidated segments and removes the tombstones. Below is an example of how the segments could look.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntfnlL8TfVclbE_5sIjBWQ.png" /></figure><h4><strong>The refresh cycle and translog</strong></h4><p>To achieve near real-time search without overwhelming disk I/O, Lucene buffers new documents in memory. By default, a refresh occurs every second, writing the in-memory buffer to a new segment in the filesystem cache, which is then opened for searching. However, since this data is only in the filesystem cache, a power failure could result in data loss. To ensure durability, every operation is immediately appended to an on-disk transaction log (translog), similar to a write-ahead log (WAL) used in relational databases. Eventually, a costly filesystem flush (fsync) is performed to persist the segments to permanent storage and to clear the translog.</p><h4><strong>Lucene’s architecture: trade-offs summary</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*_igmxgyN3tH3-bqf5zuEtw.png" /></figure><p>In addition to the inverted index and Doc Values, Lucene uses several other data structures to maximize performance for every query.</p><h4><strong>BitSets: The silent engine behind Lucene’s speed</strong></h4><p>When searching for documents in Lucene, the engine must quickly answer questions such as “Which documents match this filter?” or “Which documents have been deleted?” This need arises even when dealing with millions of records. Lucene automatically selects the appropriate structure based on the number of documents involved: it uses a dense version for large, busy sets and a sparse version that consumes minimal memory when only a few documents are affected. This concept also supports deletion tracking, field indexing, query scoring, and result caching, all of which utilize the same efficient technique. As a result, what appears to be a straightforward “find matching documents” operation is, in reality, powered by high-speed bulk-set arithmetic rather than slow record-by-record scanning.</p><h4><strong>Finite state transducers (FSTs)</strong></h4><p>When Lucene needs to find a specific word among billions of indexed terms, it doesn’t brute-force scan through a massive list. Instead, it utilizes a Finite-State Transducer (FST), a structure that functions like a smart, compressed map. An FST stores every word while sharing common letter patterns across all entries, which allows it to use surprisingly little memory despite having billions of entries.</p><p>Lucene applies this same concept in various scenarios where quick lookups are necessary, including finding terms on disk, powering autocomplete features, expanding synonyms, applying spell-check rules, and resolving AI word vectors. The results are striking: what would typically require gigabytes of RAM can be accomplished with just megabytes. This efficiency is crucial for a search engine that indexes the entire internet. In summary, an FST enables Lucene to quickly answer the question, “Where is this word?” using only a fraction of the memory that a conventional lookup table would require.</p><h4><strong>Block trees &amp; skip lists</strong></h4><p>Postings lists, which are the sequences of document IDs linked to each term, can become quite large. To address this issue, Lucene stores these lists using a block tree structure that utilizes variable-length encoding and delta compression. This approach significantly reduces the amount of disk space required. Additionally, skip lists are added to this structure, enabling the query engine to efficiently skip large sections of irrelevant document IDs during multi-term query processing.</p><h4>Opensearch</h4><p>In short, OpenSearch is a distributed Lucene index that runs on multiple nodes. The following are some key concepts about OpenSearch and why we need something like this.</p><h4>The single server bottleneck</h4><p>Imagine we are operating a single Lucene process that indexes documents containing hundreds of fields. Each new document must pass through the analysis pipeline, be written into the inverted index, and eventually be flushed to disk as a segment. This represents a significant amount of work for one process on a single machine. At some point, the rate of incoming documents will surpass the server’s capacity to handle them. When this occurs, requests begin to queue, latencies increase, and errors start to appear. The challenging part is that this capacity threshold is not defined anywhere in Lucene’s configuration settings. We cannot derive it from a formula or find it in a specification sheet. The only reliable method to identify this threshold is to conduct load tests and observe where performance begins to decline. So what can we do when one server is no longer sufficient?</p><h4>Sharding: splitting the work</h4><p>Instead of upgrading the host’s hardware (scaling vertically), we can scale horizontally by running multiple Lucene instances across different servers and distributing the data among them. If a single instance on a single server can handle a certain document ingestion rate, then two instances on two servers can roughly double that rate, each responsible for a portion of the total dataset while also balancing the search load. The result is a setup where there is still a single logical document store, but beneath the surface, the data resides in multiple physical stores across different machines. Each physical store contains a different segment of the overall collection.</p><p>Once the data is distributed across multiple stores, a single search query cannot just hit one instance. If a user searches for a specific term, every store must be queried, and the results combined before any are returned.</p><p>This pattern scales effectively. Need three times the throughput? Run three instances. Ten times? Run ten. The number of instances can increase with workload, and scaling, ingestion, and search must all be seamless and free of downtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKNe_PGclDvygk1yUzH3dg.png" /></figure><p>Shards allow OpenSearch to distribute data evenly across nodes in a cluster. For example, if we have a 400 GB index, no single node may have enough capacity to store it all. By breaking it into 10 shards of 40 GB each, OpenSearch can assign those shards to 10 nodes, with each node independently managing its portion of the data.</p><p>To clarify, imagine a cluster with two indexes: <strong>Index A</strong> and <strong>Index B</strong>. Index A is split into <strong>3 shards</strong>, while Index B is split into <strong>5 shards</strong>. OpenSearch distributes these 8 shards across two nodes. Node1 hosts Index A (Shards 1–3) and Index B (Shards 1–3), while Node2 hosts Index A (Shards 2–3) and Index B (Shards 4–5). This distribution balances the load so no single node becomes a bottleneck, as shown in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdNhtvreIPXYYY77B68DUg.png" /></figure><h4>Primary and replica shards</h4><p>Distributing shards across multiple nodes is a good first step, but it isn&#39;t enough for true fault tolerance. When a node fails, it takes all of its shards down with it. The other nodes can still respond to queries, but the results will be incomplete, and any data stored only on the failed node will be missing.</p><p>The solution for fault tolerance is replication. For every primary shard, OpenSearch maintains one replica by default, though it is possible to configure more. These replica shards serve as complete, continuously synchronized exact copies of the primary shard. A replica shard can never reside on the same node as its primary. If the node hosting the primary shard goes down, a replica on a different node can immediately step in and be promoted to the primary role. An example is shown in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TLIH2NY4FDd_4-nGkgRvw.png" /></figure><h4><strong>OpenSearch index mapping</strong></h4><p>At the core of OpenSearch is the index, which is the essential unit that stores documents and enables them to be searched. Each index has a mapping that acts as its schema. If the mapping is set up correctly, the system will function predictably; however, if it is incorrect, it can lead to issues such as increased query latency, higher storage costs, and the need for reindexing throughout the index’s lifespan.</p><h4>Explicit vs. dynamic mapping</h4><p>When creating an index, we have two options: we can either define the schema in advance (explicit mapping) or let OpenSearch infer it as documents are added (dynamic mapping). Explicit mapping is preferred for production environments. When we know the structure of our documents, which is crucial for any system expected to last beyond a single sprint, defining the mapping before adding the first document gives us greater control over :</p><ol><li>Which fields are permitted in our documents</li><li>The type of each field — text, keyword, integer, date, boolean, object, nested, and so on</li><li>How each field is indexed and how it can be searched</li><li>Whether the field supports full-text search, exact filtering, sorting, aggregation, or range queries</li></ol><p><strong>Dynamic mapping</strong> is the fallback behavior. When OpenSearch sees a field it doesn’t recognize, it inspects the value, picks a type, and adds it to the mapping on the fly. Critically, dynamic mapping doesn’t switch off just because we supplied an explicit mapping at the time of index creation. If a document arrives with an unrecognized field, OpenSearch will still extend the schema unless we’ve explicitly forbidden it (more on this below).</p><h4>Why mapping matters</h4><p>The mapping determines what queries are even <em>possible</em>. Consider a release_year field which is mapped as integer:</p><pre>GET movies/_search<br>{<br>  &quot;query&quot;: {<br>    &quot;range&quot;: {<br>      &quot;release_year&quot;: { &quot;gte&quot;: 2000 }<br>    }<br>  }<br>}</pre><p>This is a true numeric range scan over a BKD tree, which is fast, predictable, and correct.</p><p>If we map the same field as text by accident, which is easy to do under dynamic mapping. If our first document sends &quot;release_year&quot;: &quot;2000&quot; as a string and that same range query degrades into lexicographic comparison. This can cause sorting problems, ex:&quot;10000&quot; sorts before &quot;2&quot;. In a production environment, these mapping errors often appear as silent correctness bugs, making them costly to resolve.</p><h4><strong>_source: the original document</strong></h4><p>The <strong>_source</strong> field contains the exact JSON document submitted during indexing. OpenSearch compresses this JSON string before writing it to disk. When performing searches, the <strong>_source</strong> field is not used to evaluate matches; that responsibility lies with the inverted index. However, each search result returns the <strong>_source</strong> field by default, allowing the client to receive the original document without needing to perform an additional lookup. It’s important to understand this key distinction: indexing makes fields searchable, while storing makes them retrievable. These two operations are entirely separate, and several mapping parameters can be adjusted to optimize either for disk space or retrieval performance.</p><h4><strong>Controlling dynamic behavior</strong></h4><h4>dynamic_templates</h4><p>The default dynamic mapping has opinions that we may not always agree with. New strings become text with a .keyword sub-field. Strings which look like date become date. These default settings are suitable for exploratory indexing but are not ideal for most other use cases. For example, using an analyzer on a field that only requires exact filtering results in unnecessary CPU usage during data ingestion and wasted disk space indefinitely.</p><p>dynamic_templates Let&#39;s intercept the dynamic mapping decision and inject our own rules. The mental model.</p><pre>Dynamic mapping:<br>  &quot;I found a new field. I will guess its type.&quot;<br><br>Dynamic templates:<br>  &quot;I found a new field. Before guessing, I will check your rules.<br>   The first rule that matches wins.&quot;</pre><p>The engine evaluates dynamic templates from top to bottom and short-circuits upon the first successful match, making the order of our templates critical. People use different approaches to define dynamic_templates . One of the ways is to declare that any string ending in _id is a keyword, any string ending in _text is text with English analysis, and a last pattern that maps other string fields as keyword which disables the default text + keyword Subfield mapping.</p><pre>{<br>  &quot;mappings&quot;: {<br>    &quot;dynamic_templates&quot;: [<br>      {<br>        &quot;ids_as_keyword&quot;: {<br>          &quot;match_mapping_type&quot;: &quot;string&quot;,<br>          &quot;match&quot;: &quot;*_id&quot;,<br>          &quot;mapping&quot;: { &quot;type&quot;: &quot;keyword&quot; }<br>        }<br>      },<br>      {<br>        &quot;text_fields_english&quot;: {<br>          &quot;match_mapping_type&quot;: &quot;string&quot;,<br>          &quot;match&quot;: &quot;*_text&quot;,<br>          &quot;mapping&quot;: { &quot;type&quot;: &quot;text&quot;, &quot;analyzer&quot;: &quot;english&quot; }<br>        }<br>      },<br>      {<br>        &quot;strings_as_keyword&quot;: {<br>          &quot;match_mapping_type&quot;: &quot;string&quot;,<br>          &quot;match&quot;: &quot;*&quot;,<br>          &quot;mapping&quot;: { &quot;type&quot;: &quot;keyword&quot; }<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>dynamic: True, False, Strict</p><p>The dynamic parameter controls what happens when an unknown field appears. It applies at the root of the mapping or on any object field, and there are exactly three valid values:</p><h4>true — the default</h4><p><strong>Behavior:</strong> The field is detected and automatically added to the mapping.</p><h4>false</h4><p><strong>Behavior:</strong> Document is accepted, and the new field is stored in _source but never indexed.</p><h4>strict</h4><p><strong>Behavior:</strong> Document is rejected with a strict_dynamic_mapping_exception.</p><h4>date_detection and numeric_detection</h4><p>These are two more pieces of the dynamic-mapping machinery, and date_detection is switched on by default.</p><p>When OpenSearch sees a string field it hasn’t mapped before, it checks the value against each pattern in dynamic_date_formats. The first pattern that matches wins, and the field is permanently mapped as a date.</p><p>That convenience comes with a sharp edge. The decision is based solely on the <em>first document </em>and remains in effect for the life of the index. So if a field holds text that just happens to look like a date in the first document OpenSearch sees, the whole field gets locked into a date mapping, and from then on, every value that isn&#39;t a valid date fails to be indexed.</p><h4>dynamic_date_formats</h4><p>The list of patterns date_detection tries against new string fields. Custom formats are allowed:</p><pre>PUT /custom-logs<br>{<br>  &quot;mappings&quot;: {<br>    &quot;dynamic_date_formats&quot;: [&quot;MM/dd/yyyy&quot;, &quot;dd-MM-yyyy&quot;]<br>  }<br>}</pre><p>Now a document with &quot;event_date&quot;: &quot;12/31/2023&quot; produces a datetyped field instead of text. Useful when we&#39;re ingesting from a system that won&#39;t standardize on ISO-8601 date format. Though the more durable fix is to standardize at the producer.</p><h4>numeric_detection</h4><p>In OpenSearch, numeric_detection is a dynamic mapping feature that instructs the search engine to inspect incoming string fields to determine whether they contain numbers (like &quot;123&quot; or &quot;45.67&quot;). If a string looks like a number and numeric_detection is enabled, OpenSearch will automatically convert and map that field as a numeric data type (long or float) instead of standard text. Unlikedate_detection, numeric_detection is disabled by default.</p><h4>The enabled parameter: storage without search</h4><p>The enabled parameter is a very useful mapping option in OpenSearch. It helps us control what OpenSearch should index and what it should simply keep as raw data.</p><p>In simple terms, setting &quot;enabled&quot;: false tells OpenSearch:</p><blockquote><em>“Store this data in the document, but do not analyze it, index it, or make it searchable.”</em></blockquote><p>So the data is still saved inside _source, which means we can see it when we retrieve the document. But OpenSearch will completely ignore it when performing search, filtering, sorting, or aggregation. This property is valid only at the index root or on objecttyped fields, not on leaf scalar fields.</p><h4>Field-level indexing controls</h4><h4>index</h4><p>A per-field switch on the inverted index. &quot;index&quot;: true (the default for most types) makes the field queryable, &quot;index&quot;: false stores the value in _source but the field is not searchable. If a property is configured with&quot;index&quot;: false, the field <strong>can still be stored in </strong>doc_values. When we set &quot;index&quot;: false on a primitive field type, the search engine still parses the data and adds the field to our index mapping schema. It simply skips the final step of building the inverted index or BKD tree, which <strong>prevents the specific field from being searched</strong>.</p><p>Because the field is still officially mapped, the engine <strong>may continue to build </strong>doc_values<strong>for it</strong>, allowing us to continue using the field for operations like aggregations and sorting.</p><p>This behavior is fundamentally different from setting&quot;enabled&quot;: false, which completely bypasses the parsing phase and creates zero mapping structures, meaning neither an inverted index nor doc_values are built.</p><h4>store</h4><p>In OpenSearch the store mapping parameter is often confusing because OpenSearch already stores the original document by default.</p><p>When a JSON document is indexed, OpenSearch saves the full original JSON inside a hidden field called _source. Because of this, individual fields do not need to be stored separately. That is why store is false by default.</p><p>Setting &quot;store&quot;: true on a field tells OpenSearch to keep a second, independent copy of that field&#39;s value in a separate Lucene structure called <em>stored fields</em>, sitting outside _source.</p><p>Example: Large legal documents</p><p>Imagine an index for legal contracts. Each document has a small title, a date, and a very large(5 MB) contract_text field containing OCR text from a 500-page PDF.</p><p>With the default settings, returning a single title means loading the entire 5 MB _source from disk, parsing the JSON, pulling out the title, and discarding the rest. Across 50 results, that&#39;s roughly 250 MB read into memory to surface a few kilobytes of text, which is heavy disk I/O for almost no payoff.</p><p>Marking the small fields as stored avoids this:</p><pre>PUT /legal-contracts<br>{<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;title&quot;:         { &quot;type&quot;: &quot;text&quot;, &quot;store&quot;: true },<br>      &quot;date&quot;:          { &quot;type&quot;: &quot;date&quot;, &quot;store&quot;: true },<br>      &quot;contract_text&quot;: { &quot;type&quot;: &quot;text&quot; }<br>    }<br>  }<br>}</pre><p>Now each indexed document is saved twice over: the full payload in _source, plus the title and date extracted into stored fields.</p><h4>Reading from stored fields</h4><p>The benefit only appears when a query asks for the stored fields directly and skips _source entirely:</p><pre>GET /legal-contracts/_search<br>{<br>  &quot;query&quot;:         { &quot;match&quot;: { &quot;contract_text&quot;: &quot;Acme&quot; } },<br>  &quot;stored_fields&quot;: [&quot;title&quot;, &quot;date&quot;],<br>  &quot;_source&quot;:       false<br>}</pre><p>OpenSearch ignores the 5 MB _source, jumps straight to the stored fields, and returns the title and date. Memory use drops from hundreds of megabytes to a few kilobytes, and latency falls accordingly.</p><h4>The trade-off</h4><p>store: false (the default) keeps data in one place, so it costs no extra disk, but pulling one small field out of a huge document means parsing the whole thing.</p><p>store: true duplicates the field (once in _source, once on its own), costing more disk in exchange for fast retrieval of small fields that sit alongside large text or binary blobs.</p><p>In practice, store: true earns its keep only when _source is bloated with large content that&#39;s rarely needed in full.</p><h4>Runtime</h4><p>Runtime fields in OpenSearch are fields whose values are calculated at query time rather than stored during indexing. This is useful when an index already contains the raw data, but a new derived field is needed later.</p><p>For example, an e-commerce order document may contain base_price: 200 and discount_percentage: 0.15, but no final_price field. A runtime field can calculate final_price dynamically as 200 × (1 - 0.15) = 170 whenever a query needs it.</p><p>Runtime fields can be added permanently to the index mapping:</p><pre>PUT /ecommerce-orders/_mapping<br>{<br>  &quot;runtime&quot;: {<br>    &quot;final_price&quot;: {<br>      &quot;type&quot;: &quot;double&quot;,<br>      &quot;script&quot;: {<br>        &quot;source&quot;: &quot;emit(doc[&#39;base_price&#39;].value * (1.0 - doc[&#39;discount_percentage&#39;].value))&quot;<br>      }<br>    }<br>  }<br>}</pre><p>After this, final_price can be used in filters, sorting, or aggregations even though it does not physically exist in the original document.</p><pre>GET /ecommerce-orders/_search<br>{<br>  &quot;query&quot;: {<br>    &quot;range&quot;: {<br>      &quot;final_price&quot;: {<br>        &quot;gte&quot;: 150<br>      }<br>    }<br>  }<br>}</pre><p>The same idea can also be used without changing the index mapping. OpenSearch allows runtime fields to be defined directly inside a search request using runtime_mappings. In that case, the field exists only for that query.</p><pre>GET /ecommerce-orders/_search<br>{<br>  &quot;runtime_mappings&quot;: {<br>    &quot;final_price&quot;: {<br>      &quot;type&quot;: &quot;double&quot;,<br>      &quot;script&quot;: {<br>        &quot;source&quot;: &quot;emit(doc[&#39;base_price&#39;].value * (1.0 - doc[&#39;discount_percentage&#39;].value))&quot;<br>      }<br>    }<br>  },<br>  &quot;query&quot;: {<br>    &quot;range&quot;: {<br>      &quot;final_price&quot;: {<br>        &quot;gte&quot;: 150<br>      }<br>    }<br>  }<br>}</pre><p>This is useful for experiments, one-off analysis, or testing a derived field before adding it to the mapping.</p><p>The main benefit is flexibility. Runtime fields enable adding new calculated fields, fixing parsing errors, or analyzing historical data without reindexing millions of documents.</p><p>The trade-off is performance. Since the value is calculated during search, runtime fields use more CPU than normal indexed fields. They are best for exploration, temporary fixes, and low-traffic use cases. If a runtime field becomes part of a heavily used dashboard or production query, it is usually better to convert it into a normal indexed field.</p><h4>Nested objects</h4><h4>Nested Fields and include_in_parent</h4><p>OpenSearch handles arrays of objects differently than many people expect. For example:</p><pre>{<br>  &quot;comments&quot;: [<br>    { &quot;author&quot;: &quot;Alice&quot;, &quot;sentiment&quot;: &quot;positive&quot; },<br>    { &quot;author&quot;: &quot;Bob&quot;, &quot;sentiment&quot;: &quot;negative&quot; }<br>  ]<br>}</pre><p>With a normal object mapping, OpenSearch flattens this internally:</p><pre>comments.author:    [&quot;Alice&quot;, &quot;Bob&quot;]<br>comments.sentiment: [&quot;positive&quot;, &quot;negative&quot;]</pre><p>This loses the relationship between each author and sentiment. A query for author = Alice and sentiment = negative may incorrectly match this document, even though Alice’s comment was positive.</p><p>The nested type solves this problem by indexing each object in the array as a separate hidden document. This preserves the relationship between fields inside the same object.</p><pre>PUT /blog-index<br>{<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;title&quot;: { &quot;type&quot;: &quot;text&quot; },<br>      &quot;comments&quot;: {<br>        &quot;type&quot;: &quot;nested&quot;,<br>        &quot;properties&quot;: {<br>          &quot;author&quot;: { &quot;type&quot;: &quot;keyword&quot; },<br>          &quot;sentiment&quot;: { &quot;type&quot;: &quot;keyword&quot; }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Now strict queries can be written safely using a nested query:</p><pre>GET /blog-index/_search<br>{<br>  &quot;query&quot;: {<br>    &quot;nested&quot;: {<br>      &quot;path&quot;: &quot;comments&quot;,<br>      &quot;query&quot;: {<br>        &quot;bool&quot;: {<br>          &quot;must&quot;: [<br>            { &quot;term&quot;: { &quot;comments.author&quot;: &quot;Alice&quot; } },<br>            { &quot;term&quot;: { &quot;comments.sentiment&quot;: &quot;negative&quot; } }<br>          ]<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>This correctly returns no result, because Alice’s sentiment is not negative.</p><p>The trade-off is that normal flat queries cannot search nested fields directly. A standard query on comments.author does not work the same way because the data lives inside hidden nested documents.</p><p>include_in_parent: true is a compromise. It tells OpenSearch to index the comments in two ways: first, as properly nested documents, and second, as flattened fields in the parent document.</p><pre>PUT /blog-index<br>{<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;title&quot;: { &quot;type&quot;: &quot;text&quot; },<br>      &quot;comments&quot;: {<br>        &quot;type&quot;: &quot;nested&quot;,<br>        &quot;include_in_parent&quot;: true,<br>        &quot;properties&quot;: {<br>          &quot;author&quot;: { &quot;type&quot;: &quot;keyword&quot; },<br>          &quot;sentiment&quot;: { &quot;type&quot;: &quot;keyword&quot; }<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>With this mapping, nested queries still preserve correctness, while simple queries such as searching for comments.author = Alice can also work against the flattened parent data.</p><p>The cost is extra indexing and storage. The same comment data is indexed once as nested documents and again as flattened parent fields. This can increase index size and slow down ingestion, especially when documents contain large arrays.</p><p>In practice, use nested when field relationships inside object arrays must be preserved. Use include_in_parent: true only when both strict nested queries and simple flat queries are needed, such as for legacy clients, dashboards, or generic search bars.</p><h4>Properties and multi-fields</h4><p>In OpenSearch, properties is the part of the mapping where fields are defined. This is where each field gets its type, such as text, keyword, date, integer, object, or nested.</p><pre>{<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;title&quot;: {<br>        &quot;type&quot;: &quot;text&quot;<br>      },<br>      &quot;owner&quot;: {<br>        &quot;type&quot;: &quot;keyword&quot;<br>      },<br>      &quot;created_at&quot;: {<br>        &quot;type&quot;: &quot;date&quot;<br>      }<br>    }<br>  }<br>}</pre><p>A common mapping pattern is to index the same field in multiple ways. This is called a multi-field.</p><pre>{<br>  &quot;title&quot;: {<br>    &quot;type&quot;: &quot;text&quot;,<br>    &quot;fields&quot;: {<br>      &quot;keyword&quot;: {<br>        &quot;type&quot;: &quot;keyword&quot;<br>      }<br>    }<br>  }<br>}</pre><p>Here, title is indexed as analyzed text, while title.keyword is indexed as an exact keyword value.</p><p>The text field is useful for full-text search:</p><pre>{<br>  &quot;match&quot;: {<br>    &quot;title&quot;: &quot;open search guide&quot;<br>  }<br>}</pre><p>The keyword sub-field is useful for exact matching, sorting, and aggregations:</p><pre>{<br>  &quot;term&quot;: {<br>    &quot;title.keyword&quot;: &quot;OpenSearch Guide&quot;<br>  }<br>}</pre><p>Some mappings use .raw instead of .keyword:</p><pre>{<br>  &quot;title&quot;: {<br>    &quot;type&quot;: &quot;text&quot;,<br>    &quot;fields&quot;: {<br>      &quot;raw&quot;: {<br>        &quot;type&quot;: &quot;keyword&quot;<br>      }<br>    }<br>  }<br>}</pre><p>Functionally, title.keyword and title.raw usually mean the same thing: both are keyword sub-fields of a text field. The difference is only the sub-field name.</p><p>The .keyword convention is the OpenSearch default and is created automatically by dynamic mapping. The .raw convention is older and mostly exists in legacy Elasticsearch and Logstash-based setups.</p><p>For consistency, a single convention should be used throughout an index or project. In most modern OpenSearch systems, .keyword is the better default because it matches dynamic mapping behavior and is widely expected by dashboards and tooling.</p><h4>copy_to: building a catch-all search field</h4><p>The copy_to mapping parameter in OpenSearch copies values from multiple fields into a single combined search field during indexing. It is commonly used to support a simple global search box.</p><p>For example, an employee directory may need a single search box that can match by first name, last name, department, or job title. Without copy_to, the query may need to search across many fields using multi_match.</p><pre>GET /employees/_search<br>{<br>  &quot;query&quot;: {<br>    &quot;multi_match&quot;: {<br>      &quot;query&quot;: &quot;Marketing Alice&quot;,<br>      &quot;fields&quot;: [&quot;first_name&quot;, &quot;last_name&quot;, &quot;department&quot;, &quot;job_title&quot;]<br>    }<br>  }<br>}</pre><p>With copy_to, selected fields can be copied into a single field, such as global_search_field.</p><pre>PUT /employees<br>{<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;first_name&quot;: {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;copy_to&quot;: &quot;global_search_field&quot;<br>      },<br>      &quot;last_name&quot;: {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;copy_to&quot;: &quot;global_search_field&quot;<br>      },<br>      &quot;department&quot;: {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;copy_to&quot;: &quot;global_search_field&quot;<br>      },<br>      &quot;job_title&quot;: {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;copy_to&quot;: &quot;global_search_field&quot;<br>      },<br>      &quot;global_search_field&quot;: {<br>        &quot;type&quot;: &quot;text&quot;<br>      }<br>    }<br>  }<br>}</pre><p>Now an employee document can be indexed normally:</p><pre>POST /employees/_doc/1<br>{<br>  &quot;first_name&quot;: &quot;Alice&quot;,<br>  &quot;last_name&quot;: &quot;Smith&quot;,<br>  &quot;department&quot;: &quot;Marketing&quot;,<br>  &quot;job_title&quot;: &quot;Director&quot;<br>}</pre><p>OpenSearch does not add global_search_field to the _source document. The original JSON remains unchanged. Instead, OpenSearch copies the field values only into the inverted index for searching.</p><p>This allows the search query to become much simpler:</p><pre>GET /employees/_search<br>{<br>  &quot;query&quot;: {<br>    &quot;match&quot;: {<br>      &quot;global_search_field&quot;: &quot;Marketing Alice&quot;<br>    }<br>  }<br>}</pre><p>The benefit is simpler query logic and an easy way to implement global search across multiple fields. The trade-off is extra index size, because the same terms are indexed once in their original fields and again in the combined copy_to field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e74e44bd94d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>