文章以最简单为例,展示LUCENE 2.0的索引方法
需要IMPORT的东西:
import java.sql.*;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import java.io.IOException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.search.Query;
建立的代码:
public void createIndex() {
try {
IndexWriter writer=new IndexWriter("g:\\index",new StandardAnalyzer(),true);
for(int i=0;i<1000;i++){
Document lDoc=new Document();
lDoc.add(new Field("title","中国人民办公室",Field.Store.YES,Field.Index.TOKENIZED));
lDoc.add(new Field("content","广州市中山医院",Field.Store.YES,Field.Index.TOKENIZED));
writer.addDocument(lDoc);
}
writer.optimize();
writer.close();
}
catch(Exception ex){
System.out.println(ex);
System.exit(0);
}
}
读取的代码:
public void seacher(String queryString){
Hits hits=null;
IndexReader ir;
Searcher search;
try{
ir=IndexReader.open("g:\\index");
search=new IndexSearcher(ir);
String fields[] = { "title", "content" };
QueryParser parser = new MultiFieldQueryParser(fields,new StandardAnalyzer());
Query query = parser.parse("中山");
hits = search.search(query);
for (int i = 0; i < hits.length(); i++) {
Document doc = hits.doc(i);
String docValue = doc.get("content");
System.out.println(docValue);
}
}
catch(Exception e){
System.out.print(e);
}
}
其中fields是要查找的字段,
title和content是要索引的字段名称,可以自定义的
“中国人民办公室”和“广州市中山医院”是要索引的内容
Field.Index.TOKENIZED是表示要索引的字段,如果不需要索引,可以写Field.Index.NO
"g:\\index"是要放索引文件的地点,程序会在g:建立一个index的目录,里面会有三个索引文件
好了,其它更深澳的东东,我还在研究,自己努力吧,呵呵
发表于 @ 2006年07月25日 10:35:00|评论(loading...)|编辑