Django中使用Whoosh進(jìn)行全文檢索的方法
Whoosh 是純Python實(shí)現(xiàn)的全文搜索引擎,通過Whoosh可以很方便的給文檔加上全文索引功能。
什么是全文檢索
簡單講分為兩塊,一塊是分詞,一塊是搜索。比如下面一段話:
上次舞蹈演出直接在上海路的弄堂里
比如我們現(xiàn)在想檢索上次的演出,通常我們會直接搜索關(guān)鍵詞: 上次演出 ,但是使用傳統(tǒng)的SQL like 查詢并不能命中上面的這段話,因?yàn)樵?上次 和 演出 中間還有 舞蹈 。然而全文搜索卻將上文切成一個個Token,類似:
上次/舞蹈/演出/直接/在/上海路/的/弄堂/里
切分成Token后做反向索引(inverted indexing),這樣我們就可以通過關(guān)鍵字很快查詢到了結(jié)果了。
解決分詞問題
分詞是個很有技術(shù)難度的活,比如上面的語句中一個難點(diǎn)就是到底是 上海路 還是 上海 呢?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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python?計(jì)算機(jī)視覺編程進(jìn)階之圖像特效處理篇
計(jì)算機(jī)視覺這種技術(shù)可以將靜止圖像或視頻數(shù)據(jù)轉(zhuǎn)換為一種決策或新的表示。所有這樣的轉(zhuǎn)換都是為了完成某種特定的目的而進(jìn)行的,本篇我們來學(xué)習(xí)下如何對圖像進(jìn)行特效處理2021-11-11
在python中利用dict轉(zhuǎn)json按輸入順序輸出內(nèi)容方式
今天小編就為大家分享一篇在python中利用dict轉(zhuǎn)json按輸入順序輸出內(nèi)容方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02
學(xué)習(xí)Python爬蟲前必掌握知識點(diǎn)
這篇文章主要介紹了學(xué)習(xí)Python爬蟲前,我們需要了解涉及爬蟲的知識點(diǎn),學(xué)習(xí)爬蟲的知識點(diǎn)比較多,我們一起學(xué)習(xí)爬蟲吧2021-04-04

