Django中使用Whoosh進行全文檢索的方法
Whoosh 是純Python實現(xiàn)的全文搜索引擎,通過Whoosh可以很方便的給文檔加上全文索引功能。
什么是全文檢索
簡單講分為兩塊,一塊是分詞,一塊是搜索。比如下面一段話:
上次舞蹈演出直接在上海路的弄堂里
比如我們現(xiàn)在想檢索上次的演出,通常我們會直接搜索關(guān)鍵詞: 上次演出 ,但是使用傳統(tǒng)的SQL like 查詢并不能命中上面的這段話,因為在 上次 和 演出 中間還有 舞蹈 。然而全文搜索卻將上文切成一個個Token,類似:
上次/舞蹈/演出/直接/在/上海路/的/弄堂/里
切分成Token后做反向索引(inverted indexing),這樣我們就可以通過關(guān)鍵字很快查詢到了結(jié)果了。
解決分詞問題
分詞是個很有技術(shù)難度的活,比如上面的語句中一個難點就是到底是 上海路 還是 上海 呢?Python有個中文分詞庫: 結(jié)巴分詞 ,我們可以通過結(jié)巴分詞來完成索引中分詞工作,結(jié)巴分詞提供了Whoosh的組件可以直接集成,代碼示例
遇到的問題
如果是在一些VPS上測試的時候非常慢的話可能是內(nèi)存不足,比如512MB做一個博客索引非常慢,嘗試升級到1GB后可以正常使用了。
代碼
import logging import os import shutil from django.conf import settings from whoosh.fields import Schema, ID, TEXT, NUMERIC from whoosh.index import create_in, open_dir from whoosh.qparser import MultifieldParser from jieba.analyse import ChineseAnalyzer from .models import Article log = logging.getLogger(__name__) index_dir = os.path.join(settings.BASE_DIR, "whoosh_index") indexer = open_dir(index_dir) def articles_search(keyword): mp = MultifieldParser( ['content', 'title'], schema=indexer.schema, fieldboosts={'title': 5.0}) query = mp.parse(keyword) with indexer.searcher() as searcher: results = searcher.search(query, limit=15) articles = [] for hit in results: log.debug(hit) articles.append({ 'id': hit['id'], 'slug': hit['slug'], }) return articles def rebuild(): if os.path.exists(index_dir): shutil.rmtree(index_dir) os.makedirs(index_dir) analyzer = ChineseAnalyzer() schema = Schema( id=ID(stored=True, unique=True), slug=TEXT(stored=True), title=TEXT(), content=TEXT(analyzer=analyzer)) indexer = create_in(index_dir, schema) __index_all_articles() def __index_all_articles(): writer = indexer.writer() published_articles = Article.objects.exclude(is_draft=True) for article in published_articles: writer.add_document( id=str(article.id), slug=article.slug, title=article.title, content=article.content, ) writer.commit() def article_update_index(article): ''' updating an article to indexer, adding if not. ''' writer = indexer.writer() writer.update_document( id=str(article.id), slug=article.slug, title=article.title, content=article.content, ) writer.commit() def article_delete_index(article): writer = indexer.writer() writer.delete_by_term('id', str(article.id)) writer.commit()
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用Selenium在Python中實現(xiàn)錄屏功能
Selenium 是一個強大的用于自動化測試的工具,但你知道它也可以用來錄制瀏覽器操作的視頻嗎?本文將介紹如何使用 Selenium 在 Python 中實現(xiàn)錄屏功能,以便記錄和分享你的網(wǎng)頁操作過程,需要的朋友可以參考下2023-11-11python經(jīng)典趣味24點游戲程序設(shè)計
這篇文章主要介紹了python經(jīng)典趣味24點游戲程序設(shè)計,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07詳解python如何在django中為用戶模型添加自定義權(quán)限
這篇文章主要介紹了python如何在django中為用戶模型添加自定義權(quán)限,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10pandas取dataframe特定行列的實現(xiàn)方法
大家在使用Python進行數(shù)據(jù)分析時,經(jīng)常要使用到的一個數(shù)據(jù)結(jié)構(gòu)就是pandas的DataFrame,本文介紹了pandas取dataframe特定行列的實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-05-05