在某些需求场景下,我们可能需要禁用模糊查询 FuzzyQuery 和通配符查询 WildcardQuery,那通过 QueryParser 该怎么做呢?
答案就是重写 QueryParser 类。实现自己的 QueryParser 类,并将 getFuzzyQuery 方法和 getWildcardQuery 方法重写,抛出禁用的异常即可。
前面我们说过 FuzzyQuery 类可以实现搜索类似项的需求,WildcardQuery 类支持通配符查询。
@Test
public void testFuzzyQuery() throws IOException, ParseException {
//注意是区分大小写的,同时默认的编辑距离的值是2
//注意两个Term之间的编辑距离必须小于两者中最小者的长度:the edit distance between the terms must be less than the minimum length term
Query query = new FuzzyQuery(new Term("city", "Veni"));
IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(directory));
TopDocs search = indexSearcher.search(query, 10);
Assert.assertEquals(1, search.totalHits);
}
@Test
public void testWildcardQuery() throws IOException {
//*代表0个或者多个字母
Query query = new WildcardQuery(new Term("content", "*dam"));
IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(directory));
TopDocs search = indexSearcher.search(query, 10);
Assert.assertEquals(1, search.totalHits);
//?代表0个或者1个字母
query = new WildcardQuery(new Term("content", "?ridges"));
search = indexSearcher.search(query, 10);
Assert.assertEquals(2, search.totalHits);
query = new WildcardQuery(new Term("content", "b*s"));
search = indexSearcher.search(query, 10);
Assert.assertEquals(2, search.totalHits);
}
如果我现在要禁用它们,那么只需要按照下面的方法重写 getWildcardQuery 和 getFuzzyQuery 方法即可。
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Query;
/**
* Description:禁用模糊查询和通配符查询,同样的如果希望禁用其它类型查询,只需要覆写对应的getXXXQuery方法即可
*/
public class CustomQueryParser extends QueryParser {
public CustomQueryParser(String f, Analyzer a) {
super(f, a);
}
@Override
protected Query getFuzzyQuery(String field, String termStr, float minSimilarity) throws ParseException {
throw new ParseException("Fuzzy queries not allowed!");
}
@Override
protected Query getWildcardQuery(String field, String termStr) throws ParseException {
throw new ParseException("Wildcard queries not allowed!");
}
public static void main(String args[]) throws ParseException {
CustomQueryParser customQueryParser = new CustomQueryParser("filed", new WhitespaceAnalyzer());
customQueryParser.parse("a?t");
customQueryParser.parse("junit~");
}
}
这样就可以达到禁用模糊查询和通配符查询的功能了。

: » Lucene 实战教程第十三章禁用模糊查询 FuzzyQuery 和通配符查询 WildcardQuery
原创文章,作者:bd101bd101,如若转载,请注明出处:https://blog.ytso.com/tech/java/251970.html