import org.apache.lucene.search.PhraseQuery; //导入方法依赖的package包/类
public static BooleanQuery buildQuery(String text, String field) throws IOException {
BooleanQuery fullQuery = new BooleanQuery();
TokenStream tokStream = ANALYZER.tokenStream(field, text);
try {
tokStream.reset();
Term lastTerm = null;
while (tokStream.incrementToken()) {
String termStr = tokStream.getAttribute(CharTermAttribute.class).toString();
Term term = new Term(field, termStr);
TermQuery termQuery = new TermQuery(term);
termQuery.setBoost(0.8f);
fullQuery.add(termQuery, BooleanClause.Occur.SHOULD);
List expansionWords = WordNetExpansion.getStrictExpansion(termStr);
if (expansionWords != null) {
for (String expTermStr : expansionWords) {
TermQuery expTermQuery = new TermQuery(new Term(field, expTermStr));
expTermQuery.setBoost(0.4f);
fullQuery.add(expTermQuery, BooleanClause.Occur.SHOULD);
}
}
if (lastTerm != null) {
PhraseQuery bigram = new PhraseQuery();
bigram.add(lastTerm);
bigram.add(term);
bigram.setBoost(0.1f);
fullQuery.add(bigram, BooleanClause.Occur.SHOULD);
if (USE_PROXIMITY_QUERY) {
SpanNearQuery spanNearQuery = new SpanNearQuery(new SpanQuery[]{
new SpanTermQuery(lastTerm),
new SpanTermQuery(term)},
6,
false);
spanNearQuery.setBoost(0.1f);
fullQuery.add(spanNearQuery, BooleanClause.Occur.SHOULD);
}
}
lastTerm = term;
}
tokStream.end();
} finally {
tokStream.close();
}
return fullQuery;
}