lucene搜索---从多个索引文件搜索


import java.io.StringReader;
import java.util.Date;

import org.apache.lucene.analysis.cn.ChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MultiSearcher;
import org.apache.lucene.search.Query;

import org.apache.lucene.search.highlight.Highlighter;

public class Search {
 public static void main(String[] args) throws Exception{
  Search test = new Search();
  //
  Hits h = null;
  h = test.search("显示 ");
  test.printResult(h);
  
 
 }
 public Search(){
  try{
   //searcher = new IndexSearcher(IndexReader.open("E://lucene//test4//index"));
   searchers = new IndexSearcher[2]; 
   searchers[0] = new IndexSearcher(IndexReader.open("E://lucene//test4//index"));
   searchers[1] = new IndexSearcher(IndexReader.open("E://lucene//test5//index"));

  }catch(Exception e){
   e.printStackTrace();
  }
 }
 IndexSearcher[] searchers = null;
 //声明一个IndexSearcher对象

 //声明一个Query对象
 private Query query = null;
 ChineseAnalyzer analyzer = new ChineseAnalyzer();
 Highlighter highlighter = null;
 public final Hits search(String keyword){
  System.out.println("正在检索关键字:"+keyword);
  try{
   Date start = new Date();
   
   
   /*****  一个关键字,对一个字段进行查询  *****/
   QueryParser qp = new QueryParser("content",analyzer);
   query = qp.parse(keyword);
   
 
   
   
    
   MultiSearcher multiSearcher = new MultiSearcher(searchers);
   Hits hits = multiSearcher.search(query);
   
   
   Date end = new Date();
   System.out.println("检索完成,用时"+(end.getTime()-start.getTime())+"毫秒");
   return hits;
  }catch(Exception e){
   e.printStackTrace();
   return null;
  }
  
 }
 
 
 public void printResult(Hits h){
  if(h.length() == 0){
   System.out.println("对不起,没有找到您要的结果.");
  }else{
   for(int i = 0; i < h.length(); i++){
    try{
     Document doc = h.doc(i);
//     System.out.println("结果"+(i+1)+":"+doc.get("id")+" createTime:"+doc.get("createTime")+" title:"+doc.get("title")+"        content:"+doc.get("content"));
     
     System.out.println("结果"+(i+1)+":"+doc.get("id")+" createTime:"+doc.get("createTime")+" title:"+doc.get("title")+"        content:"+doc.get("content"));

    
     //System.out.println(doc.get("path"));
    }catch(Exception e){
     e.printStackTrace();
    }
   }
  }
  System.out.println("--------------------------------------");
 }
}

你可能感兴趣的:(exception,null,Lucene,search,query,import)