1.建立索引
File indexDir=new File("E:\\Index\\");
Analyzer luceneAnalyzer=new StandardAnalyzer(Version.LUCENE_35);
IndexWriter indexWriter=null;
try {
IndexWriterConfig indexWriterConfig=new IndexWriterConfig(Version.LUCENE_35,luceneAnalyzer);
indexWriter=new IndexWriter(SimpleFSDirectory.open(indexDir),indexWriterConfig);
Field f1=new Field("name","",Field.Store.YES,Field.Index.ANALYZED);
Field f2=new Field("address","",Field.Store.YES,Field.Index.ANALYZED);
ResultSet rs=getResultSet("select * from authors");
while(rs.next())
{
Document doc=new Document();
f1.setValue(rs.getString(2));
System.out.println(rs.getString(2));
doc.add(f1);
f2.setValue(rs.getString(4));
doc.add(f2);
System.out.println(rs.getString(4));
indexWriter.addDocument(doc);
}
System.out.println("DocNum:"+indexWriter.numDocs());
indexWriter.commit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
finally
{
try {
indexWriter.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
Field.Store.YES或者NO(存储域选项)
设置为YES表示或把这个域中的内容完全存储到文件中,方便进行文本的还原
设置为NO表示把这个域的内容不存储到文件中,但是可以被索引,此时内容无法完全 还原(doc.get是为null)
Field.Index(索引选项)
Index.ANALYZED:进行分词和索引,适用于标题、内容等
Index.NOT_ANALYZED:进行索引,但是不进行分词,如果身份证号,姓名,ID等,适 用于精确搜索
Index.ANALYZED_NOT_NORMS:进行分词但是不存储norms信息,这个norms中包括 了创建索引的时间和权值等信息
Index.NOT_ANALYZED_NOT_NORMS:即不进行分词也不存储norms信息
Index.NO:不进行索引
2.查找索引
IndexSearcher indexSearcher=null;
String [] queryFileds = {"name","address"};
try {
Directory dir=new SimpleFSDirectory(new File("E:\\Index"));
indexSearcher=new IndexSearcher(IndexReader.open(dir));
QueryParser queryParser=new MultiFieldQueryParser(Version.LUCENE_35,queryFileds,new StandardAnalyzer(Version.LUCENE_35));
String key="宁";
Query query=queryParser.parse(key);
TopDocs topDocs=indexSearcher.search(query,10);
System.out.println("Total:"+topDocs.totalHits);
for(ScoreDoc scoreDoc:topDocs.scoreDocs)
{
Document doc=indexSearcher.doc(scoreDoc.doc);
System.out.println(doc.get("name"));
System.out.println(doc.get("address"));
}
indexSearcher.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}