今天写了点lucene的搜索器感觉很不爽,老是出错!纠结啊!!
package jim.Lucene35;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
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.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
class Search {
Directory directory = null;
String indexPath = "index";
IndexReader reader = null;
IndexSearcher searcher = null;
QueryParser parser = null;
Query query = null;
TopDocs tds = null;
Document document = null;
public Search(){
try {
directory = FSDirectory.open(new File(indexPath));
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("创建Directory时发生错误!");
e.printStackTrace();
}//创建directory,其储存方式为在硬盘上储存
try {
reader = IndexReader.open(directory);
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
System.out.println("创建IndexReader时发生错误!");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("创建IndexReader时发生错误!");
e.printStackTrace();
}
searcher = new IndexSearcher(reader);
parser = new QueryParser(Version.LUCENE_35,"content",new StandardAnalyzer(Version.LUCENE_35));
try {
query = parser.parse("love");
} catch (ParseException e) {
// TODO Auto-generated catch block
System.out.println("query = parser.parse(\"java\")时发生错误");
e.printStackTrace();
}
try {
tds = searcher.search(query,5);
} catch (IOException e) {
System.out.println("std = searcher.search(query,5);时发生错误");
// TODO Auto-generated catch block
e.printStackTrace();
}
ScoreDoc[] sds = tds.scoreDocs;
System.out.println("sds.length: "+sds.length);
for(ScoreDoc sd:sds){
try {
document = searcher.doc(sds[0].doc);
} catch (CorruptIndexException e) {
// TODO Auto-generated catch block
System.out.println("document = searcher.doc(sd.doc);时发生错误");
e.printStackTrace();
} catch (IOException e) {
System.out.println("document = searcher.doc(sd.doc);时发生错误");
e.printStackTrace();
}
System.out.println(document.get("title")+"["+document.get("path")+"]");
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("关闭reader时发生错误!");
e.printStackTrace();
}
System.out.println("Finished");
}
}
public class Searcher {
public static void main(String [] args){
new Search();
}
}
这个只是一个小练习,明天会写个正式的!
今天的收获:
对lucene有了新的认识,多多少少能看懂lucene的文档了
今天的不足:
今天估计得敲了1000多行代码,万恶的lucene啊!老是出错!