lucene實例(lucene demo)

public class CreateIndex {//建立索引文件
public static void main(String[] args) throws Exception {

File indexDir = new File("c:\\index"); //索引所在路徑
Analyzer luceneAnalyzer = new StandardAnalyzer();
IndexWriter indexWriter = new IndexWriter(indexDir, luceneAnalyzer, true);
long startTime = new Date().getTime();
CreateIndexDAO creareindex=new CreateIndexDAO();
List indexlist=new ArrayList();//數據源
indexlist=creareindex.selectData();//
for (int i = 0; i < indexlist.size(); i++) {
Data data = (Data) indexlist.get(i);
Document doc = new Document();
doc.add(new Field("uid", data.getUid(),
Field.Store.YES, Field.Index.NO));
doc.add(new Field("keyword",data.getKeyword(),
Field.Store.YES,Field.Index.TOKENIZED,Field.TermVector.WITH_POSITIONS_OFFSETS));
doc.add(new Field("txtinfo", data.getTextinfo(),
Field.Store.YES, Field.Index.UN_TOKENIZED));
indexWriter.addDocument(doc);
}
indexWriter.optimize();
indexWriter.close();

long endTime = new Date().getTime(); {
System.out.println("用時"
+ (endTime - startTime)
+ "秒"
);
}
}
//查詢方法
public class CreateSearch {
public static void main(String[] args) throws IOException, ParseException {
Hits hits = null;
String queryString = "十";
Query query = null;
IndexSearcher searcher = new IndexSearcher("c:\\index");
Analyzer analyzer = new StandardAnalyzer();
try {
QueryParser qp = new QueryParser("keyword", analyzer);
query = qp.parse(queryString);

} catch (ParseException e) {
}
if (searcher != null) {
hits = searcher.search(query);
for (int i = 0; i < hits.length(); i++) {
Document doc = hits.doc(i);
String uid = doc.get("uid");
String keyword = doc.get("keyword");
System.out.println("記錄:" + keyword + "對應id"+keyword);
}
System.out.println("共查出記錄" + hits.length() + "條");

}
}

}
[color=red]有不明白的地方歡迎聯繫我,共同探討[/color]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章