Lucene 4.4利用BooleanQuery组合多个Query搜索

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.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
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.search.WildcardQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
 * 利用BooleanQuery
 * 进行多个Query组合查询
 * 
 * @author hadoop
 * 
 */
public class LuceneWildCardSearcher {
 /**
  * @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*");
   WildcardQuery wildcardQuery = new WildcardQuery(term);
   Term term2 = new Term("datetime", "191111");
   TermQuery termQuery = new TermQuery(term2);
   BooleanQuery booleanQuery = new BooleanQuery();
   booleanQuery.add(wildcardQuery, Occur.MUST);
   booleanQuery.add(termQuery, Occur.MUST);
   TopDocs topDocs = indexSearcher.search(booleanQuery, 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利用BooleanQuery组合多个Query搜索)