How to build a search engine in SQL, Node.js, HTML, CSS, and JS
- User
How to build a search engine in SQL, Node.js, HTML, CSS, and JS
- Assistant
How to build a search engine in SQL, Node.js, HTML, CSS, and JS
Building a search engine involves multiple components, including data storage, backend processing, and frontend interfaces. Below is a comprehensive guide to building a basic search engine using SQL for data storage, Node.js for the backend, and HTML, CSS, and JavaScript for the frontend.
Let's dive into each step in detail.
Create a Project Directory
mkdir search-engine
cd search-engine
Initialize npm
npm init -y
Install Necessary Packages
npm install express sqlite3 body-parser
For a basic search engine, you need at least one table to store documents or records that will be searchable.
CREATE TABLE documents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL
);
Create a Database File
Create a file named database.sqlite and set up the schema.
// setupDatabase.js
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./database.sqlite');
db.serialize(() => {
db.run(`CREATE TABLE IF NOT EXISTS documents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
content TEXT NOT NULL
)`);
const stmt = db.prepare("INSERT INTO documents (title, content) VALUES (?, ?)");
// Example Data
stmt.run("First Document", "This is the content of the first document.");
stmt.run("Second Document", "Content for the second document goes here.");
stmt.run("Third Document", "Here is some more content for the third document.");
stmt.finalize();
});
db.close();
Run the Setup Script
node setupDatabase.js
This will create database.sqlite with the documents table and insert some sample data.
Your project directory should look like this:
search-engine/
├── database.sqlite
├── package.json
├── setupDatabase.js
├── server.js
└── public/
├── index.html
├── styles.css
└── script.js
server.js// server.js
const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const path = require('path');
const app = express();
const db = new sqlite3.Database('./database.sqlite');
// Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
// API endpoint for search
app.get('/api/search', (req, res) => {
const query = req.query.q;
if (!query) {
return res.json({ results: [] });
}
// Simple search using LIKE
const sql = `
SELECT id, title, content
FROM documents
WHERE title LIKE ? OR content LIKE ?
LIMIT 10
`;
const searchTerm = `%${query}%`;
db.all(sql, [searchTerm, searchTerm], (err, rows) => {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json({ results: rows });
});
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
public directory serves the frontend files./api/search handles GET requests with a query parameter q for the search term. It searches the documents table where the title or content contains the search term using SQL's LIKE operator.Create the frontend files inside the public directory.
public/index.html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Search Engine</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="search-container">
<h1>Search Engine</h1>
<form id="search-form">
<input type="text" id="search-input" placeholder="Enter search terms..." required>
<button type="submit">Search</button>
</form>
</div>
<div class="results-container" id="results"></div>
<script src="script.js"></script>
</body>
</html>
public/styles.css/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.search-container {
background-color: #fff;
padding: 20px;
text-align: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin: 50px auto;
width: 50%;
border-radius: 8px;
}
.search-container h1 {
margin-bottom: 20px;
}
#search-form {
display: flex;
justify-content: center;
}
#search-input {
width: 70%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px 0 0 4px;
outline: none;
}
#search-form button {
padding: 10px 20px;
font-size: 16px;
border: none;
background-color: #28a745;
color: #fff;
cursor: pointer;
border-radius: 0 4px 4px 0;
}
#search-form button:hover {
background-color: #218838;
}
.results-container {
width: 60%;
margin: 20px auto;
}
.result-item {
background-color: #fff;
padding: 15px;
margin-bottom: 10px;
border-radius: 4px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.result-item h3 {
margin: 0 0 10px 0;
}
.result-item p {
margin: 0;
color: #555;
}
public/script.js// script.js
document.getElementById('search-form').addEventListener('submit', function(e) {
e.preventDefault();
const query = document.getElementById('search-input').value.trim();
if (query) {
search(query);
}
});
function search(query) {
fetch(`/api/search?q=${encodeURIComponent(query)}`)
.then(response => response.json())
.then(data => {
displayResults(data.results);
})
.catch(error => {
console.error('Error:', error);
});
}
function displayResults(results) {
const resultsContainer = document.getElementById('results');
resultsContainer.innerHTML = '';
if (results.length === 0) {
resultsContainer.innerHTML = '<p>No results found.</p>';
return;
}
results.forEach(item => {
const div = document.createElement('div');
div.className = 'result-item';
const title = document.createElement('h3');
title.textContent = item.title;
const content = document.createElement('p');
content.textContent = item.content;
div.appendChild(title);
div.appendChild(content);
resultsContainer.appendChild(div);
});
}
/api/search endpoint with the search query.With the frontend and backend in place, you can now test the search functionality.
Start your Node.js server.
node server.js
You should see:
Server is running on port 3000
http://localhost:3000.The current implementation uses the LIKE operator, which is simple but not very efficient for large datasets. Consider implementing full-text search for better performance and relevance.
Modify the Database Setup
Update setupDatabase.js to create a virtual table using FTS5.
// setupDatabase.js
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('./database.sqlite');
db.serialize(() => {
db.run(`DROP TABLE IF EXISTS documents`);
db.run(`CREATE VIRTUAL TABLE documents USING fts5(title, content)`);
const stmt = db.prepare("INSERT INTO documents (title, content) VALUES (?, ?)");
// Example Data
stmt.run("First Document", "This is the content of the first document.");
stmt.run("Second Document", "Content for the second document goes here.");
stmt.run("Third Document", "Here is some more content for the third document.");
stmt.finalize();
});
db.close();
Re-run the Setup Script
node setupDatabase.js
Update the Search Query in server.js
Modify the SQL query to use MATCH for full-text search.
// server.js (modify the /api/search endpoint)
app.get('/api/search', (req, res) => {
const query = req.query.q;
if (!query) {
return res.json({ results: [] });
}
// Full-Text Search using MATCH
const sql = `
SELECT id, title, content
FROM documents
WHERE documents MATCH ?
LIMIT 10
`;
const searchTerm = query + '*'; // Using wildcard for partial matches
db.all(sql, [searchTerm], (err, rows) => {
if (err) {
return res.status(500).json({ error: err.message });
}
res.json({ results: rows });
});
});
To make your search engine more robust, consider adding the following features:
Once your search engine is ready and tested locally, you can deploy it to a cloud platform or hosting service such as:
Install the Heroku CLI
Log In to Heroku
heroku login
Create a Procfile
Create a file named Procfile in the root directory.
echo "web: node server.js" > Procfile
Initialize Git Repository
git init
git add .
git commit -m "Initial commit"
Create Heroku App
heroku create your-app-name
Push to Heroku
git push heroku master
Open the App
heroku open
Your search engine should now be live!
Building a search engine with SQL, Node.js, HTML, CSS, and JavaScript involves setting up a database, creating a backend server to handle search queries, and developing a user-friendly frontend interface. While this guide covers a basic implementation, there's a vast scope for enhancements and optimizations to create a more sophisticated and efficient search engine. Exploring full-text search capabilities, improving search algorithms, and enhancing the user interface are excellent next steps to build upon this foundation.
Feel free to expand the functionality based on your specific needs and the nature of the data you wish to search.
Not yet included in a published release.
Test the Enhanced Search
Restart the server and perform searches. You should notice improved search capabilities, including partial matches and better relevance.