?? luceneramsearchtext.java
字號:
package chapter6;
import java.io.IOException;
import org.apache.lucene.index.Term;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
public class LuceneRAMSearchText {
private static String Dest_Index_Path = "D:\\workshop\\TextIndex";
static protected String[] keywords = {"001","002","003"};
static protected String[] textdetail = {"記錄 一","記錄 二", "記錄 三"} ;
/*================================================================
* 名 稱:QueryRAMIndex
* 功 能:構造檢索查詢器,對指定的目錄進行查詢,找到指定的值,并輸出相應結果。
===============================================================*/
public static void QueryRAMIndex(){
try {
Directory fsDir = FSDirectory.getDirectory(Dest_Index_Path, false);
Directory ramDir = new RAMDirectory(fsDir);
IndexSearcher searcher = new IndexSearcher(ramDir);
Term term = new Term("id","002");
//Term term = new Term("content","記錄");
Query query = new TermQuery(term);
System.out.println(query.toString());
Hits hits = searcher.search(query);
System.out.println("Search result:");
for(int i=0; i < hits.length(); i++)
{
System.out.println(hits.doc(i));
System.out.println(hits.doc(i).getField("id"));
}
}catch (IOException e) {
e.printStackTrace();
}
System.out.println("Search success");
}
/*================================================================
* 名 稱:IndexBuilder
* 功 能:構造磁盤索引,添加內容到指定目錄,為后續(xù)檢索查詢做好準備。
===============================================================*/
public static void IndexBuilder(){
try {
Analyzer TextAnalyzer = new SimpleAnalyzer();
IndexWriter TextIndex = new IndexWriter(Dest_Index_Path,TextAnalyzer,true);
TextIndex.setUseCompoundFile(true);
for(int i = 0; i < 3 ; i++){
Document document = new Document();
Field field_id = new Field("id", keywords[i],
Field.Store.YES,Field.Index.UN_TOKENIZED);
document.add(field_id);
Field field_content = new Field("content", textdetail[i],
Field.Store.YES,Field.Index.TOKENIZED);
document.add(field_content);
TextIndex.addDocument(document);
}
TextIndex.optimize();
TextIndex.close();
}catch (IOException e) {
e.printStackTrace();
}
System.out.println("Index success");
}
/*================================================================
* 名 稱:main
* 功 能:測試Lucene索引建立和內存檢索查詢功能。
===============================================================*/
public static void main(String[] args) {
IndexBuilder();
QueryRAMIndex();
System.out.println("Test success");
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -