Search code examples
djangopython-2.7elasticsearchdjango-haystack

Django Haystack + ElasticSearch Implementation on Windows OS env


I am developing a project with HayStack+ElasticSearch for search engine and I am having hard time to get around it. I've setup models and Inexing for the models as shown below:

models.py:

from django.db import models
from django.core.urlresolvers import reverse

class Product(models.Model):
    title = models.CharField(max_length=500)
    description = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to='products/')
    price = models.DecimalField(max_digits=20, decimal_places=2)
    sku = models.CharField(null=True, max_length=100)
    url = models.URLField(blank=True)
    displayed_category = models.CharField(null=True, max_length=500)
    categories = models.ManyToManyField('Category', blank=True)
    default = models.ForeignKey(
        'Category', related_name='default_category', null=True, blank=True
    )

    def __unicode__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("product_detail", kwargs={"pk": self.pk})


class Category(models.Model):
    title = models.CharField(max_length=120, unique=True)
    slug = models.SlugField(unique=True)
    description = models.TextField(null=True, blank=True)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    def __unicode__(self):
        return self.title

Views.py:

from datetime import date
from .models import Product
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.core.paginator import Paginator
from haystack.generic_views import SearchView


class ProductListView(ListView):
    model = Product
    paginate_by = 10



class ProductDetailView(DetailView):
    model = Product

class ProductSearchView(SearchView):
    model = Product
    def get_queryset(self):
        queryset = super(ProductSearchView, self).get_queryset()
        # further filter queryset based on some set of criteria
        return queryset

    def get_context_data(self, *args, **kwargs):
        context = super(ProductSearchView, self).get_context_data(*args, **kwargs)
        context["query"] = self.request.GET.get("q")
        return context

search_index.py:

from haystack import indexes
from .models import Product


class TweetIndex(indexes.SearchIndex, indexes.Indexable):
    title = indexes.CharField(model_attr='title')
    text = indexes.EdgeNgramField(model_attr='text', document=True, use_template=True)

    def prepare_title(self, obj):
        return obj.title or ''

    def get_model(self):
        return Product

Project urls.py:

from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from products.views import ProductSearchView

urlpatterns = [
    url(r'^$', 'shopsy.views.home', name='home'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^products/', include('products.urls')),
    url(r'^search/', ProductSearchView.as_view()),
    url(r'search/$', include('haystack.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

App urls.py:

from django.conf.urls import url
from .views import ProductListView, ProductDetailView, ProductSearchView

urlpatterns = [
    url(r'^$', ProductListView.as_view(), name='products'),
    url(r'^(?P<pk>\d+)/$', ProductDetailView.as_view(), name='product_detail'),

]

settings.py:

HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': 'http://127.0.0.1:9200/',
        'INDEX_NAME': 'haystack',
    },

}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
INTERNAL_IPS = ('127.0.0.1',)

With all the above settings when I run "manage.py rebuild_index" I get the following error.

Removing all documents from your index because you said so.
Failed to clear Elasticsearch index: ConnectionError(<urllib3.connection.HTTPCon
nection object at 0x03C12850>: Failed to establish a new connection: [Errno 1006
1] No connection could be made because the target machine actively refused it) c
aused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x03C1
2850>: Failed to establish a new connection: [Errno 10061] No connection could b
e made because the target machine actively refused it)
Traceback (most recent call last):
  File "C:\Users\Shazia\Desktop\working directtory\searchEngin\lib\site-packa
ges\haystack\backends\elasticsearch_backend.py", line 234, in clear
    self.conn.indices.delete(index=self.index_name, ignore=404)
  File "C:\Users\Shazia\Desktop\working directtory\searchEngin\lib\site-packa
ges\elasticsearch\client\utils.py", line 69, in _wrapped
    return func(*args, params=params, **kwargs)
  File "C:\Users\Shazia\Desktop\working directtory\searchEngin\lib\site-packa
ges\elasticsearch\client\indices.py", line 198, in delete
    params=params)

Please advise if I am doing something or all the way wrong.


Solution

  • If the ES server is not responding it could be for several reasons:

    1. The ES server is not started
    2. The ES server is not configured to listen on localhost or 127.0.0.1
    3. The ES server is not installed at all.

    In your case, it was the third option. You just need to install Elasticsearch as explained in the Django Haystack docs, start it and then it will work.