QueryParser子类对单个域查询时创建查询query,构造方法中需要传入Lucene版本号,检索域名和分词器。
QueryParser parser = new QueryParser(Version.LUCENE_43, field, analyzer);// 查询字符串
Query query = parser.parse("key");
MultiFieldQueryParser parser2 = new MultiFieldQueryParser(Version.LUCENE_43, fields, analyzer);
Query query2 = parser2.parse(key);
TermQuery tq=new TermQuery(new Term(field, key));
PrefixQuery只需要指定前缀若干个字符preStr,以preStr开始的都会被匹配,比如”Lu”可以匹配”Luke” ,”Lucene”.
PrefixQuery prefixQuery=new PrefixQuery(new Term("field,key));
PhraseQuery phraseQuery=new PhraseQuery();
phraseQuery.setSlop(3);//关键词间距离
phraseQuery.add(new Term(field, "key1"));//关键词1
phraseQuery.add(new Term(field, "key2"));//关键词2
上面的查询实例可以匹配关键词key1和key2间距不超过3的文档,field为查询域。
WildcardQuery wildcardQuery=new WildcardQuery(new Term(field, "基于?"));
?匹配1个字符,*匹配任意多个字符.
TermRangeQuery rangeQuery=new TermRangeQuery(field, lowerTerm, upperTerm, includeLower, includeUpper);
五个参数分别为域名、域的下限值、域的上限值、是否包含下限、是否包含上限。比如:
TermRangeQuery rangeQuery=new TermRangeQuery(field, "aab", "azz", true, false);
Query q = NumericRangeQuery.newFloatRange("weight", 0.03f, 0.10f, true, true);
matches all documents whose float valued “weight” field ranges from 0.03 to 0.10, inclusive.
多个query对象组合成一个对象
BooleanQuery bQuery=new BooleanQuery();
bQuery.add(new TermQuery(new Term("title", "lucene")), Occur.MUST);
bQuery.add(new TermQuery(new Term("content", "基于")), Occur.SHOULD);
bQuery.add(new TermQuery(new Term("name", "java")), Occur.MUST_NOT);
上面的例子用于查询title中一定包含”lucene”(and)或者cotent包含”基于”(or)但name中一定不含” java”(not)的文档。