Windows OS env 上的 Django Haystack + ElasticSearch 实现

Django Haystack + ElasticSearch Implementation on Windows OS env

我正在使用 HayStack+ElasticSearch 开发一个搜索引擎项目,但我很难绕过它。我已经为模型设置了模型和 Inexing,如下所示:

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

项目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)

应用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',)

当我 运行 "manage.py rebuild_index" 使用以上所有设置时,我得到以下错误。

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)

请告知我是否做错了什么或一直做错了。

如果 ES 服务器没有响应,可能有以下几个原因:

  1. ES服务器未启动
  2. ES 服务器未配置为侦听本地主机或 127.0.0.1
  3. 根本没有安装ES服务器

在你的情况下,这是第三种选择。您只需要安装 Elasticsearch as explained in the Django Haystack docs,启动它,然后它就会工作。