全文檢索索引之lucene入門篇HelloWorld

來源:互聯網
上載者:User

標籤:java

       首先,先看下目錄結構。


       第一步,在eclipse中建立jave項目。需要引入jar包,只有3個,分別是lucene的分詞器和核心包,還有高亮顯示器。做法是建立一個lib檔案夾,將jar包拷過來,然後右擊,選擇Build Path(構建路徑),Addto Build Path(添加到項目的構建路徑)。


          然後建立datasource檔案夾,添幾個txt的檔案進去,內容愛寫啥寫啥。(但是建議是一個是中文,一個是英文,可以測兩種語言的分詞)。還有luceneIndex檔案夾,用來存放建立的索引.

         其中,IndexWriteraddDocument‘s a javadoc.txt的內容是

Adds room adocument to this room index. If the room document contains room  more than setMaxFieldLength(int) terms for agiven field, the remainder are discarded.

         小笑話_總統的房間 Room .txt 的內容是

總統的房間

   一位紳士到旅遊勝地的一家飯店要開個房間,

   侍者因為他沒有預定而拒絕說:“房間全滿,無法安排。”

    “聽著!”紳士說,“假如我告訴你總統要到這裡來,你一定會馬上向他提供一套客房吧?”

    “當然啦,他是總……”

    “好了,我榮幸地通知你:總統今晚不來了。你把他的房間給我吧!”

          然後建立包,com.lucene.helloworld,建立一個HelloWorld的類。裡面主要的兩個方法就是建立索引,以及查詢關鍵字。

package com.lucene.helloworld;import org.apache.lucene.analysis.Analyzer;import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.document.Document;import org.apache.lucene.index.IndexWriter;import org.apache.lucene.index.IndexWriter.MaxFieldLength;import org.apache.lucene.queryParser.MultiFieldQueryParser;import org.apache.lucene.queryParser.QueryParser;import org.apache.lucene.search.Filter;import org.apache.lucene.search.IndexSearcher;import org.apache.lucene.search.Query;import org.apache.lucene.search.ScoreDoc;import org.apache.lucene.search.TopDocs;import org.junit.Test;import com.lucene.units.File2DocumentUtils;public class HelloWorld {//需要查詢的檔案所在的路徑String filePath = "F:\\Users\\liuyanling\\workspace\\LuceneDemo\\datasource\\peoplewhocannot.txt";//設定索引存放的路徑String indexPath = "F:\\Users\\liuyanling\\workspace\\LuceneDemo\\luceneIndex";//設定分詞器為標準分詞器Analyzer analyzer = new StandardAnalyzer();/** * 建立索引,先將檔案File轉化為Document類型,然後用IndexWriter,將Document按照設定的分詞器和其他規則,建立索引,存到相應路徑中 */@Testpublic void createIndex() throws Exception {Document doc = File2DocumentUtils.file2Document(filePath);IndexWriter indexWriter = new IndexWriter(indexPath,analyzer,true,MaxFieldLength.LIMITED);indexWriter.addDocument(doc);indexWriter.close();}/** * 搜尋,查詢關鍵字queryString,先設定查詢的範圍,在"名稱"和"內容"中查詢。然後用IndexSearcher來查詢, * 通過查詢索引來將結果返回。返回的結果是TopDocs類型,還需要進行處理才能拿到結果。 */@Testpublic void search() throws Exception {String queryString = "Internet";String[] fields = {"name","content"};QueryParser queryParser = new MultiFieldQueryParser(fields,analyzer);Query query = queryParser.parse(queryString);IndexSearcher indexSearcher = new IndexSearcher(indexPath);Filter filter = null;//查詢前10000條記錄TopDocs topDocs = indexSearcher.search(query,filter,10000);System.out.println("總共有["+topDocs.totalHits+"]條匹配結果");//將查詢出的結果的scoreDocs進行遍曆for (ScoreDoc scoreDoc : topDocs.scoreDocs ) {//取出檔案的doc編號int docSn = scoreDoc.doc; //根據編號,用indexSearcher尋找到document檔案Document doc = indexSearcher.doc(docSn);//將Document檔案內容列印出來File2DocumentUtils.printDocumentInfo(doc);};}}

    接著,由於裡面用了File2DocumentUtils類的printDocumentInfo()和file2Document(),列印Document內容和File轉換為Document兩個方法。看看File2DocummentUtils檔案內容.

package com.lucene.units;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStreamReader;import org.apache.lucene.document.Document;import org.apache.lucene.document.Field;import org.apache.lucene.document.NumberTools;import org.apache.lucene.document.Field.Index;import org.apache.lucene.document.Field.Store;/** * File轉化為Document的工具類 * @author liuyanling * */public class File2DocumentUtils {/** * 檔案File轉為Document.先根據路徑,讀取出File檔案.然後根據檔案的Name,content,size,path來建立索引,確認是否儲存. * @param path * @return Document,被轉換好的結果 */public static Document file2Document(String path) {File file = new File(path);Document doc = new Document();//將檔案名稱和內容分詞,建立索引,儲存;而內容通過readFileContent方法讀取出來。doc.add(new Field("name",file.getName(),Store.YES,Index.ANALYZED));doc.add(new Field("content",readFileContent(file),Store.YES,Index.ANALYZED));//將檔案大小儲存,但建立索引,但不分詞;路徑則不需要建立索引doc.add(new Field("size",String.valueOf(file.length()),Store.YES,Index.NOT_ANALYZED));doc.add(new Field("path",file.getPath(),Store.YES,Index.NO));return doc;}/** * 讀取檔案內容。通過FileInputStream檔案輸入資料流,InputStreamReader讀取輸入資料流,再用BufferedReader封裝,可以readLine * 一行一行將資料取出。 * @param file 檔案對象 * @return String,檔案中的內容 */public static String readFileContent(File file) {try {BufferedReader reader = new BufferedReader (new InputStreamReader(new FileInputStream(file)));//儲存File的內容StringBuffer content = new StringBuffer();for(String line = null;(line = reader.readLine()) != null;) {content.append(line).append("\n");}return content.toString();} catch (Exception e) {throw new RuntimeException();}}/** * 將Document檔案的內容列印出來,直接根據之前建立索引的使用的欄位名,get出欄位內容,列印 * @param doc */public static void printDocumentInfo(Document doc) {////第一種讀取方式,先getfiled,然後stringValue//Field r = doc.getField("name");//r.stringValue();//第二種讀取方式,直接getSystem.out.println("name ="+doc.get("name"));System.out.println("content =" +doc.get("content"));System.out.println("size =" +doc.get("size"));System.out.println("path =" +doc.get("path"));} }

    代碼寫完了,先建立索引,在createIndex方法上右擊Run As選擇Junit Test,進行單元測試。


   測試成功之後,就可以看到index增加了,說明索引添加了。


    然後測試測試,查詢的結果如下。只查詢到一個結果,將name,context,size和路徑都列印出來了。


         以上就是簡單的全文檢索索引查詢,缺陷有很多,比如索引的存放位置是事先手動建立的,比如沒有進行查詢結果的高亮設定,比如對於分詞器也只使用了標準的分詞器。所以,改進請見下篇《全文檢索索引之lucene的最佳化篇--建立索引存放的目錄》.


全文檢索索引之lucene入門篇HelloWorld

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.