本文共 3281 字,大约阅读时间需要 10 分钟。
从docker的仓库中拉取镜像
sudo docker image pull delron/elasticsearch-ik:2.4.6-1.0
修改elasticsearch-2.4.6的配置文件
elasticsearch-2.4.6.zip去官方下载
retwork.host: 修改为本机ip地址 运行搜索引擎服务器
sudo docker run -dti --name=elasticsearch --network=host -v /home/ubuntu/Desktop/elasticsearch-2.4.6/config:/usr/share/elasticsearch/config delron/elasticsearch-ik:2.4.6-1.0-dti 守护进程运行--name 容器名字--network=host 设置运行在本机ip/home/ubuntu/Desktop/elasticsearch-2.4.6/config 映射到本机的配置文件:/usr/share/elasticsearch/config 在docker里的配置文件
pip安装第三方库
elasticsearch必须安装2.4.1,高版本报错
pip install django-haystack pip install elasticsearch==2.4.1
Haystack注册应用
INSTALLED_APPS = [ 'haystack',]
settings配置
# HaystackHAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://开启搜索引擎服务的ip:9200/', # Elasticsearch服务器ip地址,端口号固定为9200 'INDEX_NAME': 'meiduo_mall', # Elasticsearch建立的索引库的名称 },}# 当添加、修改、删除数据时,自动生成索引# HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
from haystack import indexesfrom apps.goods.models import SKUclass SKUIndex(indexes.SearchIndex, indexes.Indexable): # document=True 代表该字段主要进行关键字查询 # # use_template=True代表,`text`字段的索引值可以由多个数据库模型类字段组成, # 具体由哪些模型类字段组成,我们用`use_template=True`表示后续通过模板来指明。 text = indexes.CharField(document=True, use_template=True) # 重写get_model方法 返回要查询数据库哪个表 def get_model(self): return SKU # filter过滤条件 已上架的商品 def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.filter(is_launched=True)
id、name、caption为索引
{ { object.id }}{ { object.name }}{ { object.caption }}
运行命令生成索引
python manage.py rebuild_index
注意这个MySearchView类没有继承View而是继承的SearchView没有as_view()方法
查看源代码SearchView有__call__方法 直接调用对象就可以
数据格式
data_list = [
{‘id’:商品id}, {‘name’:商品name}, {‘price’:商品price}, {‘default_image_url’:商品图片路径}, ]视图必须继承SearchView
重写create_response方法
方法源代码
def create_response(self): """ Generates the actual HttpResponse to send back to the user. """ # context为数据集 context = self.get_context() return render(self.request, self.template, context)
返回列表时safe设为False 返回字典时设置为True
遍历context['page'].object_list获取到数据集对象,数据集对象.object.数据库内字段可以获取到数据
注意!object没有S!!
class MySearchView(SearchView): def create_response(self): context = self.get_context() data_list = [] for sku in context['page'].object_list: data_list.append({ 'id': sku.object.id, 'name': sku.object.name, 'price': sku.object.price, 'default_image_url': sku.object.default_image.url, 'searchkey': context.get('query'), 'page_size': context['page'].paginator.num_pages, 'count': context['page'].paginator.count, }) return JsonResponse(data_list, safe=False)
# 控制搜索结果的分页数量HAYSTACK_SEARCH_RESULTS_PER_PAGE = 3
转载地址:http://cquhf.baihongyu.com/