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

/**
 * 测试Lucene 4.4范围搜索
 * 实现需求描述:
 * 可以实现基于时间的范围查询比如查询
 * 191110到198717之间的值
 * @author hadoop
 *
 */
public class LuceneRangSearcher {

 /**
  * @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 begin = new Term("datetime", "191111");
   Term end = new Term("datetime", "198108");
   /**
    * 参数Boolean值说明
    * false表示不包含 191111
    * true 表示包含198108
    * 这两个Boolean表示查询结果
    * 是否包含lower,upper两个临界值
    */
   TermRangeQuery termRangeQuery = new TermRangeQuery("datetime",
     begin.bytes(), end.bytes(), false, true);
   TopDocs topDocs = indexSearcher.search(termRangeQuery, 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();
  }

 }
}

你可能感兴趣的:(Lucene 4.4范围查询)