使用haystack,Elasticsearch實現商品搜索流程
from Mp
ps: 本文章意在自己練手時運用搜索功能蒙袍,docker正常不會這么用(怕誤導人嘻嘻嘻)
從線上獲取鏡像
docker image pull delron/elasticsearch-ik:2.4.6-1.0
修改提供的elasticsearc-2.4.6壓縮包內config的.yml文件內容
network.host: 自己機器的IP地址
創(chuàng)建docker容器運行
/home/python/Desktop/elasticsearch-2.4.6/config 為配置文件路徑
docker run -dti --network=host --name=elasticsearch -v /home/python/Desktop/elasticsearch-2.4.6/config:/usr/share/elasticsearch/config delron/elasticsearch-ik:2.4.6-1.0
使用haystack對接Elasticsearch
安裝haystack
pip install drf-haystack
pip install elasticsearch==2.4.1
配置
INSTALLED_APPS = [
...
'haystack',
]
# 配置Haystack搜索引擎后端
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
# 端口號固定為9200
'URL': 'http://192.168.188.136:9200/',
# 指定elasticsearch建立的索引庫的名稱
'INDEX_NAME': 'md_mall',
},
}
# 當添加俊卤、修改、刪除數據時害幅,自動生成索引 es自動重建索引
# 保證了在Django運行起來后消恍,有新的數據產生時,haystack仍然可以讓Elasticsearch實時生成新數據的索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
模板文件
# 在模板中指定搜索列
templates/search/indexes/模型類名稱/模型類小寫_text.txt
# 內容
{{ object.name }}
{{ object.caption }}
索引類
# 新建search_indexes.py文件
from haystack import indexes
# 繼承可改
from .models import 被搜索的模型類
# 被搜索引擎建立索引的字段索引類
# 類名可改為:xxxxIndex
class XxxxIndex(indexes.SearchIndex, indexes.Indexable):
"""xxxx索引數據模型類"""
# document=True: 表名該字段是主要進行關鍵字查詢的字段
# use_template=True: 表示通過模板來指明模型類字段
# 在模板中指定搜索列 templates/search/indexes/模型類名稱/模型類小寫_text.txt
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
"""返回建立索引的模型類"""
# 模型類可改
return 模型類
def index_queryset(self, using=None):
"""返回建立索引的數據查詢集"""
# is_launched 是否上架出售
# 查詢條件可修改
return self.get_model().objects.filter(is_launched=True)
序列化器
from .search_indexes import XxxxIndex
class XxxxIndexSerializer(HaystackSerializer):
"""
索引結果序列化器
檢查前端傳入的參數text以现,并且檢索出數據后再使用這個序列化器返回給前端
"""
# 向前端返回數據時序列化的字段
# Haystack通過Elasticsearch檢索出搜索結果后狠怨,
# 會在數據庫中取出完整的數據庫模型類對象,放到object中
# 序列化器可改
object = xxxxSerializer(read_only=True)
class Meta:
# 索引類名稱可改
index_classes = [XxxxIndex]
fields = (
'text', # 用于接收查詢關鍵字
'object' # 用于返回查詢結果
)
創(chuàng)建視圖集
class XxxxSearchViewSet(HaystackViewSet):
"""Xxxx搜索"""
# 模型類可改
index_models = [Xxxx]
serializer_class = XxxxIndexSerializer
# 分頁
pagination_class = XxxxListPagination
手動生成初始索引
python manage.py rebuild_index
定義路由
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('定義的路徑', views.XxxxSearchViewSet, base_name='xxxx_search')
urlpatterns += router.urls