Data Management: CRUD Operations
7 min read
In the world of databases and search engines, CRUD (Create, Read, Update, Delete) is the foundational alphabet. Before we can perform mind-bending analytical aggregations or full-text fuzzy searches, we need to know how to get our data in, change it, and get it out.
Elasticsearch interacts with the world via a REST API. This means we will be communicating with our cluster using standard HTTP methods: GET, POST, PUT, and DELETE.
Let's dive into the core operations you will use daily in the industry.
1. Creating and Indexing Your First Documents 📝
Definition: Indexing is the process of adding a JSON document to an Elasticsearch index, making it searchable.
The Problem: You have raw data—like user profiles, application logs, or product catalogs—sitting in your application's memory. If a customer wants to search for "wireless headphones," your application cannot instantly scan millions of raw database rows efficiently.
The Solution: You send this data to Elasticsearch to be "indexed." Elasticsearch converts your raw JSON into an optimized, searchable format and stores it on disk.
How it works (The Flow)
Imagine managing a massive public library. You don’t just throw new books in a pile on the floor. When a new book arrives, you write a card catalog entry for the title, author, and keywords, and then place the book on a specific shelf. Elasticsearch does exactly this. It takes your JSON (the book), analyzes the text to build an Inverted Index (the card catalog), and saves the document (the shelf).
Industry Standard: Auto-generated vs. Manual IDs
When indexing data, you have two choices for document IDs.
1. Manual ID (PUT)
Use this when your data already has a unique identifier from your primary database (like a PostgreSQL primary key). This guarantees consistency.
PUT /users/_doc/101
{
"name": "Jane Doe",
"role": "Software Engineer",
"department": "Search Infrastructure"
}2. Auto-generated ID (POST)
Use this for time-series data or logs where you don't care about a specific ID, you just want the data stored fast.
POST /users/_doc
{
"name": "John Smith",
"role": "Data Analyst",
"department": "Analytics"
}Elasticsearch will reply with a random 20-character string like _id: "W_xyz123abc987". Generating auto-IDs is slightly faster for the cluster because it doesn't have to check if the ID already exists.
2. Retrieving Data: Fetching Documents by ID 🔍
Definition: Retrieving is the act of fetching a specific document from an Elasticsearch index using its exact unique ID.
The Problem: Searching requires computational power. If a user clicks on their own profile page, running a full-text search query like MATCH name "Jane Doe" is an absolute waste of CPU resources.
The Solution: The GET API bypasses the complex search phase entirely. It acts like a direct key-value lookup, retrieving the document instantly from storage.
The Basic GET
GET /users/_doc/101Industry Practice: Source Filtering
In production, documents can be massive. Imagine an e-commerce product document with 200 fields (reviews, specs, shipping data). If your front-end only needs the product name and price for a checkout cart, sending all 200 fields wastes network bandwidth and memory.
You can filter the _source to retrieve only what you need:
GET /users/_doc/101?_source=name,roleUnder the hood: Elasticsearch stores your exact original JSON in a special field called _source. When you retrieve a document, ES reads this field from disk and returns it to you.
3. Updating Documents: Partial vs. Full Updates 🛠️
Definition: Updating modifies an existing document in an index. A full update overwrites the entire document, while a partial update modifies only specific fields.
The Problem: Jane Doe gets promoted from "Software Engineer" to "Engineering Manager." You need to reflect this in the database. If you send her entire 50-field profile back to the server just to change one word, you waste bandwidth and risk accidentally overwriting other recent changes.
The Solution: Use the _update API to send only the exact fields that changed.
Partial Update (POST)
To change just a piece of the document, we use the _update endpoint and wrap our changes in a "doc" object.
POST /users/_update/101
{
"doc": {
"role": "Engineering Manager"
}
}Full Update / Overwrite (PUT)
If you use the PUT method with an existing ID, Elasticsearch will brutally overwrite the entire document. Any field you forget to include will be gone forever.
PUT /users/_doc/101
{
"name": "Jane Doe",
"role": "Engineering Manager"
}Under the Hood: The Illusion of Updating
Here is an interesting fact: Documents in Elasticsearch are immutable. They cannot be changed once written to disk (thanks to Apache Lucene, the engine under ES).
When you do a partial update, Elasticsearch doesn't actually grab an eraser and fix the existing document. Instead, it:
- Fetches the old document.
- Changes the value in memory.
- Indexes a brand new document.
- Marks the old document as "deleted" (it gets cleaned up automatically later).
4. Deleting Documents and Indices Safely 🗑️
Definition: Deleting removes documents or entire indices from your cluster to free up storage space.
The Problem: Data gets stale. Users delete their accounts, or temporary logs expire. Keeping data forever wastes expensive disk space and slows down searches.
The Solution: The DELETE API allows you to remove individual documents or drop entire indices instantly.
Deleting a Single Document
DELETE /users/_doc/101Deleting an Entire Index
If you have a log index from last year that you no longer need, deleting the index is practically instantaneous and frees up disk space immediately.
DELETE /logs-2024Industry Practice: Don't Shoot Yourself in the Foot
Imagine typing DELETE /logs-* but you accidentally sneeze, hit backspace, and execute DELETE /*. You just deleted your entire production database. This is a rite of passage you desperately want to skip.
To prevent accidental catastrophic deletions, industry standard requires setting a cluster setting called action.destructive_requires_name. This forces developers to type the exact name of the index they want to delete, disabling wildcards (*) for deletions.
5. The Bulk API: Processing Data at Scale 🚚
Definition: The Bulk API allows you to perform multiple indexing, updating, or deleting operations in a single REST API call.
The Problem: Making an HTTP request carries overhead (establishing a connection, headers, network latency). If you have 10,000 application logs to insert, making 10,000 separate POST requests will choke your network and take forever.
The Solution: The Bulk API bundles all those operations into one massive payload.
The Flow
Imagine carrying groceries from your car to your kitchen. You don't walk to the car, grab one apple, walk to the kitchen, put it down, and repeat 50 times. You use a grocery bag. The Bulk API is the grocery bag of Elasticsearch.
The NDJSON Format (Newline Delimited JSON)
The Bulk API does not use standard JSON arrays. It uses a highly specific format where every line is a separate JSON object, ending with a newline character (\n).
The structure requires an Action line (what you want to do), followed by a Data line (the document).
POST /_bulk
{"index":{"_index":"users","_id":"102"}}
{"name":"Alice","role":"Designer"}
{"update":{"_index":"users","_id":"101"}}
{"doc":{"role":"Director"}}
{"delete":{"_index":"users","_id":"103"}}
(Notice the empty line at the very bottom? The final line must end with a newline character, or the request will fail!)
Industry Practice: Finding the Sweet Spot
You might think, "Great! I'll put 5 million documents in one Bulk request!" If you do that, your cluster will run out of memory and crash.
The industry standard for Bulk requests is sizing them by physical byte size, not document count. A good rule of thumb is keeping bulk payloads between 5MB and 15MB per request. If you hit 15MB, send the request, and start a new bag.
📚 References & Extra Reading
To deepen your understanding and ensure you are using the exact parameters for your specific Elasticsearch version, refer to the official Elastic documentation:
Challenge
You are tasked with performing several data manipulation operations on a products index in a single, efficient API call.
Construct the complete request body for the Elasticsearch Bulk API to accomplish the following four actions in the specified order:
- Index a new document for a product with the manual ID
ABC-123. The product's data is:{"name": "Quantum SSD", "storage_gb": 1024, "price": 129.99}. - Index another new document for a different product, but this time, allow Elasticsearch to auto-generate the ID. The product's data is:
{"name": "RGB Mechanical Keyboard", "layout": "US", "price": 89.99}. - Perform a partial update on the document with the ID
XYZ-789. You only need to update itspriceto119.99and add a new fieldon_salewith a value oftrue. - Delete the document with the ID
OLD-456entirely.
Expected result
Your solution should be a correctly formatted NDJSON (Newline Delimited JSON) payload ready to be sent as the request body to the POST /_bulk endpoint.
The payload must consist of several JSON objects, each on its own line. Every line, including the final one, must end with a newline character.
The structure should be:
- An
indexaction line specifying_indexasproductsand_idasABC-123, followed on the next line by the corresponding product data JSON. - A second
indexaction line specifying only the_indexasproducts, followed on the next line by its product data JSON. - An
updateaction line specifying_indexasproductsand_idasXYZ-789, followed on the next line by a JSON object containing a"doc"key. The value of"doc"should be an object with thepriceandon_salefields. - A
deleteaction line specifying_indexasproductsand_idasOLD-456. This action line should not be followed by a data line.