1. 程式人生 > 實用技巧 >nested exception is java.lang.IllegalStateException: Ambiguous mapping. 巢狀的異常是java.lang.IllegalStateException:模稜兩可的對映。

nested exception is java.lang.IllegalStateException: Ambiguous mapping. 巢狀的異常是java.lang.IllegalStateException:模稜兩可的對映。

1.基本介紹

1.1 安裝

pip install drf-haystack   # django的開源搜尋框架 
pip install whoosh   # 搜尋引擎 
pip install jieba   # 中文分詞Jieba,由於Whoosh自帶的是英文分詞,對中文的分詞支援 不是太好

1.2 什麼是haystack?

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

2.配置使用

syl/settings.py 全文檢索配置

'''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'),    # 指定倒排索引 存放位置
    }
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

2.2 在子應用下建立索引檔案

  • apps/course/search_indexes.py
# -*- coding: utf-8 -*-
from haystack import indexes
from .models import Course

# 修改此處,類名為模型類的名稱+Index,比如模型類為GoodsInfo,則這裡類名為GoodsInfoIndex(其 實可以隨便寫)
class CourseIndex(indexes.SearchIndex,indexes.Indexable):

    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()

2.3 指定索引模板檔案

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

2.4 修改為jieba分詞中的中文分析器

  • apps/course/whoosh_cn_backend.py
# -*- coding: utf-8 -*-
# 更換 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


2.5 課程全文檢索介面檢視函式

  • course/views.py
from syl import settings 
from django.core.paginator import InvalidPage, Paginator 
from haystack.forms import ModelSearchForm 
from django.http import JsonResponse

# 如果settings.py中配置就是用settings中配置的,否則就每頁15條
RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 15)

def course_index_search(request):
    query = request.GET.get('q',None)
    page = int(request.GET.get('page',1)) # 第幾頁
    page_size = int(request.GET.get('page_size',RESULTS_PER_PAGE)) #每頁多少條
    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": []})

    # 對結果集進行分頁
    paginator = Paginator(results,page_size)
    try:
        page = paginator.page(page)
    except InvalidPage:
        return JsonResponse({"code": 404, "msg": 'No file found!', "data": []})

    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)

2.6 syl/urls.py 新增路由

urlpatterns = [
    path('search/', course_index_search),
]

2.7 命令構建倒排索引

python manage.py rebuild_index

3.測試課程全文檢索

  • 測試介面
http://192.168.56.100:8888/search/?q=python&page=1&page_size=1
  • 測試結果