
Traditional search engines usually rely on keywords to find relevant information. However, keyword-based search can struggle when users express the same idea using different words.
For example, imagine a user searches for:
"How can I create a backend using JavaScript?"
Your database contains an article titled:
"A Beginner's Guide to Node.js Server-Side Development"
A traditional keyword search might not rank the article highly because the wording differs. A semantic search engine, however, can identify the relationship between the query and the article based on their meaning.
This is where semantic search and vector databases become useful.
Semantic search uses AI models to understand the meaning of queries and documents. Vector databases store numerical representations of information, called embeddings, and retrieve relevant results based on vector similarity.
In this tutorial, you will learn how semantic search works, how vector databases support it, and how to build a semantic search engine using Node.js, OpenAI embeddings, and ChromaDB.
What Is Semantic Search?
Semantic search is a search technique that attempts to understand the meaning and intent behind a user's query instead of relying exclusively on exact keyword matches.
It uses techniques such as natural language processing, embeddings, and vector similarity to retrieve relevant information.
For example, consider these search queries:
"How do I make my website faster?"
"Ways to improve website performance"
"How can I optimize page loading speed?"
Although the wording differs, all three queries express a similar intent.
A semantic search engine can identify these relationships and retrieve relevant documents even when they do not contain the exact words used in the query.
Key Benefits of Semantic Search
Understands semantic relationships between words and sentences.
Helps retrieve relevant content when queries use different wording.
Supports natural-language queries.
Improves document discovery in large collections.
Can be combined with traditional keyword search.
Provides a foundation for AI chatbots and RAG applications.
What Is a Vector Database?
A vector database stores and retrieves numerical vectors representing data such as text, images, and other supported content.
These numerical representations are called embeddings.
An embedding model converts text into a vector containing numerical values.
For example:
const embedding = [
0.21,
-0.45,
0.78,
0.12,
-0.33
];These values are illustrative rather than actual output from a particular embedding model.
An embedding model generates vectors that encode learned patterns and relationships. A vector database can compare these vectors to find similar items.
Popular vector search options include:
ChromaDB
MongoDB Atlas Vector Search
Pinecone
Weaviate
Qdrant
The right choice depends on your application architecture, data size, deployment requirements, and operational needs.
How Does a Semantic Search Engine Work?
A semantic search engine typically follows a sequence of steps.
Step 1: Collect Documents
The application collects information from sources such as websites, blogs, PDFs, product catalogs, or documentation.
Step 2: Generate Document Embeddings
An embedding model converts each document, or each document chunk, into a numerical vector.
Step 3: Store the Embeddings
The application stores the embeddings alongside document content and useful metadata in a vector database.
Step 4: Receive a Search Query
A user enters a natural-language query, such as:
"Which database should I use for an AI application?"
Step 5: Generate a Query Embedding
The same compatible embedding model converts the search query into a vector.
Step 6: Perform Vector Search
The vector database compares the query embedding with stored document embeddings and retrieves relevant results.
Step 7: Display Search Results
The application returns the matching documents, titles, links, or other useful information to the user.
The complete workflow looks like this:
Documents → Embedding Model → Vector Database → Search Query → Query Embedding → Similarity Search → Search Results
Technologies Used in This Tutorial
We will build a simple semantic search engine using the following technologies.
Technology | Purpose |
|---|---|
Node.js | Runs the backend application |
JavaScript | Implements the search logic |
OpenAI API | Generates text embeddings |
ChromaDB | Stores embeddings and retrieves similar documents |
LangChain.js | Connects the embedding model and vector database |
dotenv | Loads environment variables |
This project is a useful starting point for developers learning AI application development with Node.js.
Step 1: Create a Node.js Project
First, create a new project directory.
mkdir semantic-search-engine
cd semantic-search-engineInitialize the project:
npm init -yInstall the required dependencies:
npm install @langchain/core @langchain/openai @langchain/chroma dotenvConfigure your package.json to use ES modules:
{
"type": "module",
"scripts": {
"start": "node index.js"
}
}If your package.json already contains other fields, keep them and add or update the relevant configuration.
Step 2: Start ChromaDB
We will use ChromaDB to store document embeddings and perform similarity searches.
If Docker is installed, start a local ChromaDB server:
docker run -d \
--name chromadb \
-p 8000:8000 \
chromadb/chromaCheck whether the container is running:
docker psYou can inspect the logs with:
docker logs chromadbThis setup is suitable for a basic local development example. For production, configure persistent storage, access controls, backups, and other necessary security measures.
Step 3: Configure Your Environment Variables
Create a .env file in the project root:
OPENAI_API_KEY=your_openai_api_keyReplace the placeholder with your actual API key.
Create a .gitignore file:
node_modules/
.envSecurity tip: Never expose your API key in frontend JavaScript or commit it to a public Git repository.
This tutorial uses OpenAI embeddings. You can also use another compatible embedding model by replacing the embedding integration.
Step 4: Prepare Documents for Semantic Search
Our search engine needs documents to search.
For this example, we will create a small collection of technical articles.
Create an index.js file:
import "dotenv/config";
import { Document } from "@langchain/core/documents";
import { Chroma } from "@langchain/chroma";
import { OpenAIEmbeddings } from "@langchain/openai";
const embeddings = new OpenAIEmbeddings({
model: "text-embedding-3-small",
});
const vectorStore = new Chroma(embeddings, {
collectionName: "semantic_search_articles",
host: "localhost",
port: 8000,
});
const documents = [
new Document({
pageContent:
"Node.js is a JavaScript runtime used to build scalable backend applications and REST APIs.",
metadata: {
title: "Introduction to Node.js",
category: "Backend Development",
url: "/blogs/introduction-to-nodejs",
},
}),
new Document({
pageContent:
"React is a JavaScript library used to build interactive user interfaces and frontend applications.",
metadata: {
title: "Introduction to React",
category: "Frontend Development",
url: "/blogs/introduction-to-react",
},
}),
new Document({
pageContent:
"Redis is an in-memory data store commonly used for caching, fast lookups, and session management.",
metadata: {
title: "Redis for Developers",
category: "Backend Development",
url: "/blogs/redis-for-developers",
},
}),
new Document({
pageContent:
"Vector databases store embeddings and retrieve semantically similar information for AI applications.",
metadata: {
title: "Understanding Vector Databases",
category: "Artificial Intelligence",
url: "/blogs/vector-databases",
},
}),
new Document({
pageContent:
"Retrieval-Augmented Generation combines document retrieval with language models to generate context-aware answers.",
metadata: {
title: "Introduction to RAG",
category: "Artificial Intelligence",
url: "/blogs/introduction-to-rag",
},
}),
];Each document contains three important elements:
pageContent: The text that will be searched.metadata: Additional information about the document.url: A link that can be used to navigate to the original article.
Metadata makes it easier to display search results and filter documents by category.
Step 5: Generate Embeddings and Store Documents
Now we need to convert the documents into embeddings and store them in ChromaDB.
Add the following code to index.js:
async function indexDocuments() {
await vectorStore.addDocuments(documents);
console.log("Documents indexed successfully!");
}
await indexDocuments();When addDocuments() is called, the LangChain integration uses the configured embedding model to generate vectors and stores the documents in ChromaDB.
Run the application:
npm startYou should see a message confirming that the documents have been indexed.
For this demonstration, the documents are inserted each time the script runs. In a real application, use stable document IDs and an appropriate update or upsert strategy to avoid duplicate records.
Step 6: Implement Semantic Search
Now let's create the main search function.
Add the following code after the document-indexing function:
async function semanticSearch(query, limit = 3) {
if (!query || typeof query !== "string") {
throw new Error("A valid search query is required.");
}
const results = await vectorStore.similaritySearch(
query,
limit
);
return results.map((document) => ({
title: document.metadata.title,
category: document.metadata.category,
url: document.metadata.url,
content: document.pageContent,
}));
}This function accepts a search query and returns the most relevant documents retrieved by the vector store.
Now test it:
const results = await semanticSearch(
"How can I create backend applications using JavaScript?"
);
console.log(JSON.stringify(results, null, 2));Although the query does not exactly match the article's title, the search engine may retrieve the Node.js article because the content expresses a related idea.
The actual results depend on the embedding model, the documents, and the similarity ranking.
Step 7: Understand the Search Results
Suppose a user searches for:
How can I create backend applications using JavaScript?The search engine may return a result similar to this:
[
{
"title": "Introduction to Node.js",
"category": "Backend Development",
"url": "/blogs/introduction-to-nodejs",
"content": "Node.js is a JavaScript runtime used to build scalable backend applications and REST APIs."
}
]This is an illustrative result rather than guaranteed output.
The important point is that the search engine can retrieve related content without requiring an exact title match.
Unlike a simple keyword search, semantic search compares vector representations to identify related content.
Step 8: Add Metadata Filtering
Sometimes you want to search only within a particular category.
For example, suppose a user wants information about AI rather than frontend or backend development.
You can add a metadata filter:
async function searchByCategory(query, category) {
const results = await vectorStore.similaritySearch(
query,
5,
{
category,
}
);
return results.map((document) => ({
title: document.metadata.title,
category: document.metadata.category,
url: document.metadata.url,
content: document.pageContent,
}));
}Use the function like this:
const results = await searchByCategory(
"How do AI applications retrieve relevant information?",
"Artificial Intelligence"
);
console.log(results);This approach restricts retrieval to documents matching the selected category.
Check the documentation for your installed LangChain integration version to confirm its supported metadata-filter syntax.
Step 9: Build a Search API with Express.js
Now let's expose the semantic search functionality through a REST API.
Install Express:
npm install expressCreate a file named server.js:
import "dotenv/config";
import express from "express";
import { Chroma } from "@langchain/chroma";
import { OpenAIEmbeddings } from "@langchain/openai";
const app = express();
app.use(express.json());
const embeddings = new OpenAIEmbeddings({
model: "text-embedding-3-small",
});
const vectorStore = new Chroma(embeddings, {
collectionName: "semantic_search_articles",
host: "localhost",
port: 8000,
});
app.post("/api/search", async (req, res) => {
try {
const { query } = req.body;
if (typeof query !== "string" || !query.trim()) {
return res.status(400).json({
success: false,
message: "A valid search query is required.",
});
}
const results = await vectorStore.similaritySearch(
query.trim(),
5
);
return res.json({
success: true,
results: results.map((document) => ({
title: document.metadata.title,
category: document.metadata.category,
url: document.metadata.url,
content: document.pageContent,
})),
});
} catch (error) {
console.error("Semantic search failed:", error);
return res.status(500).json({
success: false,
message: "Unable to complete the search.",
});
}
});
app.listen(3000, () => {
console.log("Semantic search API running on port 3000");
});Update your package.json script:
{
"scripts": {
"start": "node server.js"
}
}Make sure the ChromaDB collection has already been populated using the indexing process in the previous steps.
In a real application, keep document ingestion separate from the API server's startup process so you do not repeatedly index documents every time the server restarts.
Test the API
Start the server:
npm startSend a POST request to:
http://localhost:3000/api/searchRequest body:
{
"query": "How can I build a backend with JavaScript?"
}The API will return the most relevant documents from ChromaDB.
You can test this endpoint using Postman or another HTTP client.
For production, add authentication where appropriate, request-size limits, rate limiting, timeouts, and monitoring.
Step 10: Improve Search Quality
A basic semantic search engine is a useful starting point, but real-world applications often require additional improvements.
1. Use Document Chunking
Large documents should often be split into smaller, meaningful sections before generating embeddings.
For example, a 5,000-word technical article could be divided into chunks containing individual sections.
This helps the system retrieve the most relevant part of an article instead of returning the entire document.
The best chunk size depends on the document structure, embedding model, and application requirements.
2. Choose an Appropriate Embedding Model
The embedding model has a significant impact on retrieval quality.
Consider factors such as:
Semantic retrieval accuracy.
Supported languages.
Embedding dimensions.
API cost.
Latency.
Privacy and deployment requirements.
Evaluate candidate models using real queries from your application.
3. Use Metadata Effectively
Store useful metadata such as:
Document title.
Category.
Source URL.
Publication date.
Author.
Access permissions.
Metadata enables filtering and helps your application display meaningful results.
4. Combine Keyword Search and Semantic Search
Semantic search is useful for understanding meaning, but exact keyword search is still important.
For example, searching for a specific error code or product identifier may work better with exact matching.
Hybrid search combines keyword-based retrieval with vector search. Depending on your implementation, you can combine or rerank results from both approaches.
5. Evaluate Retrieval Quality
Test your search engine using representative queries and known relevant documents.
Measure whether the expected documents appear among the top results.
Useful evaluation metrics include precision at K, recall at K, and mean reciprocal rank.
These metrics help you determine whether changes to the embedding model, chunk size, or search configuration improve the results.
Common Problems and Solutions
ChromaDB Connection Errors
If your Node.js application cannot connect to ChromaDB:
Verify that Docker is running.
Check that the ChromaDB container is active.
Confirm the configured hostname and port.
Inspect the container logs.
Verify that the application can access the server.
Embedding API Errors
If embedding requests fail:
Check your API key.
Verify that your account has access to the selected model.
Check API quota and rate limits.
Review your network connection.
Implement appropriate error handling.
Poor Search Results
If results are not relevant:
Improve document quality.
Review the chunking strategy.
Test a different embedding model.
Add metadata filters where appropriate.
Evaluate retrieval settings with representative queries.
Duplicate Documents
If running your indexing script repeatedly creates duplicates, use stable document IDs and an appropriate update or upsert strategy.
Package Compatibility Problems
LangChain integrations can change between versions. If imports or constructor options do not work, consult the current documentation for the versions installed in your project.
Best Practices for Production Semantic Search
Before deploying a semantic search engine, consider these recommendations:
Keep API keys secure: Store credentials in environment variables or a secrets manager.
Separate ingestion from search: Index documents through a dedicated workflow rather than on every API request.
Use stable document identifiers: Make updates and deletions reliable.
Configure persistent storage: Ensure indexed data survives restarts.
Apply access controls: Users should only retrieve documents they are authorized to access.
Monitor latency and cost: Track embedding requests, search latency, and failures.
Test relevance: Evaluate results using realistic user queries.
Handle document updates: Recompute embeddings when source content changes.
Protect against abuse: Validate input, apply rate limits, and set suitable request limits.
Use hybrid search when appropriate: Combine semantic matching with keyword matching for better results.
Conclusion
Semantic search makes it possible to retrieve information based on meaning rather than relying exclusively on exact keywords.
By combining Node.js, an embedding model, LangChain, and ChromaDB, you can build a search engine that retrieves relevant documents from natural-language queries.
In this tutorial, you learned how to:
Understand semantic search and vector databases.
Generate and store document embeddings.
Perform semantic similarity searches.
Filter results using metadata.
Build a semantic search REST API with Express.js.
Improve retrieval quality for production applications.
You can extend this project to create an AI-powered blog search engine, documentation search platform, product discovery system, or RAG-based chatbot.
Start with a small document collection, test the search results, and gradually improve the system as your application grows.
Frequently Asked Questions (FAQs)
1. What is a semantic search engine?
A semantic search engine retrieves information based on the meaning and intent of a query rather than relying exclusively on exact keyword matches.
2. Why are vector databases used in semantic search?
Vector databases store embeddings and retrieve vectors that are similar to a query vector. This makes them useful for finding semantically related documents.
3. Can I build a semantic search engine using Node.js?
Yes. You can use Node.js with an embedding model, a vector database such as ChromaDB, and an integration framework such as LangChain.
4. What is the difference between semantic search and keyword search?
Keyword search focuses on matching words or terms. Semantic search compares representations of meaning and can retrieve relevant content even when the query uses different wording.
5. Is ChromaDB suitable for semantic search?
Yes. ChromaDB supports storing embeddings and retrieving semantically similar documents, making it useful for semantic search and RAG applications.
6. What is the role of embeddings in semantic search?
Embeddings convert text into numerical vectors that capture learned patterns and relationships. The search engine compares query and document vectors to retrieve relevant results.
7. Can semantic search be used in RAG applications?
Yes. A RAG system can use semantic search to retrieve relevant documents and provide them as context to a language model when generating an answer.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


