-->
With a Real World Example: How to Create a Search Engine Using Flask and Python, with Source Code.

With a Real World Example: How to Create a Search Engine Using Flask and Python, with Source Code.

Back to top

Updated by Ashirafu Kibalama on April 02, 2024

"Here is an example of creating a search engine using Flask and Python. The source code will also be provided."


We will guide you in creating a Python and Flask search engine. 


You'll learn to handle user input, query a database, and display search results dynamically. 


By the end of this tutorial, you'll have a fully functional search engine that you can customize and integrate into your web applications.


Below is a basic example of a search engine implemented using Flask in Python. 


In this example, we are dealing with a real-world situation where we must retrieve documents from a database to create a search engine using Flask and Python with source code.

#home page


#Search within the sidebar



6 Steps to Create a Search Engine Using Flask and Python, with Source Code.


Step 1) Import the requirements, for example:

from datetime import date

from flask import Flask, render_template, redirect, url_for, flash, request, make_response, send_file
from flask_bootstrap import Bootstrap5
from flask_ckeditor import CKEditor


Step 2) Create the Search functionality:



This line performs a search operation on a database table named Posts.




It uses SQLAlchemy's filtering mechanism to filter the rows of the Posts table where either the title column or the body column contains the query string. 


The like method with the % wildcard allows for partial matches. 


The | operator performs a logical OR operation between the two filter conditions. 


Finally, .all() fetches all the matching rows from the database.


This line returns the search results obtained from the database query.

In summary, the function searches for posts in a database table (Posts) based on a given query string, considering both the title and the body of the posts. It then returns the matching posts as results.

#main.py


# OTHER CODES ABOVE

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///our_posts.db'
db = SQLAlchemy(model_class=Base)
db.init_app(app)
migrate = Migrate(app, db)


# SEARCH FUNCTION STARTS HERE

def search_results(query):
# Execute a query to fetch documents containing the query string
results = Posts.query.filter(Posts.title.like(f'%{query}%') | Posts.body.like(f'%{query}%')).all()

return results


# SEARCH FUNCTION ENDS HERE

# CONFIGURE TABLE
# CREATE TABLE IN DB FOR POSTS
class Posts(db.Model):
__tablename__ = "posts"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
title: Mapped[str] = mapped_column(String(300), unique=True, nullable=False)
description: Mapped[str] = mapped_column(String(250), nullable=False)
date: Mapped[str] = mapped_column(String(250), nullable=False)
body: Mapped[str] = mapped_column(Text, nullable=False)
author: Mapped[str] = mapped_column(String(250), nullable=False)

# OTHERS CODES BELOW


Step 3) Define the route that handles search functionality:



#main.py


# OTHER CODES ABOVE

# Handling search results
@app.route('/search', methods=['GET', 'POST'])
def search():
if request.method == 'POST':
query = request.form.get('query', '').strip() # Get query and strip whitespace

if query: # Check if query is not empty
results = search_results(query)
return render_template('search_results.html', query=query, results=results)
else:
# Show "Empty query" message if query is empty
return render_template('search_results.html', query='', results=None)

return render_template('search_results.html', query=None, results=None)


# OTHER CODES BELOW


Step 4) Display search results, including the search query and the results themselves, i.e. using the search_results.html:

#search_results.html



#search_results.html

{% from "bootstrap5/form.html" import render_form %} {% block content %} {%
include "header.html" %}

<main class="mb-4">
<div class="container">
<div class="row">

<h1>Search Results</h1>
<p>Searched for: {{ query }}</p>
<ul>
{% if results %}
{% for result in results %}
<a href="{{url_for('show_post', post_id=result.id)}}">
<li>

<strong>{{ result.title }}</strong>

</li>
</a>
{% endfor %}
{% else %}
<li>No results found or Search Query is Empty.</li>
{% endif %}
</ul>
<a href="/">Back to search</a>




</div>
</div>
</main>





{% include "footer.html" %} {% endblock %}


Step 5) Create the search form:



#sidebar.html

<div class="col-md-4">
<div class="position-sticky" style="top: 2rem;">
<!-- Search Bar Starts -->

<form action="/search" class="d-flex mb-5" role="search" method="post">
<input name="query" class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>

<!-- Search Bar Ends -->



<div>
<h4 class="fst-italic">Recent posts</h4>
<ul class="list-unstyled">
<li>
<a class="d-flex flex-column flex-lg-row gap-3 align-items-start align-items-lg-center py-3 link-body-emphasis text-decoration-none border-top" href="#">
<svg class="bd-placeholder-img" width="100%" height="96" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" preserveAspectRatio="xMidYMid slice" focusable="false"><rect width="100%" height="100%" fill="#777"></rect></svg>
<div class="col-lg-8">
<h6 class="mb-0">Example blog post title</h6>
<small class="text-body-secondary">January 15, 2023</small>
</div>
</a>
</li>
<li>
<a class="d-flex flex-column flex-lg-row gap-3 align-items-start align-items-lg-center py-3 link-body-emphasis text-decoration-none border-top" href="#">
<svg class="bd-placeholder-img" width="100%" height="96" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" preserveAspectRatio="xMidYMid slice" focusable="false"><rect width="100%" height="100%" fill="#777"></rect></svg>
<div class="col-lg-8">
<h6 class="mb-0">This is another blog post title</h6>
<small class="text-body-secondary">January 14, 2023</small>
</div>
</a>
</li>
<li>
<a class="d-flex flex-column flex-lg-row gap-3 align-items-start align-items-lg-center py-3 link-body-emphasis text-decoration-none border-top" href="#">
<svg class="bd-placeholder-img" width="100%" height="96" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" preserveAspectRatio="xMidYMid slice" focusable="false"><rect width="100%" height="100%" fill="#777"></rect></svg>
<div class="col-lg-8">
<h6 class="mb-0">Longer blog post title: This one has multiple lines!</h6>
<small class="text-body-secondary">January 13, 2023</small>
</div>
</a>
</li>
</ul>
</div>

<div class="p-4">
<h4 class="fst-italic">Archives</h4>
<ol class="list-unstyled mb-0">
<li><a href="#">March 2021</a></li>
<li><a href="#">February 2021</a></li>
<li><a href="#">January 2021</a></li>
<li><a href="#">December 2020</a></li>

</ol>
</div>

<div class="p-4 ">
<h4 class="fst-italic">Elsewhere</h4>
<ol class="list-unstyled">
<li><a href="#">GitHub</a></li>
<li><a href="#">Twitter</a></li>
<li><a href="#">Facebook</a></li>
</ol>
</div>
</div>
</div>


Step 6) Test your Search engine:

#when search is empty



#Output:


#Search for any thing:



#Output:


To create a search engine using Flask and Python, follow these six steps: import required libraries, develop search functionality, define a route for search requests, create a template for displaying search results, design and implement a search form, and test thoroughly.


Please let us know how this post helped you or if there is anything we missed. Your feedback is valuable.


"Thank you, and great coding!" 


Other Posts:


1) When should you use PostgreSQL over SQLite? 


2) What are the advantages and disadvantages of SQLite Compared to server-based database systems?


3) With an Example Fix: Database Configuration Postgresql Flask Example


4) SQLAlchemy Migrate vs Alembic vs Flask Migrate


5) Sqlalchemy-migrate vs Alembic 


6) Flask-migrate vs Alembic 


7) With an Example Fix: Flask Migrate is not Working in Sqlalchemy 


8) With an Example Fix: How To Delete Existing Migration Files Flask Python / Directory migrations already exists and is not empty


9) With an Example Fix: Sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) No Such Column:


10) Which is Better, SQLite or SQLAlchemy?