Building a Semantic Search Engine with Next.js and Elasticsearch

April 28, 2025
Next.js
Django
Elasticsearch
Text Embeddings
Search

In this article, I'll share my experience building CozyBible.com, a semantic search engine for Bible verses using Next.js, Django, and Elasticsearch.

Why Semantic Search?

Traditional keyword search is limited - it only finds exact matches. Semantic search understands the meaning behind queries, providing more relevant results even when the exact words aren't present.

Architecture Overview

The application has three main components:

  • Next.js frontend for the user interface
  • Django REST API for business logic
  • Elasticsearch for indexing and searching

Text Embeddings

The key to semantic search is text embeddings - numerical representations of text that capture meaning. I used OpenAI's text-embedding-3-small model to convert text into 1,536-dimension vectors.

Indexing in Elasticsearch

Elasticsearch stores these embeddings in a dense_vector field and runs nearest-neighbor searches against them. Here's a simplified version of the indexing and query code:

# Map the embedding field, then index each verse with its vector
es.indices.create(index="bible_verses", mappings={
    "properties": {
        "text": {"type": "text"},
        "embedding": {"type": "dense_vector", "dims": 1536, "index": True},
    }
})

es.index(index="bible_verses", document={"text": text, "embedding": embedding})

# Embed the query the same way, then find the closest verses
results = es.search(
    index="bible_verses",
    knn={
        "field": "embedding",
        "query_vector": get_embedding(query),
        "k": 10,
        "num_candidates": 100,
    },
)

Building the Search API

The Django REST API handles the search logic, converting each user query into an embedding and finding the closest verses.

Next.js Frontend

The frontend provides a clean, intuitive interface for users to enter natural language queries and view results.

Conclusion

Building a semantic search engine is a fascinating project that combines NLP, search technology, and modern web development. The result is a search box that takes a question in plain language instead of an exact phrase.