我使用python 2.7.11和djnago 1.10.2。我创建了产品模型,并在数据库中保存了1000个产品。(Postgrelsql)实际上,我使用Django elasticsearch,但它不起作用。它的搜索仅基于产品名称,如果搜索类别、颜色等,我要求显示相关产品。我试过例子。
from haystack import indexes
from product.models import Product
class ProductIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
product_name = indexes.CharField(model_attr='product_name')
product_colour = indexes.CharField(model_attr='product_colour')
def get_model(self):
return Product
def index_queryset(self, using=None):
return self.get_model().objects.all() 我创建了ProductColour模型,并在产品moedls中使用了product_colour外键。如果我搜索product_colour,然后显示所有发布的数据。
以下几个步骤:-
发布于 2017-02-02 07:07:23
我使用Django elasticsearch,但它不起作用。
根据您的干草堆设置,您没有使用Elasticsearch。您正在使用的SimpleEngine,这根本不是真正的搜索引擎。要使用Elasticsearch,您的设置必须包含以下内容:
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://127.0.0.1:9200/',
'INDEX_NAME': 'haystack',
},
}请注意,干草不是搜索引擎本身。它只是一个在django应用程序中使用多个搜索引擎的工具。你已经已安装的弹性搜索了吗?
目前,我猜它不能工作,因为SimpleEngine不能正确地处理您的Many2ManyField。
在您的ProductIndex中,您将product_colour定义为CharField。但是您从ProductColour模型中引用了整个相关的模型实例。使用MultiValueField执行以下操作:
from haystack import indexes
from product.models import Product
class ProductIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
product_name = indexes.CharField(model_attr='product_name')
# use a MultiValueField for your m2m relation
product_colours = indexes.MultiValueField()
# define this method that returns all the values for your product_colours index field
# it must be called "prepare_{your field name}"
def prepare_product_colours(self, object):
return [colour.name for color in object.product_colour.all()]然后,您将需要一个搜索索引模板,在该模板中,text字段的内容将生成如干草堆文档中所述。
https://stackoverflow.com/questions/41980467
复制相似问题