Whoosh 是純Python實(shí)現(xiàn)的全文搜索引擎,通過Whoosh可以很方便的給文檔加上全文索引功能。
什么是全文檢索
簡(jiǎn)單講分為兩塊,一塊是分詞,一塊是搜索。比如下面一段話:
上次舞蹈演出直接在上海路的弄堂里
比如我們現(xiàn)在想檢索上次的演出,通常我們會(huì)直接搜索關(guān)鍵詞: 上次演出 ,但是使用傳統(tǒng)的SQL like 查詢并不能命中上面的這段話,因?yàn)樵?上次 和 演出 中間還有 舞蹈 。然而全文搜索卻將上文切成一個(gè)個(gè)Token,類似:
上次/舞蹈/演出/直接/在/上海路/的/弄堂/里
切分成Token后做反向索引(inverted indexing),這樣我們就可以通過關(guān)鍵字很快查詢到了結(jié)果了。
解決分詞問題
分詞是個(gè)很有技術(shù)難度的活,比如上面的語句中一個(gè)難點(diǎn)就是到底是 上海路 還是 上海 呢?Python有個(gè)中文分詞庫: 結(jié)巴分詞 ,我們可以通過結(jié)巴分詞來完成索引中分詞工作,結(jié)巴分詞提供了Whoosh的組件可以直接集成,代碼示例
遇到的問題
如果是在一些VPS上測(cè)試的時(shí)候非常慢的話可能是內(nèi)存不足,比如512MB做一個(gè)博客索引非常慢,嘗試升級(jí)到1GB后可以正常使用了。
代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
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() |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.imzjy.com/blog/2018-10-06-full-text-search-with-whoosh