In today’s digital age, search functionality is essential for any e-commerce platform. By integrating Elasticsearch for scalable search capabilities, Flask as the web framework, and Docker for smooth deployment, you can create a responsive and containerized search application. This article will guide you through the process of setting up such an application from the ground up, using these tools to develop a scalable e-commerce search and shopping cart system.
Project Architecture
The project architecture revolves around a client-server model, with the following components:
- Elasticsearch: Our primary search engine and data store for storing product details.
- Flask Application: Acts as the API and server, handling user requests, managing sessions, and rendering HTML templates.
- Docker: Provides containerization to package the application and Elasticsearch, enabling easy deployment.
The architecture can be visualized as follows:
- Frontend: HTML, CSS (for styling), and Bootstrap for responsive UI, with forms for search and cart interactions.
- Backend: Flask handles requests and session management for cart data. Elasticsearch stores and serves product data.
- Deployment: Docker allows us to package and deploy the application in a contained environment.
Step 1: Set Up Elasticsearch
Elasticsearch is our data backbone, storing product information and providing powerful search functionality.
- Install Elasticsearch on Cloud or Locally: You can deploy Elasticsearch on a cloud provider (e.g., Elastic Cloud) or run it locally in Docker for development.
- Create an Index with Mappings: Define an index named
productsto store our data. An index is like a database table where we specify mappings, or schema, for fields likeCategory,ProductType, andGender. - Sample Ingestion Script: Our
ingestion.pyscript loads a CSV file(fashion.csv) with product data into Elasticsearch, establishing mappings for fields likeProductId,ProductTitle, andColour.
# ingestion.py
import os
import pandas as pd
from elasticsearch import Elasticsearch, helpers
# Set up Elasticsearch connection
es = Elasticsearch(
["host:port"],
basic_auth=("username", "password"),
)
index_name = "products"
# Load CSV data
def load_data(file_path):
return pd.read_csv(file_path, encoding='ISO-8859-1')
# Index setup
def delete_index():
if es.indices.exists(index=index_name):
es.indices.delete(index=index_name)
def create_index():
index_config = {
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
},
"mappings": {
"properties": {
"ProductId": {"type": "keyword"},
"Gender": {"type": "keyword"},
"Category": {"type": "keyword"},
"SubCategory": {"type": "keyword"},
"ProductType": {"type": "keyword"},
"Colour": {"type": "keyword"},
"Usage": {"type": "keyword"},
"ProductTitle": {"type": "text"},
"ImageURL": {"type": "keyword"}
}
}
}
es.indices.create(index=index_name, body=index_config)
# Bulk ingestion
def ingest_data(data):
actions = [{"_index": index_name, "_source": row.to_dict()} for _, row in data.iterrows()]
helpers.bulk(es, actions)
def main():
file_path = "fashion.csv"
data = load_data(file_path)
delete_index()
create_index()
ingest_data(data)
if __name__ == "__main__":
main()
Step 2: Build the Flask Application
The Flask app serves as the server and connects with Elasticsearch to fetch and display products. It also manages user sessions to support the “add to cart” feature.
- Initialize Flask and Connect to Elasticsearch:
from flask import Flask, render_template, request, session, redirect, url_for
from elasticsearch import Elasticsearch
app = Flask(__name__)
app.secret_key = os.urandom(24)
es = Elasticsearch(
["host:port"],
basic_auth=("username", "password")
)
2. Create Routes for Home, Search, and Cart:
- The home route displays category-wise products.
- The search route handles user queries, while the cart route adds items to a cart stored in a session.
# Route to add item to cart
@app.route("/add_to_cart/<product_id>")
def add_to_cart(product_id):
if "cart" not in session:
session["cart"] = []
session["cart"].append(product_id)
session.modified = True
return redirect(url_for("view_cart"))
Step 3: Create Docker Environment
A Dockerfile and docker-compose.yml setup lets us containerize the application, making it easy to deploy anywhere.
- Dockerfile: Specifies Python installation, dependencies, and the entry command.
- docker-compose.yml: Declares services for the Flask app and provides environment variables for Elasticsearch.
Dockerfile
FROM python:3.9
WORKDIR /app
COPY . /app
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 5030
CMD ["python", "app.py"]
docker-compose.yml (replace hostname, username and password with actual values)
version: '3.8'
services:
app:
build: .
ports:
- "5030:5030"
environment:
- ELASTICSEARCH_HOST=hostname
- ELASTICSEARCH_USERNAME=username
- ELASTICSEARCH_PASSWORD=password
volumes:
- .:/app
Step 4: Frontend Templates (HTML + CSS)
- index.html — Displays categories and a search box:
<div class="category-links">
<a href="{{ url_for('category_search', category_name='Apparel') }}">Apparel</a>
<a href="{{ url_for('category_search', category_name='Footwear') }}">Footwear</a>
</div>
2. results.html — Displays search results with pagination and an add-to-cart button:
<div class="product-card">
<img src="{{ product['ImageURL'] }}" alt="{{ product['ProductTitle'] }}">
<p>{{ product['ProductTitle'] }}</p>
<a href="{{ url_for('add_to_cart', product_id=product['ProductId']) }}" class="add-to-cart">Add to Cart</a>
</div>




Conclusion
This project showcases the development of a scalable, Dockerized search and cart application by integrating Flask, Elasticsearch, and Docker. Through this configuration, we achieved:
- Efficient Search: Elasticsearch handles indexing and searching across millions of records efficiently.
- Session Management: Flask’s session capabilities provide a simple way to store user cart information.
- Seamless Deployment: Docker enables consistent deployment across any environment.
Future Expansions
- Implementing Caching: Use Redis or Memcached to reduce Elasticsearch queries for frequently accessed data.
- Improving UI/UX: Enhance the frontend design using Bootstrap or custom CSS to create a more visually appealing interface.
- Analytics and Logging: Track user behavior for improved product recommendations.
With this configuration, you now have a strong foundation to develop a more advanced e-commerce platform.
The project code is available on my GitHub.






Leave a comment