Implement search with Django-haystack and Elasticsearch Part-I

Haystack works as a search plugin for Django. You can use different backends Elastic-search, Whose, Sorl, Xapian to search objects. All backends work with the same code. In this post, I am using elastic search as backend.

Installation:

Configuration:

add haystack to installed apps

Settings:

Add back-end settings for the haystack.

Above settings for elastic search.

Add signal processor for the haystack. This signal will update objects in an index.

For This tutorial, I am using below as a model.

books/models.py:

SearchIndex:

The purpose of indexing objects is to optimize speed and performance in finding relevant documents for a given search query.
With search index haystack determines what data should be placed in the index. In haystack, you write a unique index for each model.

create a new file in books/search_indexes.py below code goes

search index will be created by subclassing both haystack.Indexes.SearchIndex and haystack.Indexes.Indexable. Specify index field types by indexes field types(similar to models).

in above index class get_model method used to define a model which you want to create indexes. prepare_fieldname method used to define data for indexing.

Haystack will use a template to index data. these index syntaxes are similar to Django template tags.

templates/search/book_text.txt

Setup:

urls.py

build index:

search query form.

input field q is mandatory for searching.

Display search results:

belove code goes in templates/search/search.html

Got error or want to give suggestions please comment below. Happy Coding.

The article was originally published at MicroPyramid blog.

Python, Django, Android and IOS, reactjs, react-native, AWS, Salesforce consulting & development company