Lucene 4.4简单搜索测试

package com.zsj.test;

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

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
 * 测试Lucene 4.4简单搜索
 * @author hadoop
 *
 */
public class LuceneSearcher {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String dir = "D:\\user";

  try {
   Directory directory = FSDirectory.open(new File(dir));
   @SuppressWarnings("deprecation")
   IndexReader reader = IndexReader.open(directory);
   IndexSearcher indexSearcher = new IndexSearcher(reader);
   /**
    * 创建搜索字段
    */
   Term term = new Term("name", "shu");
   TermQuery termQuery = new TermQuery(term);
   TopDocs topDocs = indexSearcher.search(termQuery, 4);
   ScoreDoc scoreDocs[] = topDocs.scoreDocs;
   for (int i = 0; i < scoreDocs.length; i++) {
    Document document = indexSearcher.doc(scoreDocs[i].doc);
    System.out.println(document.get("id"));
    System.out.println(document.get("name"));
    System.out.println(document.get("text"));
   }

directory.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }

}

你可能感兴趣的:(Lucene 4.4简单搜索测试)