Tutorials

Python Elasticsearch Autocomplete Input Example Source Code

In this tutorial, you’ll learn how to create an autocomplete functionality for search engines. Just like Google or Bing has implemented on their websites.

The frontend is developed using Python Flask and HTML5 whereas the backend is powered by Elasticsearch.


Folder Structure

  • Backend
    • api.py
  • Frontend
    • templates
      • home.html
    • app.py

Backend/api.py

try:
    from flask import app,Flask
    from flask_restful import Resource, Api, reqparse
    import elasticsearch
    from elasticsearch import Elasticsearch
    import datetime
    import concurrent.futures
    import requests
    import json
except Exception as e:
    print("Modules Missing {}".format(e))


app = Flask(__name__)
api = Api(app)

#------------------------------------------------------------------------------------------------------------

NODE_NAME = 'myelkfirst'
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

#------------------------------------------------------------------------------------------------------------


"""
{
"wildcard": {
    "title": {
        "value": "{}*".format(self.query)
    }
}
}

"""


class Controller(Resource):
    def __init__(self):
        self.query = parser.parse_args().get("query", None)
        self.baseQuery ={
            "_source": [],
            "size": 0,
            "min_score": 0.5,
            "query": {
                "bool": {
                    "must": [
                        {
                            "match_phrase_prefix": {
                                "title": {
                                    "query": "{}".format(self.query)
                                }
                            }
                        }
                    ],
                    "filter": [],
                    "should": [],
                    "must_not": []
                }
            },
            "aggs": {
                "auto_complete": {
                    "terms": {
                        "field": "title.keyword",
                        "order": {
                            "_count": "desc"
                        },
                        "size": 25
                    }
                }
            }
        }

    def get(self):
        res = es.search(index=NODE_NAME, size=0, body=self.baseQuery)
        return res


parser = reqparse.RequestParser()
parser.add_argument("query", type=str, required=True, help="query parameter is Required ")

api.add_resource(Controller, '/autocomplete')


if __name__ == '__main__':
    app.run(debug=True, port=4000)

Frontend/templates/home.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>

    <title></title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>

<div style="height: 55vh;" class="jumbotron ui-widget">
    <h4 style="text-align: center;padding: 20px;">Search as you Type with Elastic Search</h4>
    <div style="position:absolute; left: 40%;top: 30%">
        <input id="source" />
        <div id="result"></div>
        <a >

Frontend/app.py

from flask import Flask
from flask import request,redirect,render_template,session
import requests
import base64
import requests

app = Flask(__name__)


@app.route('/', methods=["GET", "POST"])
def index():
    return render_template("home.html")


@app.route('/pipe', methods=["GET", "POST"])
def pipe():
    data = request.form.get("data")
    payload = {}
    headers= {}
    url = "http://127.0.0.1:4000/autocomplete?query="+str(data)
    response = requests.request("GET", url, headers=headers, data = payload)
    return response.json()



if __name__ == "__main__":
    app.run(debug=True, port=5000)
Furqan

Well. I've been working for the past three years as a web designer and developer. I have successfully created websites for small to medium sized companies as part of my freelance career. During that time I've also completed my bachelor's in Information Technology.

Recent Posts

Obsidian vs Notion (2026): I tested both for 6 months

If you have been searching for the right note-taking or knowledge management app, you have…

May 31, 2026

AnyType Alternatives: 10 Best Tools for Knowledge Management in 2026

Looking for AnyType alternatives? You're not alone. AnyType has gained popularity as a privacy-focused, local-first…

May 31, 2026

Notion Alternatives – Best Note-taking & Wiki Tools

Notion is a popular all-in-one workspace, but many users seek alternatives for different needs (free…

May 31, 2026

Best Logseq Alternatives in 2026: Find Your Perfect Knowledge Management Tool

Logseq is a beloved tool in the personal knowledge management (PKM) community. It's free, open-source,…

May 30, 2026

Webshare Alternatives: 8 Best Proxy Providers to Use in 2026

Looking for a Webshare alternative? You're not alone. Webshare is a popular proxy service with…

May 30, 2026

Docker Alternatives in 2026: The Complete Guide to Container Tools

Docker changed software development forever. It made containers accessible, gave developers a simple workflow, and…

May 30, 2026