lucene3.6查询TopDocs

来源:互联网 发布:easypusher linux 编辑:程序博客网 时间:2024/05/18 00:25

import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
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.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

/**
 *
 */

/**
 * @author cyh
 *
 */
public class IndexSearcherTest {
 public static final Version VERSION_36 = Version.LUCENE_36;

 public static Analyzer analyzer = new IKAnalyzer();

 public static void search(String[] fields, String keyword) throws Exception {
  /** 获取IndexSearcher */
  IndexReader reader = IndexReader.open(FSDirectory
    .open(new File("index")));
  IndexSearcher searcher = new IndexSearcher(reader);

  /** 搜索条件 */
  // QueryParser parser = new QueryParser(VERSION_36, fields[0],
  // analyzer);
  QueryParser parser = new MultiFieldQueryParser(VERSION_36, fields,
    analyzer);
  Query query = parser.parse(keyword);
  System.out.println("Searching for: " + query.toString());

  TopDocs results = searcher.search(query, 5);
  // TopDocs results = searcher.search(query, 5, sort);
  ScoreDoc[] hits = results.scoreDocs;
  System.out.println("results.totalHits:" + results.totalHits);
  System.out.println("hits.length:" + hits.length);

  // 高亮显示设置
  // Formatter formatter = new SimpleHTMLFormatter("<b>","</b>");
  // Highlighter highlighter = new Highlighter(formatter,new
  // QueryScorer(query));
  // highlighter.setTextFragmenter(new SimpleFragmenter(200));

  for (ScoreDoc scoreDoc : hits) {
   // 评分详情
   // Explanation explanation = searcher.explain(query, scoreDoc.doc);

   Document doc = searcher.doc(scoreDoc.doc);
   System.out.println(scoreDoc.score + "\tid:" + doc.get("path"));
   // System.out.println(scoreDoc.score + "  " + doc.toString());

   // TokenStream tokenStream = analyzer.tokenStream("token", new
   // StringReader(doc.get(field)));
   // System.out.println(highlighter.getBestFragment(tokenStream,doc.get(field)));
  }
 }

 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
  search(new String[] { "body" }, "hello");

 }

}

原创粉丝点击