Django Haystack and Elasticsearch

Hello! Today blog post is about Django Haystack and how to integrate it quickly with Elasticsearch.

First after creating django project (At beginning of 2016 django-haystack don’t work properly with django 1.9 so I used 1.8.9 version) and making new app let’s add models:

from django.db import models

    ('Male', 'Male'),
    ('Female', 'Female')

class Person(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES)
    email = models.CharField(max_length=100)
    ip_address = models.CharField(max_length=100)

    def __str__(self):
        return '{first_name} {last_name}'.format(first_name=self.first_name, last_name=self.last_name)

And register model to the admin site. Don’t forget about adding created app to and making makemigrations and migrate after it:

from django.contrib import admin

from .models import Person

Then create simple script wich will load a data from JSON to the database. This JSON data is randomly generated data from this webpage. Call it and place in your django application folder.

# coding=utf-8
import os
import json

from .models import Person

DATA_FILE = os.path.join(

def run(verbose=True):
with open(DATA_FILE) as data_file:
    data = json.load(data_file)
    for record in data:

This script looks for file MOCK_DATA.json. Then based on fields on this JSON loads data to the django application. You can run this by shell and then:

>>> from django_app import load
{'ip_address': '', 'gender': 'Female', 'first_name': 'Christine', 'last_name': 'Cunningham', 'email': ''}
{'ip_address': '', 'gender': 'Male', 'first_name': 'Scott', 'last_name': 'Hanson', 'email': ''}
# rest of the records

Now it’s time to install and elasticsearch. On ubuntu you can do it as follows:

1.First install java-8

$ sudo apt-get install python-software-properties -y
$ sudo add-apt-repository ppa:webupd8team/java -y
$ sudo apt-get update
$ sudo apt-get install oracle-java8-installer -y

2.Verify if it’s properly installed

$ java -version
java version "1.8.0_72"
Java(TM) SE Runtime Environment (build 1.8.0_72-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.72-b15, mixed mode)

3.Now install elasticsearch itself

$ wget -qO - | sudo apt-key add -
$ echo "deb stable main" | sudo tee -a /etc/apt/sources.list.d/elk.list
$ sudo apt-get update && sudo apt-get install elasticsearch -y
$ sudo service elasticsearch start

4.Verify if elasticsearch is running

$ curl http://localhost:9200
  "status" : 200,
  "name" : "May \"Mayday\" Parker",
  "cluster_name" : "elasticsearch",
  "version" : {
    "number" : "1.7.5",
    "build_hash" : "00f95f4ffca6de89d68b7ccaf80d148f1f70e4d4",
    "build_timestamp" : "2016-02-02T09:55:30Z",
    "build_snapshot" : false,
    "lucene_version" : "4.10.4"
  "tagline" : "You Know, for Search"

Now it’s time to install to more python packages:

$ pip install django-haystack==2.4.1
$ pip install elasticsearch

After adding them to INSTALLED_APPS:


and setup up connection in

    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': 'localhost:9200',
        'INDEX_NAME': 'haystack',

Create file called in your django application folder (django_project/django_app/

from haystack import indexes

from .models import Person

class PersonIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    first_name = indexes.CharField(model_attr='first_name')
    last_name = indexes.CharField(model_attr='last_name')
    gender = indexes.CharField(model_attr='gender')
    email = indexes.CharField(model_attr='email')
    ip_address = indexes.CharField(model_attr='ip_address')

    def get_model(self):
        return Person

In this file we declare indexes with will be created in elasticsearch. The first field text indicates which field is primary to be searched within. This field can be named wherever you wanted but the convention is to name it text. There is only one field in each index with document=True argument. Another argument use_template=True tells haystack to use a template for building document for an index. This document is usually located under django_project/templates/search/indexes/django_app/index_name.txt. And for this data looks like this:

{{ object.title }}
{{ object.first_name }}
{{ object.last_name }}
{{ object.gender }}
{{ }}
{{ object.ip_address }}

Don’t forget to add this django_project/templates/ to TEMPLATES in

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates/'),],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [

After this add haystack.urls to

urlpatterns = [
    url(r'^search/', include('haystack.urls'))

Now it’s time to create search.html in django_project/templates/search/search.html:

{% extends 'base.html' %}

{% block content %}

<h2>Person search</h2>

    <form method="get" action="." class="form" role="form">
        {{ form.non_field_errors }}
        <div class="form-group">
                {{ form.as_p }}
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="Search">

        {% if query %}
            <table class="table table-striped table-bordered" cellspacing="0" id='result_table'>
                        <th>First name</th>
                        <th>Last name</th>
                        <th>IP address</th>
                    {% for result in page.object_list %}
                            <td>{{ result.first_name }}</td>
                            <td>{{ result.last_name }}</td>
                            <td>{{ result.gender }}</td>
                            <td>{{ }}</td>
                            <td>{{ result.ip_address}}</td>
                    {% empty %}
                        <tr>No results found.</tr>
                    {% endfor %}
        {% endif %}
{% endblock content %}

{% block extrajs %}
$(document).ready(function() {
        "searching": false
} );
{% endblock %}

This is basic template for searching. I added DataTable for better appearance.

Before we can search let’s rebuild the indexes by:

$ ./ rebuild_index

Now try to search something in elasticsearch itself to see if the documents are there:

$ curl -XGET http://localhost:9200/haystack/_search?pretty=true&q=first_name:Scott
"took" : 3,
 "timed_out" : false,
 "_shards" : {
   "total" : 5,
   "successful" : 5,
   "failed" : 0
 "hits" : {
   "total" : 1000,
   "max_score" : 1.0,
   "hits" : [ {
     "_index" : "haystack",
     "_type" : "modelresult",
     "_id" : "persons.person.1",
     "_score" : 1.0,
     "_source":{"django_ct": "persons.person", "last_name": "Harrison", "ip_address": "", "email": "", "first_name": "Russell", "gender": "Male", "text": "\nRussell\nHarrison\nMale\\n38.84.45.160\n", "id": "persons.person.1", "django_id": "1"}
   # rest of results here...

And that’s all. We got working search! You can find the repo on github. If you feel that this post was valuable please send me email. Thanks!


  1. django-haystack docs
  2. this gist