全文索引搜尋whoosh,
問題Whoosh是python中解決索引尋找的模組,在討論索引尋找的文章已經對有關索引尋找進行了闡述,此處詳細說明Whoosh模組的應用。
思路說明Whoosh的安裝
這裡有詳細內容(連結被被閹割!)
whoosh的使用步驟
whoosh在應用上劃分三個步驟:
下面依次闡述各步驟
建立索引和模式對象建立索引模式
使用Whoosh的第一步就是要建立索引對象。首先要定義索引模式,以欄位的形式列在索引中。例如:
>>> from whoosh.fields import *>>> schema = Schema(title=TEXT, path=ID, content=TEXT)
title/path/content就是所謂的欄位。每個欄位對應索引尋找目標檔案的一部分資訊,上面的例子中就是建立索引的模式:索引內容包括title/path/content。一個欄位建立了索引,意味著它能夠被搜尋;也能夠被儲存,意味著返回結果。例如上面的例子,可以寫成:
>>> schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)
這裡在某些欄位後面添加了(stored=True),意味著將返回該欄位的搜尋結果。
以上就建立好了索引模式,不需要重複建立索引模式,因為一旦此模式建立,將隨索引儲存。
在生產過程中,如果你願意,還可以建立一個類用於建立索引模式。如下例子:
from whoosh.fields import SchemaClass, TEXT, KEYWORD, ID, STOREDclass MySchema(SchemaClass): path = ID(stored=True) title = TEXT(stored=True) content = TEXT tags = KEYWORD
索引欄位類型
在上例中,title=TEXT,title是欄位名稱,後面的TEXT是該欄位的類型。這兩個分別說明了索引內容和尋找物件類型。whoosh有如下欄位類型,供建立所以模式使用。
- whoosh.fields.ID:僅能為一個單元值,即不能分割為若干個詞,通常用於諸如檔案路徑,URL,日期,分類。
- whoosh.fields.STORED:該欄位隨檔案儲存,但是不能被索引,也不能被查詢。常用於顯示檔案資訊。
- whoosh.fields.KEYWORD:用空格或者逗號(半形)分割的關鍵詞,可被索引和搜尋。為了節省空間的,不支援詞彙搜尋。
- whoosh.fields.TEXT:檔案的常值內容。建立文本的索引並儲存,支援詞彙搜尋。
- whoosh.fields.NUMERIC:數字類型,儲存整數或浮點數。
- whoosh.fields.BOOLEAN:布爾類值
- whoosh.fields.DATETIME:時間物件類型
關於索引欄位類型的更多內容,請看這裡.(連結被被閹割!)
建立索引儲存目錄
索引模式建立之後,還要建立索引儲存目錄。如下:
import os.pathfrom whoosh.index import create_infrom whoosh.index import open_dirif not os.path.exists('index'): #如果目錄index不存在則建立 os.mkdir('index') ix = create_in("index",schema) #按照schema模式建立索引目錄ix = open_dir("index") #開啟該目錄一遍儲存索引檔案
上例中,用create_in建立一個具有前述索引模式的索引儲存目錄對象,所有的索引將被儲存在該目錄(index)中。
之後,用open_dir開啟這個目錄。
第一步到此結束。
把上面的代碼整理一下,供參考:
import os.pathfrom whoosh import fieldsfrom whoosh import indexschema = fields.Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)if not os.path.exists("index"): os.mkdir("index")ix = index.create_in("index",schema)ix = index.open_dir("index")
寫索引檔案
(待續)
聲明
本文屬於閹割之後的版本。要看完整版,請到我的github:qiwsir的ITArticles裡面的BasicPython。