1. 需求分析
當(dāng)用戶在搜索框輸入關(guān)鍵字后,我們要為用戶提供相關(guān)的搜索結(jié)果。
這種需求依賴數(shù)據(jù)庫的模糊查詢like關(guān)鍵字可以實現(xiàn),但是like關(guān)鍵字的效率極低,而且查詢需要在多個字段中進(jìn)行,使用like關(guān)鍵字也不方便。
我們引入搜索引擎來實現(xiàn)全文檢索。全文檢索即在指定的任意字段中進(jìn)行檢索查詢。
2. 搜索引擎原理
通過搜索引擎進(jìn)行數(shù)據(jù)查詢時,搜索引擎并不是直接在數(shù)據(jù)庫中進(jìn)行查詢,而是搜索引擎會對數(shù)據(jù)庫中的數(shù)據(jù)進(jìn)行一遍預(yù)處理,單獨建立起一份索引結(jié)構(gòu)數(shù)據(jù)。
我們可以將索引結(jié)構(gòu)數(shù)據(jù)想象成是字典書籍的索引檢索頁,里面包含了關(guān)鍵詞與詞條的對應(yīng)關(guān)系,并記錄詞條的位置。

我們在通過搜索引擎搜索時,搜索引擎將關(guān)鍵字在索引數(shù)據(jù)中進(jìn)行快速對比查找,進(jìn)而找到數(shù)據(jù)的真實存儲位置。
3. Elasticsearch
開源的 Elasticsearch 是目前全文搜索引擎的首選。
它可以快速地儲存、搜索和分析海量數(shù)據(jù)。維基百科、Stack Overflow、Github 都采用它。
Elasticsearch 的底層是開源庫 Lucene。但是,你沒法直接用 Lucene,必須自己寫代碼去調(diào)用它的接口。Elastic 是 Lucene 的封裝,提供了 REST API 的操作接口,開箱即用。
Elasticsearch 是用Java實現(xiàn)的。
搜索引擎在對數(shù)據(jù)構(gòu)建索引時,需要進(jìn)行分詞處理。分詞是指將一句話拆解成多個單字或詞,這些字或詞便是這句話的關(guān)鍵詞。如
我是中國人。
'我'、'是'、'中'、'國'、'人'、'中國'等都可以是這句話的關(guān)鍵詞。
Elasticsearch 不支持對中文進(jìn)行分詞建立索引,需要配合擴(kuò)展elasticsearch-analysis-ik來實現(xiàn)中文分詞處理。
4. 使用Docker安裝Elasticsearch及其擴(kuò)展
獲取鏡像,可以通過網(wǎng)絡(luò)pull
docker image pull delron/elasticsearch-ik:2.4.6-1.0
或者加載提供給大家的鏡像文件
docker load -i elasticsearch-ik-2.4.6_docker.tar
修改elasticsearch的配置文件 elasticsearc-2.4.6/config/elasticsearch.yml第54行,更改ip地址為本機(jī)ip地址
network.host: 10.211.55.5
創(chuàng)建docker容器運(yùn)行
docker run -dti --network=host --name=elasticsearch -v /home/python/elasticsearch-2.4.6/config:/usr/sh
5. 使用haystack對接Elasticsearch
Haystack為Django提供了模塊化的搜索。它的特點是統(tǒng)一的,熟悉的API,可以讓你在不修改代碼的情況下使用不同的搜索后端(比如 Solr, Elasticsearch, Whoosh, Xapian 等等)。
我們在django中可以通過使用haystack來調(diào)用Elasticsearch搜索引擎。
1)安裝
pip install drf-haystack
pip install elasticsearch==2.4.1
drf-haystack是為了在REST framework中使用haystack而進(jìn)行的封裝(如果在Django中使用haystack,則安裝django-haystack即可)。
2)注冊應(yīng)用
INSTALLED_APPS = [
...
'haystack',
...
]
3)配置
在配置文件中配置haystack使用的搜索引擎后端
# Haystack
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
'URL': 'http://10.211.55.5:9200/', # 此處為elasticsearch運(yùn)行的服務(wù)器ip地址,端口號固定為9200
'INDEX_NAME': 'meiduo', # 指定elasticsearch建立的索引庫的名稱
},
}
# 當(dāng)添加、修改、刪除數(shù)據(jù)時,自動生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
注意:
HAYSTACK_SIGNAL_PROCESSOR 的配置保證了在Django運(yùn)行起來后,有新的數(shù)據(jù)產(chǎn)生時,haystack仍然可以讓Elasticsearch實時生成新數(shù)據(jù)的索引
4)創(chuàng)建索引類
通過創(chuàng)建索引類,來指明讓搜索引擎對哪些字段建立索引,也就是可以通過哪些字段的關(guān)鍵字來檢索數(shù)據(jù)。
在應(yīng)用中新建search_indexes.py文件,用于存放索引類
from haystack import indexes
from .models import SKU
class SKUIndex(indexes.SearchIndex, indexes.Indexable):
"""
SKU索引數(shù)據(jù)模型類
"""
text = indexes.CharField(document=True, use_template=True)
id = indexes.IntegerField(model_attr='id')
name = indexes.CharField(model_attr='name')
price = indexes.DecimalField(model_attr='price')
default_image_url = indexes.CharField(model_attr='default_image_url')
comments = indexes.IntegerField(model_attr='comments')
def get_model(self):
"""返回建立索引的模型類"""
return SKU
def index_queryset(self, using=None):
"""返回要建立索引的數(shù)據(jù)查詢集"""
return self.get_model().objects.filter(is_launched=True)
在SKUIndex建立的字段,都可以借助haystack由elasticsearch搜索引擎查詢。
其中text字段我們聲明為document=True,表名該字段是主要進(jìn)行關(guān)鍵字查詢的字段, 該字段的索引值可以由多個數(shù)據(jù)庫模型類字段組成,具體由哪些模型類字段組成,我們用use_template=True表示后續(xù)通過模板來指明。其他字段都是通過model_attr選項指明引用數(shù)據(jù)庫模型類的特定字段。
在REST framework中,索引類的字段會作為查詢結(jié)果返回數(shù)據(jù)的來源。
6)在templates目錄中創(chuàng)建text字段使用的模板文件
具體在templates/search/indexes/goods/sku_text.txt文件中定義
{{ object.name }}
{{ object.caption }}
{{ object.id }}
此模板指明當(dāng)將關(guān)鍵詞通過text參數(shù)名傳遞時,可以通過sku的name、caption、id來進(jìn)行關(guān)鍵字索引查詢。
7)手動生成初始索引
python manage.py rebuild_index
8)創(chuàng)建序列化器
在serializers.py中創(chuàng)建haystack序列化器
from drf_haystack.serializers import HaystackSerializer
class SKUIndexSerializer(HaystackSerializer):
"""
SKU索引結(jié)果數(shù)據(jù)序列化器
"""
class Meta:
index_classes = [SKUIndex]
fields = ('text', 'id', 'name', 'price', 'default_image_url', 'comments')
注意fields屬性的字段名與SKUIndex類的字段對應(yīng)。
9)創(chuàng)建視圖
在views.py中創(chuàng)建視圖
from drf_haystack.viewsets import HaystackViewSet
class SKUSearchViewSet(HaystackViewSet):
"""
SKU搜索
"""
index_models = [SKU]
serializer_class = SKUIndexSerializer
注意:
- 該視圖會返回搜索結(jié)果的列表數(shù)據(jù),所以如果可以為視圖增加REST framework的分頁功能。
- 我們在實現(xiàn)商品列表頁面時已經(jīng)定義了全局的分頁配置,所以此搜索視圖會使用全局的分頁配置。
10)定義路由
通過REST framework的router來定義路由
router = DefaultRouter()
router.register('skus/search', views.SKUSearchViewSet, base_name='skus_search')
...
urlpatterns += router.urls
11)測試
我們可以GET方法訪問如下鏈接進(jìn)行測試
http://api.meiduo.site:8000/skus/search/?text=wifi
http://api.meiduo.site:8000/skus/search/?id=1
http://api.meiduo.site:8000/skus/search/?name=iphone
bug說明:
如果在配置完haystack并啟動程序后,出現(xiàn)如下異常,是因為drf-haystack還沒有適配最新版本的REST framework框架

可以通過修改REST framework框架代碼,補(bǔ)充_get_count函數(shù)定義即可
文件路徑 虛擬環(huán)境下的 lib/python3.6/sitepackages/rest_framework/pagination.py
def _get_count(queryset):
"""
Determine an object count, supporting either querysets or regular lists.
"""
try:
return queryset.count()
except (AttributeError, TypeError):
return len(queryset)