Elasticsearch的安装
- 从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里的配置文件
Django操控搜索引擎Haystack的安装和配置
- pip安装第三方库
elasticsearch必须安装2.4.1,高版本报错
pip install django-haystack
pip install elasticsearch==2.4.1
- Haystack注册应用
INSTALLED_APPS = [
'haystack',
]
- setting配置
- HAYSTACK_SIGNAL_PROCESSOR配置项保证了在Django运行起来后,有新的数据产生时,Haystack仍然可以让Elasticsearch实时生成新数据的索引
# Haystack
HAYSTACK_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'
自定义索引类
- 必须继承indexes.SearchIndex, indexes.Indexable
from haystack import indexes
from apps.goods.models import SKU
class 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)
- 创建模板来指定text字段的索引
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)
- 视图内重写create_response方法后的代码
- 前端请求时搜索的关键字变量名必须为q='xxxx’才会搜索
返回列表时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)
- settings文件内配置返回数据分页
# 控制搜索结果的分页数量
HAYSTACK_SEARCH_RESULTS_PER_PAGE = 3