1. 程式人生 > >Lucene 4.4 基於字首搜尋

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.PrefixQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class LucenePrefixSearcher {

 /**
  * @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", "zh");
   PrefixQuery prefixQuery = new PrefixQuery(term);

   TopDocs topDocs = indexSearcher.search(prefixQuery, 10);
   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"));
    System.out.println(document.get("datetime"));
   }
   directory.close();

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

 }
}