1. 程式人生 > 實用技巧 >ubuntu下安裝docker django使用whoosh搜尋引擎 使用es(elasticsearch)代替whoosh

ubuntu下安裝docker django使用whoosh搜尋引擎 使用es(elasticsearch)代替whoosh

1.docker基本原理

https://www.cnblogs.com/xiaonq/p/10241045.html

2.ubuntu安裝docker

2.1 安裝docker

# 1.解除安裝舊版本
sudo apt-get remove docker docker-engine docker.io containerd runc

# 2.更新ubuntu的apt源索引
# 修改apt國內源為中科大源
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
sudo sed -i 's/archive.ubuntu.com/mirrors.ustc.edu.cn/' /etc/apt/sources.list
sudo apt update

#3.安裝包允許apt通過HTTPS使用倉庫
sudo apt-get install \
    apt-transport-https \
    ca-certificates \
    curl \
    software-properties-common

#4.新增Docker官方GPG key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

#5.設定Docker穩定版倉庫
#5.1 設定使用官方,很慢
sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"
#5.2 設定使用阿里雲
add-apt-repository "deb [arch=amd64] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable"
    
#6.新增倉庫後,更新apt源索引
sudo apt-get update

#7.安裝最新版Docker CE(社群版)
sudo apt-get install docker-ce

#8.檢查Docker CE是否安裝正確
sudo docker run hello-world

2.2 docker預設是國外源可以設定成國內映象源

root@linux-node1 django-docker]# vim /etc/docker/daemon.json    # 設定docker映象源
{
    "registry-mirrors": ["http://hub-mirror.c.163.com"]
}
或者
{
    "registry-mirrors": ["https://docker.mirrors.ustc.edu.cn"]
}

[root@linux-node2 ~]# systemctl daemon-reload                   # 過載檔案
[root@linux-node2 ~]# systemctl restart docker                  # 重啟docker生效

2.3 docker啟動設定

# 啟動Docker服務並設定開機啟動
systemctl start docker
systemctl enable docker

2.4 docker簡單使用(建立一個ngixn容器)

# 1、建立一個nginx容器
 docker run -it nginx
 
 # 2、檢視docker執行的容器(可以獲取到這個容器的id)
 docker ps
 
 # 3、訪問這個容器
 # 進入這個nginx容器(進入的檔案系統和宿主機是完全隔離的,有自己獨立的檔案系統)
 docker exec -it 73877e65c07d bash
 
 # 4、檢視當前容器的 IP
 docker inspect 73877e65c07d   # 73877e65c07d是通過docekr ps檢視到的容器ID
 curl 172.17.0.2               # 測試這個nginx容器是否可以訪問

基本介紹

  1. 前後端不分離:https://www.cnblogs.com/xiaonq/p/12363589.html

    1. 安裝

      1. pip install drf-haystack # django的開源 搜尋框架(python語音寫的,搜尋框架可以使用其他
        語音的搜尋引擎)
        pip install whoosh # 搜尋引擎(python語音寫的)
        pip install jieba # 中文分詞Jieba,由於Whoosh自帶的是英文分詞,對中文的分詞支援
        不是太好
        
    2. 什麼是haystack?

      • haystack是django的開源搜尋框架,該框架支援 Solr,Elasticsearch,Whoosh, Xapian 搜尋引 擎,不用更改程式碼,直接切換引擎,減少程式碼量。
      • 搜尋引擎使用Whoosh,這是一個由純Python實現的全文搜尋引擎,沒有二進位制檔案等,比較小 巧,配置比較簡單,當然效能自然略低。
      • 中文分詞Jieba,由於Whoosh自帶的是英文分詞,對中文的分詞支援不是太好,故用jieba替換 whoosh的分片語件。
    3. 配置使用

      1. syl/settings.py 全文檢索配置

      2. '''1.註冊app '''
        INSTALLED_APPS = [
        'haystack', # haystack要放在應用的上面
        ]
        '''2.模板路徑 '''
        TEMPLATES = [
        {
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        },
        ]
        
        
        '''3.全文檢索配置'''
        HAYSTACK_SEARCH_RESULTS_PER_PAGE = 15  # 搜尋出多條資料時需要分頁
        HAYSTACK_CONNECTIONS = {
            'default': {
                # 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
                'ENGINE': 'course.whoosh_cn_backend.MyWhooshEngine',
                'PATH': os.path.join(BASE_DIR, 'whoosh_index'),  # 指定倒排索引存放位置
            },
        }
        
        # ES引擎
        # settings.py 修改haystack配置
        # ES引擎
        # HAYSTACK_CONNECTIONS = {
        #     'default': {
        #         'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        #         'URL': 'http://127.0.0.1:9200/',  # Elasticsearch伺服器ip地址,埠號固定為9200
        #         'INDEX_NAME': 'syl',  # Elasticsearch建立的反向索引庫的名稱
        #     },
        # }
        # 新增此項,當資料庫改變時,會自動更新索引,非常方便
        HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
        
        
      3. 在子應用下建立索引檔案

        1. apps/course/search_indexes.py

        2. """
          author:翔翔
          date:
          use:
          """
          # apps/course/search_indexes.py
          # 檔名必須是 search_indexes.py
          from haystack import indexes
          from .models import Course
          # 修改此處,類名為模型類的名稱+Index,比如模型類為GoodsInfo,則這裡類名為GoodsInfoIndex(其實可以隨便寫)
          class CourseIndex(indexes.SearchIndex, indexes.Indexable):
              """
              Course索引類
              """
              # text為索引欄位
              # document = True,這代表haystack和搜尋引擎將使用此欄位的內容作為索引進行檢索
              # use_template=True 指定根據表中的那些欄位建立索引檔案的說明放在一個檔案中
              text = indexes.CharField(document=True, use_template=True)
              # 對那張表進行查詢
              def get_model(self): # 過載get_model方法,必須要有
                  """返回建立索引的模型類"""
                  return Course # 返回這個model
              # 建立索引的資料
              def index_queryset(self, using=None):
                  """返回要建立索引的資料查詢集"""
                  # 這個方法返回什麼內容,最終就會對那些方法建立索引,這裡是對所有欄位建立索引
                  return self.get_model().objects.all()
          
      4. 指定索引模板檔案

        1. templates/search/indexes/course/course_text.txt
          
        2. # 建立檔案路徑命名必須這個規範:templates/search/indexes/應用名稱/模型類名稱
          _text.txt
          
        3. {{object.id}}
          {{object.title}}
          {{object.desc}}
          
      5. apps/course/whoosh_cn_backend.py

        1. """
          author:翔翔
          date:
          use:
          """
          # 更換 text 欄位的 分析方式, 變為jieba分詞中的中文分析器
          from haystack.backends.whoosh_backend import WhooshEngine, WhooshSearchBackend
          from whoosh.fields import TEXT
          from jieba.analyse import ChineseAnalyzer
          
          
          class MyWhooshSearchBackend(WhooshSearchBackend):
              def build_schema(self, fields):
                  (content_field_name, schema) = super().build_schema(fields)
                  # 指定whoosh使用jieba進行分詞
                  schema._fields['text'] = TEXT(stored=True,
                                                analyzer=ChineseAnalyzer(),
                                                field_boost=fields.get('text').boost,
                                                sortable=True)
                  return (content_field_name, schema)
          
          
          class MyWhooshEngine(WhooshEngine):
              backend = MyWhooshSearchBackend
          
          
      6. 課程全文檢索介面檢視函式

        1. course/views.py

        2. 
          from syl import settings
          from django.core.paginator import InvalidPage, Paginator
          from haystack.forms import ModelSearchForm
          from django.http import JsonResponse,HttpResponse
          
          # 如果settings.py中配置就是用settings中配置的,否則就每頁15條
          RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 15)
          
          
          def course_index_search(request):
              # 1.獲取前端傳過來的關鍵字(查詢資料)
              query = request.GET.get('q', None)
              page = int(request.GET.get('page', 1))  # 第幾頁
              page_size = int(request.GET.get('page_size', RESULTS_PER_PAGE))  # 每頁多少條
              # 2.獲取查詢條件,進行查詢
              if query:
                  form = ModelSearchForm(request.GET, load_all=True)  # 將查詢條件傳遞給查詢對 象
                  if form.is_valid():
                      results = form.search()  # 查詢出來的最終資料
                  else:
                      results = []
              else:
                  return JsonResponse({"code": 404, "msg": 'No file found!', "data": []})
              # 3.對結果集進行分頁
              paginator = Paginator(results, page_size)
              try:
                  page = paginator.page(page)  # 從分好的頁中拿第幾頁
              except InvalidPage:  # 如果分頁出錯
                  return JsonResponse({"code": 404, "msg": 'No file found!', "data": []})
              # 4.把查詢的分頁結果集物件轉換成json格式
              jsondata = []
              for result in page.object_list:  # 分頁後的課程查詢結果
                  data = {
                      'id': result.object.id,
                      'title': result.object.title,
                      'desc': result.object.desc,
                      'img':
                          request.scheme + '://' + request.META['HTTP_HOST'] + result.object.img.url,
                      # 'follower': result.object.follower,
                      'learner': result.object.learner,
                      'status': result.object.status,
                      'course_type': result.object.course_type.id
                  }
                  jsondata.append(data)
              result = {
                  "code": 200,
                  "msg": 'Search successfully!',
                  "data": {"count": page.paginator.count, "results": jsondata}
              }
              # return JsonResponse(result)
              return HttpResponse(json.dumps(result, ensure_ascii=False))
          
          
      7. syl/urls.py 新增路由

        1. urlpatterns = [
          	path('search/', course_index_search),
          ]
          
      8. 命令構建倒排索引

        1. python manage.py rebuild_index
          
      9. 測試課程全文檢索

        1. 測試介面

        2. http://192.168.56.100:8888/search/?q=測試&page=1&page_size=1
          
        3. 測試結果

        4. ![image-20201112212145036](C:\Users\wyx\Desktop\小實訓\day14 全文檢索kounch es docker安裝 docker拉取es映象\圖片\image-20201112212145036.png)

        5. 返回結果
          
          {
          "code": 200,
          "msg": "Search successfully!",
          "data": {
          "count": 1,
          "results": [
          {
          "id": 1,
          "title": "Linux入門課程",
          "desc": "要在實驗樓愉快地學習,先要熟練地使用 Linux,本實驗介紹 Linux 基
          本操作,shell 環境下的常用命令。",
          "img": "http://192.168.56.100:8888/media/course/linux.jpg",
          "learner": 222,
          "status": "1",
          "course_type": 3
          }
          ]
          }
          

1.docker安裝ES

  • 1.拉取docker映象
# 從倉庫拉取映象
sudo docker image pull delron/elasticsearch-ik:2.4.6-1.0
  • 2.使用docker安裝ES
docker run -d -p 9200:9200 -p 9300:9300 --name elasticsearch delron/elasticsearch-ik:2.4.6-1.0
  • 3.在頁面中測試
http://192.168.56.100:9200/
報錯安裝  pip install elasticsearch

2.使用ES替代whoosh全文檢索

# settings.py  修改haystack配置
# ES引擎
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': 'http://127.0.0.1:9200/',        # Elasticsearch伺服器ip地址,埠號固定為9200
        'INDEX_NAME': 'syl',                    # Elasticsearch建立的反向索引庫的名稱
    },
}