lucene数据库实例

创建索引
/**
* @author wanghuan
* @description 创建索引
* @throws CorruptIndexException
* @throws LockObtainFailedException
* @throws IOException
*/
public void createIndex() throws CorruptIndexException, LockObtainFailedException, IOException{
List<Hospital> list=Database.query();
  /* 创建索引初始化,执行这些语句将创建或清空d:\\save\\目录下所有索引 */
IndexWriter writer1 = new IndexWriter("d:\\save\\",new StandardAnalyzer(), true);
writer1.close();

/*
* 往创建的初始化索引中添加索引内容,StandardAnalyzer表示用lucene自带的标准分词机制,
* false表示不覆盖原来该目录的索引,细心的读者可能已经发现, 这句话和上面的那句就这个false不一样
*/
IndexWriter writer2 = new IndexWriter("d:\\save\\",new StandardAnalyzer(), false);
   
//创建文档
    for(Hospital hosp:list){
    Document doc = new Document();
   
    Field field1 = new Field("hospId", hosp.getId()+"", Field.Store.YES,Field.Index.TOKENIZED);
    /* 往文件里添加这个域 */
    doc.add(field1);
    /* 同理:创建另外一个域ArticleText,并往这个域里面添加内容 */
    Field field2 = new Field("hospName", hosp.getName(),Field.Store.YES, Field.Index.TOKENIZED);
    doc.add(field2);
//     //为字段 sname 建索引
//             doc.add(new Field("hospName",hosp.getName(),Field.Store.YES,Field.Index.TOKENIZED));
            System.out.println(hosp.getName());
            writer2.addDocument(doc);  
    }
    //关闭流
    writer2.close();
}

搜索

/**
* @author wanghuan
* @param serchString
* @throws Exception
*/
public void search(String serchString) throws Exception {
/* 创建一个搜索,搜索刚才创建的d:\\save\\目录下的索引 */
IndexSearcher indexSearcher = new IndexSearcher("d:\\save\\");
/* 在这里我们只需要搜索一个目录 */
IndexSearcher indexSearchers[] = { indexSearcher };
/* 我们需要搜索两个域"ArticleTitle", "ArticleText"里面的内容 */
String[] fields = { "hospId", "hospName" };
/* 下面这个表示要同时搜索这两个域,而且只要一个域里面有满足我们搜索的内容就行 */
BooleanClause.Occur[] clauses = { BooleanClause.Occur.SHOULD,BooleanClause.Occur.SHOULD };
/*
* MultiFieldQueryParser表示多个域解析,
* 同时可以解析含空格的字符串,如果我们搜索"中国 金牌",根据前面的索引,显然搜到的是第二份文件
*/
Query query = MultiFieldQueryParser.parse(serchString, fields, clauses,new StandardAnalyzer());
/* Multisearcher表示多目录搜索,在这里我们只有一个目录 */
MultiSearcher searcher = new MultiSearcher(indexSearchers);
/* 开始搜索 */
Hits h = searcher.search(query);
/* 把搜索出来的所有文件打印出来 */
for (int i = 0; i < h.length(); i++) {
/* 打印出文件里面ArticleTitle域里面的内容 */
System.out.println(h.doc(i).get("hospId"));
/* 打印出文件里面ArticleText域里面的内容 */
System.out.println(h.doc(i).get("hospName"));
}
/* 关闭 */
searcher.close();
}

你可能感兴趣的:(Lucene)