django - Windows OS上的Django Haystack + ElasticSearch实现

标签 django python-2.7 elasticsearch django-haystack

我正在用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服务器没有响应,则可能是由于以下几个原因:

  • ES服务器未启动
  • ES服务器未配置为在localhost或127.0.0.1上侦听
  • 根本没有安装ES服务器。

  • 就您而言,这是第三个选择。您只需要安装Elasticsearch as explained in the Django Haystack docs,然后启动它就可以了。

    关于django - Windows OS上的Django Haystack + ElasticSearch实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37292561/

    相关文章:

    html - 静态文件更改未反射(reflect)在提供的样式表中

    python - 在 Windows 中安装 eyed3

    java - 如何使用 JAVA 高级 REST 客户端创建 Elasticsearch 索引?

    python - AttributeError 'UserViewset' 对象没有属性 'action'

    python - Django 子域 URL 调度

    python - 没有函数与给定名称和参数类型匹配 - PGCrypto

    python - 无法在 Python 中导入 urllib

    python - 在 Python 2.7 中使用 Ruffus 库,just_print 标志失败

    ElasticSearch post_filter 和过滤聚合的行为不同

    json - 创建或更新索引时 `type`不更新