Introduction and Getting Started
8 min read
Course: Elasticsearch
Topic: Introduction and Getting Started
Welcome to the world of Elasticsearch. If you have ever used a search bar on an e-commerce website and instantly found the exact product you were looking for despite making three spelling mistakes, you have likely interacted with Elasticsearch. 🕵️♂️
Today, we are going to break down what it is, where it lives in the modern tech stack, how to spin it up, and how to start talking to it.
1. The 'Why' Before the 'How': What is Elasticsearch?
Elasticsearch is a highly scalable, distributed, open-source search and analytics engine built on Apache Lucene. It stores data as JSON documents and allows you to search, analyze, and visualize massive volumes of data in near real-time.
The Problem:
Traditional Relational Database Management Systems (RDBMS) like MySQL or PostgreSQL are fantastic for structured data and strict relationships. However, imagine you run a massive online bookstore with millions of book descriptions. If a user searches for the word "wizard," a traditional SQL database has to scan through every single row (SELECT * FROM books WHERE description LIKE '%wizard%') to find the matches. As your data grows, this row-by-row scanning becomes painfully slow and resource-heavy.
How it solves it:
Elasticsearch does not store data in tables and rows. Instead, it uses a data structure called an Inverted Index.
When you add a document to Elasticsearch, it breaks down the text into individual words (tokens) and keeps a list of exactly which document contains which word. It is exactly like the index at the back of a textbook. When you search for "wizard," Elasticsearch doesn't scan the whole database; it flips straight to the "W" section of its index, sees that "wizard" appears in Document #42 and Document #105, and instantly returns the results.
Industry Usability:
In the industry, Elasticsearch is rarely used as the primary "source of truth" (like a database handling financial transactions). Instead, it is attached alongside traditional databases to power specific, heavy-duty features:
- Full-Text Search: Powering the autocomplete and search bars of platforms like Netflix, Uber, and Wikipedia.
- Log Management: Storing and analyzing millions of system logs so engineers can quickly figure out why a server crashed at 3 AM.
- Metrics and Analytics: Monitoring system health and application performance in real-time.
2. Understanding the Elastic Stack (ELK) Ecosystem
Elasticsearch is just the engine. But an engine is useless without a dashboard and a fuel pipeline.
The Problem:
You have a powerful search engine, but how do you continuously feed it raw data from 50 different web servers? And once the data is in there, how do your data analysts read it without having to write raw, complex code queries in the terminal?
How it solves it: The ELK Stack
The industry standard solution is an integrated ecosystem of tools known as the ELK Stack (now officially called the Elastic Stack). ELK is an acronym for three core open-source projects working in harmony:
- E - Elasticsearch (The Brain): The core storage and search engine. This is where the data is indexed and where the heavy lifting happens.
- L - Logstash (The Pipeline): A server-side data processing pipeline. It ingests data from a multitude of sources simultaneously, transforms it (e.g., parsing messy, unstructured log lines into clean JSON), and then sends it to a "stash" like Elasticsearch.
- K - Kibana (The Window): The visual interface. Kibana sits on top of Elasticsearch and provides beautiful dashboards, charts, and graphs. It is how humans make visual sense of the millions of JSON documents living inside the engine.
Bonus Player: Beats (The Scouts)
Later, Elastic introduced Beats to the stack. Beats are lightweight, single-purpose data shippers installed directly on your servers. Instead of running a heavy Logstash instance on your web server, you install a tiny "Beat" (like Filebeat for reading log files, or Metricbeat for reading CPU usage) that quietly watches your server and ships data directly to Elasticsearch.
Imagine you are running a massive pizza shop. Elasticsearch is the giant pantry where all ingredients are stored and instantly retrievable. Logstash is the delivery truck bringing in fresh supplies from different farms, cleaning them, and organizing them into boxes. Kibana is the digital inventory dashboard the manager looks at to see how many tomatoes are left. And Beats are the little automated sensors on the fridge telling the truck exactly when it's time to pick up more supplies. 🍕
3. Setting up Your Elasticsearch Environment
In the industry, installing databases and engines directly onto your host operating system is a recipe for messy configurations and version conflicts. The absolute standard for local development and testing is using Docker.
Docker allows us to download a pre-packaged, perfectly configured "container" of Elasticsearch and run it anywhere in seconds.
The Setup (Using Docker)
- Ensure Docker is Installed: You need Docker Desktop (Windows/Mac) or Docker Engine (Linux) running on your machine.
- Run the Container: Open your terminal and run the following command to pull the latest 8.x image and start it:
docker run --name elasticsearch \
-p 9200:9200 \
-e "discovery.type=single-node" \
-e "xpack.security.enabled=false" \
docker.elastic.co/elasticsearch/elasticsearch:8.13.0Let's break down what just happened under the hood:
--name elasticsearch: We are naming our container so we can easily stop, start, or delete it later.-p 9200:9200: Elasticsearch natively communicates over port 9200. This maps your computer's local port 9200 to the container's port 9200.-e "discovery.type=single-node": Elasticsearch is designed to automatically look for other servers to form a "cluster". This tells it, "You are alone, don't look for friends," which saves memory and drastically speeds up startup time.-e "xpack.security.enabled=false": Crucial Note! In modern Elasticsearch (8.x+), security (passwords and TLS/HTTPS) is enabled by default. For production environments, this is strictly mandatory. However, for learning the basic API on your local machine on Day 1, dealing with SSL certificates is a massive headache. We turn it off here to keep our learning environment frictionless.
Wait a minute or two for the terminal to stop spitting out startup logs.
Verify it is running:
Open your browser and navigate to http://localhost:9200. You should see a JSON response confirming Elasticsearch is breathing:
{
"name" : "1a2b3c4d5e6f",
"cluster_name" : "docker-cluster",
"version" : {
"number" : "8.13.0",
"build_flavor" : "default"
},
"tagline" : "You Know, for Search"
}If you see "You Know, for Search", congratulations! 🚀 You have an enterprise-grade search engine running locally.
4. Your First Interaction: Exploring the REST API
The Problem:
Unlike SQL databases where you need a specific database driver and a dedicated language like SQL (SELECT * FROM...), you need a universally understood way to send and receive data from Elasticsearch seamlessly, regardless of whether you are writing Python, JavaScript, or Java.
How it solves it:
Elasticsearch uses a standard REST API. You communicate with it using standard HTTP methods (GET, POST, PUT, DELETE), and it replies with standard JSON. If your programming language (or even just your terminal) can make a web request, it can talk to Elasticsearch.
Before we write commands, let's learn the two alphabets of Elasticsearch:
- Index: An index is a collection of similar documents. (Equivalent to a Database or a Table in SQL).
- Document: The actual data, formatted as a JSON object. (Equivalent to a Row in SQL).
Let's interact with our node. You can run these using curl in your terminal, or use a tool like Postman.
1. Create an Index (PUT)
Let's create an index called movies to store our data.
curl -X PUT "localhost:9200/movies"Response: {"acknowledged":true,"shards_acknowledged":true,"index":"movies"}
2. Add a Document (POST)
Let's add our first movie. We send a POST request to /movies/_doc/1, where 1 is the unique ID we want to assign to this specific document.
curl -X POST "localhost:9200/movies/_doc/1" -H 'Content-Type: application/json' -d'
{
"title": "The Matrix",
"director": "The Wachowskis",
"year": 1999,
"genres": ["Action", "Sci-Fi"]
}'3. Read a Document (GET)
Want to retrieve the exact document you just created? Just use GET with its unique ID.
curl -X GET "localhost:9200/movies/_doc/1"4. Search the Data (GET /_search)
This is where Elasticsearch flexes its muscles. Let's ask it to find any movie that contains the word "Matrix" in the title. We use the _search endpoint and pass a "Query DSL" (Domain Specific Language) JSON object.
curl -X GET "localhost:9200/movies/_search" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"title": "Matrix"
}
}
}'Notice we didn't search for the exact string "The Matrix", just "Matrix". Because of the Inverted Index we talked about earlier, Elasticsearch instantly understands the token "Matrix" is tied to Document 1, and returns it with a _score indicating how relevant the result is to your search.
5. Update a Document (POST /_update)
Let's say we want to add a rating to our movie without overwriting the whole document. We use the _update endpoint.
curl -X POST "localhost:9200/movies/_update/1" -H 'Content-Type: application/json' -d'
{
"doc": {
"rating": 8.7
}
}'6. Delete a Document (DELETE)
When it's time to clean up, you can easily remove the document by pointing to its ID:
curl -X DELETE "localhost:9200/movies/_doc/1"And just like that, you've mastered the basic CRUD (Create, Read, Update, Delete) operations in Elasticsearch. You are now communicating fluently with the engine!
📚 References & Extra Reading
Challenge
You are tasked with managing a product catalog using Elasticsearch's REST API. Your goal is to write the correct sequence of HTTP requests (method, endpoint, and JSON body where applicable) to perform the following operations. Treat each task as a separate, sequential step.
- Create a new index named
productsto store product information. - Add a document for a new product with the ID
101. The product data is:{"name": "Quantum Laptop Pro", "brand": "Innovatech", "price": 1499.99, "in_stock": true}. - Perform a search within the
productsindex to find any document where thenamefield contains the word "Laptop". - The price of the product with ID
101has dropped. Perform a partial update on the document to change itspriceto1350.00without altering other fields. - Delete the product document with the ID
101.
Expected result
The solution should consist of five distinct REST API calls written in sequence, matching the tasks.
- Create Index: A
PUTrequest to the/productsendpoint.bashPUT /products - Add Document: A
POSTorPUTrequest to/products/_doc/101with the full product JSON as the body.bashPOST /products/_doc/101 { "name": "Quantum Laptop Pro", "brand": "Innovatech", "price": 1499.99, "in_stock": true } - Search Documents: A
GETrequest to the/_searchendpoint of the index, with a JSON body containing amatchquery.routerosGET /products/_search { "query": { "match": { "name": "Laptop" } } } - Update Document: A
POSTrequest to the/_updateendpoint for the specific document ID, with a body containing thedocobject for a partial update.awkPOST /products/_update/101 { "doc": { "price": 1350.00 } } - Delete Document: A
DELETErequest to the specific document endpoint/products/_doc/101.gradleDELETE /products/_doc/101