lucene支持十分丰富的查询,这里列写其中一些比较常用的查询的用法。
term查询、queryParser查询 ,booleanQuery
package search;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
public class Searcher {
public static void termQuery() throws Exception{
Directory directory = FSDirectory.getDirectory("./index", false);
IndexSearcher searcher = new IndexSearcher(directory);
Term t = new Term("body","document");
Query query = new TermQuery(t);
Hits hits = searcher.search(query);
System.out.println(hits.length());
}
public static void queryParser() throws Exception{
Directory directory = FSDirectory.getDirectory("./index", false);
IndexSearcher searcher = new IndexSearcher(directory);
Query query = QueryParser.parse("text","body",new StandardAnalyzer());
Hits hits = searcher.search(query);
System.out.println(hits.length());
}
public static void booleanQuery() throws Exception{
Query parseQuery = QueryParser.parse("text","body",new StandardAnalyzer());
Term t = new Term("body","document");
Query termQuery = new TermQuery(t);
BooleanQuery boolQuery = new BooleanQuery();
boolQuery.add(parseQuery,true,false);
boolQuery.add(termQuery,true,false);
Directory directory = FSDirectory.getDirectory("./index", false);
IndexSearcher searcher = new IndexSearcher(directory);
Hits hits = searcher.search(boolQuery);
System.out.println(hits.length());
}
public static void main(String[] args) throws Exception{
termQuery();
queryParser();
booleanQuery();
}
}