基於python+whoosh的全文檢索實現


whoosh的官方介紹:http://whoosh.readthedocs.io/en/latest/quickstart.html

因為做的是中文的全文檢索需要導入jieba工具包以及whoosh工具包

直接上代碼吧

 1 from whoosh.qparser import QueryParser  
 2 from whoosh.index import create_in  
 3 from whoosh.index import open_dir  
 4 from whoosh.fields import *  
 5 from jieba.analyse import ChineseAnalyzer  
 6 from get_comment import SQL  
 7 from whoosh.sorting import FieldFacet  
 8   
 9 analyser = ChineseAnalyzer()    #導入中文分詞工具  
10 schema = Schema(phone_name=TEXT(stored=True, analyzer=analyser), price=NUMERIC(stored=True),  
11                     phoneid=ID(stored=True))# 創建索引結構  
12 ix = create_in("path", schema=schema, indexname='indexname') #path 為索引創建的地址,indexname為索引名稱  
13 writer = ix.writer()  
14 writer.add_document(phone_name='name',price ="price",phoneid ="id") #  此處為添加的內容   
15 print("建立完成一個索引")  
16 writer.commit()  
17 # 以上為建立索引的過程  
18 new_list = []  
19 index = open_dir("indexpath", indexname='comment')  #讀取建立好的索引  
20 with index.searcher() as searcher:  
21     parser = QueryParser("要搜索的項目,比如“phone_name", index.schema)  
22     myquery = parser.parse("搜索的關鍵字")  
23     facet = FieldFacet("price", reverse=True)  #按序排列搜索結果  
24     results = searcher.search(myquery, limit=None, sortedby=facet)  #limit為搜索結果的限制,默認為10,詳見博客開頭的官方文檔  
25     for result1 in results:  
26         print(dict(result1))  
27         new_list.append(dict(result1))  

注:

 

Whoosh 有一些很有用的預定義 field types,你也可以很easy的創建你自己的。
whoosh.fields.ID
這個類型簡單地將field的值索引為一個獨立單元(這意味着,他不被分成單獨的單詞)。這對於文件路徑、URL、時間、類別等field很有益處。
whoosh.fields.STORED
這個類型和文檔存儲在一起,但沒有被索引。這個field type不可搜索。這對於你想在搜索結果中展示給用戶的文檔信息很有用。
whoosh.fields.KEYWORD
這個類型針對於空格或逗號間隔的關鍵詞設計。可索引可搜索(部分存儲)。為減少空間,不支持短語搜索。
whoosh.fields.TEXT
這個類型針對文檔主體。存儲文本及term的位置以允許短語搜索。
whoosh.fields.NUMERIC
這個類型專為數字設計,你可以存儲整數或浮點數。
whoosh.fields.BOOLEAN
這個類型存儲bool型
whoosh.fields.DATETIME
這個類型為 datetime object而設計(更多詳細信息)
whoosh.fields.NGRAM  和 whoosh.fields.NGRAMWORDS
這些類型將fiel文本和單獨的term分成N-grams(更多Indexing & Searching N-grams的信息)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM