
When building a web application, search functionality often starts with a simple database query. For example, you might use MongoDB's $regex operator or MySQL's LIKE clause to find products by name. This works well when your dataset is small, but as the application grows, search can become slower and harder to maintain.
Imagine you're building an e-commerce application with 500,000 products. Users expect to search for products instantly, filter results by category, sort by price, and find relevant matches even when they don't type the exact product name.
A basic database query may struggle to provide all these features efficiently, especially when users expect advanced text matching, relevance scoring, autocomplete, and faceted filtering.
This is where Elasticsearch becomes useful.
Elasticsearch is a distributed search and analytics engine built on Apache Lucene. It supports full-text search, filtering, sorting, aggregations, and relevance scoring. When combined with FastAPI, we can build a fast, asynchronous search API that powers product catalogs, documentation platforms, job portals, and content management systems.
In this article, we'll build a practical search API using FastAPI and Elasticsearch. We'll cover installation, indexing documents, implementing search endpoints, filtering, pagination, autocomplete, error handling, and production best practices.
1. What Is Elasticsearch?
Elasticsearch is a search engine designed to retrieve relevant information from large collections of documents.
Unlike a traditional database query that primarily checks whether records match specific conditions, Elasticsearch can analyze text and rank matching documents according to their relevance.
For example, suppose an e-commerce application contains these products:
[
{
"id": 1,
"name": "Apple MacBook Pro",
"category": "laptops",
"price": 199999
},
{
"id": 2,
"name": "Apple MacBook Air",
"category": "laptops",
"price": 119999
},
{
"id": 3,
"name": "Dell XPS Laptop",
"category": "laptops",
"price": 149999
}
]If a user searches for MacBook, Elasticsearch can return the matching products and rank them according to the query.
It can also support searches that combine multiple requirements:
Find products containing the words
MacBook Pro.Return only products costing less than ₹150,000.
Filter products by category.
Sort matching products by price.
Return the most relevant results first.
Provide suggestions while the user types.
Elasticsearch stores JSON documents inside indexes. An index is a logical collection of documents, similar in some respects to a database table or a MongoDB collection.
However, Elasticsearch is not a direct replacement for every database. A common architecture is to store the primary application data in PostgreSQL, MySQL, or MongoDB and use Elasticsearch as a separate search index.
2. Why Combine FastAPI with Elasticsearch?
FastAPI is a Python framework for building APIs. It provides request validation through Pydantic, dependency injection, automatic API documentation, and asynchronous request handling.
Elasticsearch provides the search capabilities that our application needs.
Together, they make it possible to build a dedicated search service.
Consider an e-commerce application:
React / Next.js Frontend
|
v
FastAPI Backend
|
v
Elasticsearch
|
v
Product Search ResultsThe frontend sends a search request to FastAPI. FastAPI validates the parameters, constructs an Elasticsearch query, executes the search, and returns a structured JSON response.
For a production e-commerce application, the architecture might also include a primary database:
React / Next.js
|
v
FastAPI Backend
/ \
v v
PostgreSQL Elasticsearch
Primary Data Search IndexPostgreSQL stores authoritative product information, while Elasticsearch maintains a searchable representation of those products.
This separation has several advantages:
Full-text search without writing complex SQL queries.
Relevance-based ranking.
Flexible filtering and sorting.
Efficient search over large document collections.
Support for autocomplete and search suggestions.
Aggregations for categories, price ranges, and analytics.
The main trade-off is additional infrastructure. Your application must keep the search index synchronized with the primary database and account for the possibility that indexed data may be temporarily stale.
3. Set Up the Project
Let's build a product search API using FastAPI and Elasticsearch.
First, create a project directory:
mkdir fastapi-elasticsearch-search
cd fastapi-elasticsearch-searchCreate a virtual environment:
python -m venv venvActivate it on macOS or Linux:
source venv/bin/activateOn Windows, use:
venv\Scripts\activateInstall the required dependencies:
pip install fastapi "uvicorn[standard]" "elasticsearch[async]" pydantic-settingsWe'll use the official asynchronous Elasticsearch Python client.
The AsyncElasticsearch client allows FastAPI to await Elasticsearch requests instead of blocking the event loop while waiting for search results.
For this example, we'll use a modern Elasticsearch 8.x or 9.x deployment with compatible client versions. Check the compatibility requirements for your chosen server and client versions before deployment.
A simple project structure looks like this:
fastapi-elasticsearch-search/
│
├── app/
│ ├── __init__.py
│ ├── main.py
│ ├── config.py
│ ├── elasticsearch_client.py
│ ├── schemas.py
│ └── search_service.py
│
├── requirements.txt
└── .envFor a small demonstration, you can initially keep the implementation in one file. Separating configuration, schemas, and search logic becomes more useful as the project grows.
4. Run Elasticsearch Locally
The easiest way to experiment with Elasticsearch is to run it using Docker.
If Docker is installed, you can start a single-node Elasticsearch instance for local development:
docker run --name elasticsearch-dev \
-p 9200:9200 \
-e discovery.type=single-node \
-e xpack.security.enabled=false \
-e ES_JAVA_OPTS="-Xms512m -Xmx512m" \
-m 1g \
docker.elastic.co/elasticsearch/elasticsearch:8.17.0This command uses Elasticsearch 8.17.0 as a pinned example version.
The security setting disables authentication and TLS, so use this configuration only for an isolated local development environment. Do not expose this container to an untrusted network or use this configuration in production.
For a production deployment, use an appropriately secured Elasticsearch installation with authentication, TLS, network restrictions, and managed credentials.
You can verify the local instance with:
curl http://localhost:9200A successful response contains information about the Elasticsearch node and cluster.
You can also open the endpoint in a browser:
http://localhost:9200If Elasticsearch fails to start, check the container logs:
docker logs elasticsearch-devElasticsearch can require substantial memory, so make sure Docker has enough resources allocated.
5. Configure FastAPI and Elasticsearch
Let's start by defining the application settings.
Create app/config.py:
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
elasticsearch_url: str = "http://localhost:9200"
elasticsearch_index: str = "products"
model_config = SettingsConfigDict(
env_file=".env",
extra="ignore",
)
settings = Settings()Create a .env file:
ELASTICSEARCH_URL=http://localhost:9200
ELASTICSEARCH_INDEX=productsFor local development, this configuration is sufficient.
In production, the connection settings should include the authentication and TLS configuration required by your Elasticsearch deployment. Avoid storing production passwords or API keys in version control.
Next, create app/elasticsearch_client.py:
from contextlib import asynccontextmanager
from elasticsearch import AsyncElasticsearch
from fastapi import FastAPI, Request
from app.config import settings
@asynccontextmanager
async def lifespan(app: FastAPI):
client = AsyncElasticsearch(
hosts=[settings.elasticsearch_url],
)
app.state.elasticsearch = client
try:
yield
finally:
await client.close()
def get_elasticsearch(
request: Request,
) -> AsyncElasticsearch:
return request.app.state.elasticsearchThe lifespan handler creates the Elasticsearch client when FastAPI starts and closes it when the application shuts down.
This is better than creating a new client for every request. The client manages its own connection pool and can reuse connections across requests.
Now we can access the client through FastAPI's dependency injection system.
6. Define the Product Schema
Before implementing search, let's define the structure of a product.
Create app/schemas.py:
from pydantic import BaseModel, Field
class Product(BaseModel):
id: str
name: str
description: str
category: str
price: float = Field(ge=0)
in_stock: bool = True
class ProductSearchResult(BaseModel):
id: str
name: str
description: str
category: str
price: float
in_stock: bool
class ProductSearchResponse(BaseModel):
total: int
page: int
size: int
results: list[ProductSearchResult]The Product model represents the data we'll index.
The ProductSearchResponse model defines the response returned to the frontend.
For example:
{
"total": 2,
"page": 1,
"size": 10,
"results": [
{
"id": "1",
"name": "Apple MacBook Pro",
"description": "Powerful laptop for developers",
"category": "laptops",
"price": 199999,
"in_stock": true
}
]
}Pydantic validates our response structure and makes the API documentation more informative.
Notice that the response includes pagination metadata. Returning this information makes it easier for a frontend application to implement page navigation.
7. Create the Elasticsearch Index
Elasticsearch indexes need mappings that describe how fields should be stored and searched.
For example, a product name might need full-text search, while a product category might need exact-match filtering.
These are different operations, so the field mappings should reflect their intended use.
Create app/search_service.py:
from elasticsearch import AsyncElasticsearch
from app.config import settings
async def create_products_index(
client: AsyncElasticsearch,
):
index_name = settings.elasticsearch_index
if await client.indices.exists(index=index_name):
return
await client.indices.create(
index=index_name,
mappings={
"properties": {
"id": {"type": "keyword"},
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword"
}
},
},
"description": {
"type": "text"
},
"category": {
"type": "keyword"
},
"price": {
"type": "float"
},
"in_stock": {
"type": "boolean"
},
}
},
)Let's understand these mappings.
text fields: Used for full-text search. Elasticsearch analyzes the text so that individual terms can match queries.
keyword fields: Used for exact matching, sorting, and aggregations. They're useful for values such as category names, identifiers, and status codes.
Numeric fields: Used for range filtering, sorting, and numerical calculations.
Boolean fields: Used for true-or-false conditions, such as whether a product is in stock.
The name.keyword subfield lets us use the same product name for full-text search and exact-value operations.
One important detail: Elasticsearch mappings generally cannot be changed arbitrarily after an index has been populated. If you need an incompatible mapping change, you may need to create a new index and reindex your documents.
Also, don't create an index on every incoming search request. Index initialization belongs in a startup process, a migration command, or a dedicated setup operation.
8. Index Product Documents
An index is useful only when it contains searchable documents.
Let's add a function to insert products into Elasticsearch.
Update app/search_service.py:
async def index_product(
client: AsyncElasticsearch,
product: dict,
):
await client.index(
index=settings.elasticsearch_index,
id=product["id"],
document=product,
refresh="wait_for",
)The id parameter assigns a stable Elasticsearch document identifier.
This matters because indexing the same product again with the same ID updates the existing document rather than creating a duplicate document with a different ID.
The refresh="wait_for" option waits for the document to become searchable through a refresh. It can be useful in local examples and tests, but you should avoid forcing refreshes on every write in a high-throughput production application because they can reduce indexing performance.
Let's index some sample products:
sample_products = [
{
"id": "1",
"name": "Apple MacBook Pro",
"description": (
"Powerful laptop for software development"
),
"category": "laptops",
"price": 199999,
"in_stock": True,
},
{
"id": "2",
"name": "Apple MacBook Air",
"description": (
"Lightweight laptop for everyday work"
),
"category": "laptops",
"price": 119999,
"in_stock": True,
},
{
"id": "3",
"name": "Dell XPS Laptop",
"description": (
"High-performance laptop for professionals"
),
"category": "laptops",
"price": 149999,
"in_stock": False,
},
{
"id": "4",
"name": "Logitech Wireless Mouse",
"description": (
"Wireless mouse for office and home use"
),
"category": "accessories",
"price": 2499,
"in_stock": True,
},
]You can create a setup function that inserts these documents.
For example, add the following function to app/search_service.py:
async def seed_products(
client: AsyncElasticsearch,
):
for product in sample_products:
await index_product(client, product)In a real project, place sample_products in a separate development fixture or script rather than mixing test data into the production search service.
For production systems, indexing is often performed by a background worker or an event-driven process that synchronizes changes from the primary database.
9. Build the Basic Search API
Now let's implement our first search endpoint.
The goal is to allow users to search product names and descriptions using a query parameter.
Create app/main.py:
from contextlib import asynccontextmanager
from elasticsearch import AsyncElasticsearch
from fastapi import (
Depends,
FastAPI,
HTTPException,
Query,
)
from elasticsearch import ApiError
from app.config import settings
from app.elasticsearch_client import (
get_elasticsearch,
)
from app.schemas import (
ProductSearchResponse,
ProductSearchResult,
)
from app.search_service import create_products_index
@asynccontextmanager
async def lifespan(app: FastAPI):
client = AsyncElasticsearch(
hosts=[settings.elasticsearch_url],
)
app.state.elasticsearch = client
try:
await create_products_index(client)
yield
finally:
await client.close()
app = FastAPI(
title="Product Search API",
version="1.0.0",
lifespan=lifespan,
)
@app.get(
"/api/products/search",
response_model=ProductSearchResponse,
)
async def search_products(
q: str = Query(
min_length=1,
max_length=100,
),
client: AsyncElasticsearch = Depends(
get_elasticsearch
),
):
try:
response = await client.search(
index=settings.elasticsearch_index,
query={
"multi_match": {
"query": q,
"fields": [
"name^3",
"description",
],
}
},
)
except ApiError as exc:
raise HTTPException(
status_code=503,
detail="Search service is temporarily unavailable",
) from exc
hits = response["hits"]["hits"]
results = [
ProductSearchResult(**hit["_source"])
for hit in hits
]
return ProductSearchResponse(
total=response["hits"]["total"]["value"],
page=1,
size=len(results),
results=results,
)The multi_match query searches multiple fields.
We've assigned a boost of ^3 to the product name:
"fields": ["name^3", "description"]This tells Elasticsearch that matches in the product name should generally contribute more to the relevance score than matches in the description.
For example, when searching for MacBook, products with the word in their names should generally rank higher than products that mention it only in their descriptions.
The exact order depends on the relevance scores and the indexed documents.
Important: This example combines the startup lifecycle and index initialization in main.py, so you should not also register the earlier standalone lifespan handler from elasticsearch_client.py. Use one application lifespan handler and one shared client. The standalone handler shown earlier illustrates the client lifecycle pattern; the integrated version here is the one used by this application.
Start the application:
uvicorn app.main:app --reloadOpen the API documentation:
http://127.0.0.1:8000/docsTry searching for:
/api/products/search?q=MacBookThe API should return products matching the query.
If the index is empty, insert the sample products before testing search. You can run a separate development seed script that creates the index and calls seed_products().
10. Add Filtering and Pagination
A real search API usually needs more than a query string.
Users may want to filter products by category, restrict results to items in stock, set a price range, and navigate through multiple pages.
Let's extend the endpoint with these features.
The following example replaces the basic search endpoint:
@app.get(
"/api/products/search",
response_model=ProductSearchResponse,
)
async def search_products(
q: str = Query(
min_length=1,
max_length=100,
),
category: str | None = None,
min_price: float | None = Query(
default=None,
ge=0,
),
max_price: float | None = Query(
default=None,
ge=0,
),
in_stock: bool | None = None,
page: int = Query(default=1, ge=1),
size: int = Query(default=10, ge=1, le=100),
client: AsyncElasticsearch = Depends(
get_elasticsearch
),
):
if (
min_price is not None
and max_price is not None
and min_price > max_price
):
raise HTTPException(
status_code=422,
detail="min_price cannot exceed max_price",
)
filters = []
if category is not None:
filters.append({
"term": {
"category": category
}
})
if in_stock is not None:
filters.append({
"term": {
"in_stock": in_stock
}
})
price_range = {}
if min_price is not None:
price_range["gte"] = min_price
if max_price is not None:
price_range["lte"] = max_price
if price_range:
filters.append({
"range": {
"price": price_range
}
})
try:
response = await client.search(
index=settings.elasticsearch_index,
from_=(page - 1) * size,
size=size,
query={
"bool": {
"must": [
{
"multi_match": {
"query": q,
"fields": [
"name^3",
"description",
],
}
}
],
"filter": filters,
}
},
)
except ApiError as exc:
raise HTTPException(
status_code=503,
detail="Search service is temporarily unavailable",
) from exc
hits = response["hits"]["hits"]
total_hits = response["hits"]["total"]
if isinstance(total_hits, dict):
total = total_hits["value"]
else:
total = total_hits
results = [
ProductSearchResult(**hit["_source"])
for hit in hits
]
return ProductSearchResponse(
total=total,
page=page,
size=size,
results=results,
)This endpoint uses Elasticsearch's bool query to combine full-text search with structured filters.
The must clause determines which documents match the text query.
The filter clause restricts the matching documents without contributing to the relevance score.
For example, a request might look like this:
/api/products/search?q=laptop&category=laptops&min_price=100000&max_price=160000&in_stock=true&page=1&size=10This searches for laptops priced between ₹100,000 and ₹160,000 that are currently in stock.
Why use filters instead of including everything in the text query?
Text search and structured filtering serve different purposes.
A full-text query determines whether a document is relevant to the user's search terms. A filter checks whether the document satisfies a condition such as category, availability, or price range.
Using filter clauses keeps the query easier to understand and can improve performance because Elasticsearch may cache eligible filter results.
A note about pagination
The from and size parameters work well for ordinary pagination.
However, deep pagination becomes expensive when the offset grows significantly. Elasticsearch normally limits the result window to 10,000 documents by default.
For large result sets, use search_after with a stable sort order. For consistent pagination while documents are changing, consider using a point-in-time (PIT) search context alongside search_after.
11. Improve Search Relevance
Returning matching documents is only part of a good search experience. We also need to make sure the most useful results appear first.
Elasticsearch calculates a relevance score for matching documents. The score depends on the query, indexed fields, term frequency, and other factors.
For example, suppose someone searches for:
wireless mouseA product named Wireless Mouse should generally rank above a product named Office Accessories whose description mentions a wireless mouse.
We can improve relevance by searching specific fields, boosting important fields, and using phrase matching.
Consider this query:
query = {
"bool": {
"should": [
{
"multi_match": {
"query": "wireless mouse",
"fields": [
"name^3",
"description",
],
}
},
{
"match_phrase": {
"name": {
"query": "wireless mouse",
"boost": 5,
}
}
},
],
"minimum_should_match": 1,
}
}The multi_match clause searches both the name and description, while the match_phrase clause gives an additional boost to products whose names contain the phrase in the specified order.
This is useful when users search for specific product names, brands, or technical terms.
Don't add boosts randomly. Test queries against representative data and examine the results to determine whether the ranking matches actual user expectations.
Elasticsearch also provides tools such as the Explain API and Profile API for investigating why a document matched or why a query performs slowly.
12. Implement Autocomplete
Autocomplete is another feature that makes a search API feel more responsive.
When users start typing, the frontend can request suggestions instead of waiting until they enter the complete search phrase.
For example:
User types: mac
Suggestions:
- MacBook Pro
- MacBook Air
- Mac MiniOne common approach is to use Elasticsearch's completion field.
To support it, add a dedicated field to the index mapping:
"suggest": {
"type": "completion"
}Each product document can contain a suggestion value:
{
"id": "1",
"name": "Apple MacBook Pro",
"suggest": {
"input": [
"Apple MacBook Pro",
"MacBook Pro",
"MacBook"
]
}
}Because mappings cannot always be changed in place, adding this field to an existing index may require creating a new index and reindexing the documents.
Now create an autocomplete endpoint:
@app.get("/api/products/autocomplete")
async def autocomplete_products(
q: str = Query(
min_length=1,
max_length=100,
),
client: AsyncElasticsearch = Depends(
get_elasticsearch
),
):
try:
response = await client.search(
index=settings.elasticsearch_index,
suggest={
"product_suggestions": {
"prefix": q,
"completion": {
"field": "suggest",
"size": 10,
"skip_duplicates": True,
},
}
},
)
except ApiError as exc:
raise HTTPException(
status_code=503,
detail="Search service is temporarily unavailable",
) from exc
suggestions = (
response["suggest"]["product_suggestions"][0]
["options"]
)
return {
"suggestions": [
item["text"]
for item in suggestions
]
}A request to:
/api/products/autocomplete?q=macmight return:
{
"suggestions": [
"Apple MacBook Pro",
"MacBook Pro",
"MacBook"
]
}The actual results depend on the indexed suggestion values and the configured completion behavior.
For a good frontend experience, debounce autocomplete requests so that the browser doesn't send a new request for every keystroke. Also consider caching common suggestions and limiting the maximum number of returned options.
13. Handle Elasticsearch Errors Properly
Search services can fail for reasons unrelated to the user's query.
Elasticsearch might become temporarily unavailable, a request might time out, or an index might be missing.
Your API should handle expected failures without exposing internal infrastructure details.
For example:
from elasticsearch import ApiError
from elasticsearch import ConnectionError as ESConnectionError
from elasticsearch import ConnectionTimeout
from fastapi import HTTPException
async def execute_search(
client: AsyncElasticsearch,
query: dict,
):
try:
return await client.search(
index=settings.elasticsearch_index,
query=query,
)
except (
ESConnectionError,
ConnectionTimeout,
) as exc:
raise HTTPException(
status_code=503,
detail="Search service is temporarily unavailable",
) from exc
except ApiError as exc:
# Log the detailed error securely on the server.
raise HTTPException(
status_code=503,
detail="Unable to complete the search request",
) from excThis helper illustrates the error-handling pattern; use it consistently in your search endpoints if you adopt it.
In a production application, distinguish between client errors, configuration problems, and transient infrastructure failures. For example, an invalid query should not automatically be treated the same way as an Elasticsearch outage.
Log useful diagnostic information on the server, but avoid returning stack traces, credentials, connection strings, or internal hostnames to clients.
You should also configure reasonable connection and request timeouts. Retries may help with transient failures, but only retry operations when doing so is safe and useful. Repeated retries against an overloaded cluster can make the problem worse.
14. Keep Elasticsearch Synchronized with Your Database
One of the most important design decisions is deciding how product data reaches Elasticsearch.
If PostgreSQL is the primary database, the normal flow might be:
Product Created or Updated
|
v
PostgreSQL
|
v
Background Worker
|
v
Elasticsearch
|
v
Search APIWhen a product is created or updated, the application also needs to update the search index.
There are several ways to implement this.
Direct indexing
The API writes to the primary database and then indexes the product in Elasticsearch.
This is straightforward, but it introduces a failure scenario: the database transaction may succeed while indexing fails.
If the API treats both operations as one logical operation without a recovery strategy, the two systems can become inconsistent.
Background jobs
The API writes to the primary database and submits an indexing job to a queue.
A background worker processes the job and updates Elasticsearch.
This separates search indexing from the main request path, but requires reliable job delivery, retry handling, and monitoring.
Transactional outbox
For more reliable synchronization, use the transactional outbox pattern.
The application writes the product change and an outbox event in the same database transaction. A background worker reads pending events and updates Elasticsearch.
This prevents the application from committing the database change without also recording the event that must be processed.
The worker should handle retries and duplicate events safely. Stable document IDs and idempotent indexing operations help ensure that processing the same event more than once doesn't create duplicate products.
Remember that Elasticsearch is often eventually consistent with the primary database. A newly updated product may not immediately appear in search results.
For most product catalogs, this is acceptable. If your business requires immediate consistency for a particular operation, design that workflow explicitly rather than assuming search indexing is synchronous.
15. Security Considerations
A powerful search API can also expose sensitive data if authorization is not implemented carefully.
For example, a multi-tenant SaaS application might store documents belonging to multiple organizations in the same index.
If the API accepts a tenant ID directly from the client and uses it without validating the authenticated user's access, one organization might retrieve another organization's documents.
To avoid this, derive the tenant identity from the authenticated user's trusted server-side context and apply the tenant filter to every relevant query.
For example:
query = {
"bool": {
"must": [
{
"multi_match": {
"query": search_text,
"fields": [
"name",
"description",
],
}
}
],
"filter": [
{
"term": {
"tenant_id": authenticated_tenant_id
}
}
],
}
}Here, authenticated_tenant_id must come from a validated authorization process, not from an untrusted request parameter.
Other security practices include:
Require authentication for private search endpoints.
Enforce resource-level permissions on sensitive documents.
Restrict network access to Elasticsearch.
Use TLS and appropriate credentials.
Avoid exposing internal Elasticsearch APIs to public clients.
Validate query parameters and limit page sizes.
Avoid logging access tokens or sensitive search content unnecessarily.
Review which fields are returned in
_sourceso that internal metadata doesn't leak to clients.
For complex applications, consider index-level permissions, document-level security, or separate indexes for different security boundaries where appropriate.
16. Performance Optimization for Production
Once your API works correctly, the next step is making it reliable under real traffic.
Here are several practical improvements.
Reuse the asynchronous client
Create one Elasticsearch client per application process and reuse its connection pool. Close it during application shutdown.
Creating a client for every request wastes resources and can increase connection overhead.
Use bulk indexing
If you need to index thousands of products, avoid sending one request per product.
The Bulk API lets you submit multiple indexing operations in one request, which generally improves throughput.
For large imports, process data in manageable batches and monitor bulk failures rather than assuming every document was indexed successfully.
Avoid excessive refreshes
Frequent refreshes can reduce indexing throughput.
Use refresh behavior appropriate to your workload. Most production indexing pipelines should not force a refresh after every document.
Choose mappings carefully
Use keyword fields for exact-match filters, sorting, and aggregations. Use text fields for full-text search.
Avoid mapping every arbitrary field dynamically when the document structure is uncontrolled. Excessive field growth can cause mapping problems and waste resources.
Set sensible result limits
Limit the number of results returned by a single request. For ordinary search endpoints, a maximum page size of 50 or 100 is often a reasonable starting point, though the right value depends on the workload.
Use search_after for deep pagination instead of requesting extremely large offsets.
Monitor the search service
Monitor metrics such as:
Search request latency.
Search error rates.
Elasticsearch CPU and memory utilization.
JVM heap usage where applicable.
Indexing throughput.
Rejected requests and thread-pool queues.
Index size and document count.
These metrics help you detect performance problems before they become serious user-facing issues.
Cache carefully
Caching popular search results can reduce repeated query load, but search results may change as documents are updated.
If you introduce application-level caching, define an expiration policy and invalidation strategy. Always include relevant query parameters and tenant or authorization context in cache keys so that results are not accidentally shared across users who should see different data.
17. When Should You Use Elasticsearch?
Elasticsearch is particularly useful when an application needs more sophisticated search than ordinary database queries can conveniently provide.
Good use cases include:
E-commerce platforms: Search products by name, description, brand, category, price, and availability.
Job portals: Search jobs by title, skills, location, company, and experience requirements.
Documentation websites: Search articles and technical documentation using full-text queries.
Content management systems: Find articles, pages, and media based on their content and metadata.
Log analytics: Search large volumes of application logs and filter events by timestamp, service, status, and other fields.
AI applications: Retrieve relevant documents using keyword search, semantic search, or hybrid retrieval when configured with suitable vector-search capabilities.
However, Elasticsearch may be unnecessary for a small application with a limited dataset and simple search requirements. PostgreSQL full-text search or MongoDB's search capabilities may be sufficient.
Choose Elasticsearch when its search functionality justifies the additional infrastructure and operational complexity.
Conclusion
FastAPI and Elasticsearch make a powerful combination for building modern search APIs. FastAPI provides a clean interface for validating requests, handling asynchronous operations, and documenting endpoints, while Elasticsearch handles full-text search, relevance scoring, filtering, and autocomplete.
In this tutorial, we covered how to configure an Elasticsearch client, define index mappings, index product documents, build a search endpoint, implement filtering and pagination, improve relevance, and add autocomplete.
We also explored important production considerations, including error handling, secure tenant filtering, database synchronization, bulk indexing, and performance monitoring.
The key takeaway is that building a reliable search API involves more than writing an Elasticsearch query. You also need a sensible index design, a synchronization strategy, secure authorization, and an operational plan for handling failures.
Start with a small search endpoint, measure its behavior against realistic data, and introduce more advanced features as your application's requirements grow. This approach will help you build a search service that remains useful and maintainable as your application scales.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


