通配符搜索
Lucene 支持在单个词中(不是在短语查询中)的单个和多个字符通配符搜索。
要执行单个字符通配符搜索,请使用“?” 象征。
要执行多字符通配符搜索,请使用“*”符号。
单字符通配符搜索查找与替换的单字符匹配的术语。例如,要搜索“text”或“test”,您可以使用以下搜索:
te?t 多字符通配符搜索查找 0 个或更多字符。例如,要搜索 test、tests 或 tester,您可以使用搜索:
测试*
例如,使用正则表达式
RegexQuery query = new RegexQuery(newTerm("^a.*$"));
query.setRegexImplementation(new JavaUtilRegexCapabilities());
return searcher.search(query, null, 1000).totalHits;
http://lucene.apache.org/core/4_3_1/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package_description
示例代码:
BasicConfigurator.configure();
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
// Store the index in memory:
Directory directory = new RAMDirectory();
// To store an index on disk, use this instead:
// Directory directory = FSDirectory.open(new
// File("./lucene/data"));
IndexWriterConfig config = new IndexWriterConfig(
Version.LUCENE_CURRENT, analyzer);
IndexWriter iwriter;
iwriter = new IndexWriter(directory, config);
String[] words = { "Olimpia", "Cerro", "Olimpo", "Libertad",
"Nacional", "Sol", "O'higgins", "Sao Paulo",
"Oriente Petrolero", "Barrio Obrero", "B. Obrero" };
for (String word : words) {
Document doc = new Document();
String text = word;
doc.add(new Field("name", text, Field.Store.YES,
Field.Index.NOT_ANALYZED));
// ,Field.Store.NO, Field.Index.NOT_ANALYZED
iwriter.addDocument(doc);
}
iwriter.close();
// Now search the index:
logger.info("HelloLucene.main: query2 -----------");
DirectoryReader ireader2 = DirectoryReader.open(directory);
IndexSearcher isearcher2 = new IndexSearcher(ireader2);
logger.info("HelloLucene.main: query2 -----------");
RegexQuery query2 = new RegexQuery(new Term("name", "O.*"));
query2.setRegexImplementation(new JavaUtilRegexCapabilities(
JavaUtilRegexCapabilities.FLAG_CASE_INSENSITIVE));
ScoreDoc[] hits2 = isearcher2.search(query2, null, 1000).scoreDocs;
for (int i = 0; i < hits2.length; i++) {
Document hitDoc = isearcher2.doc(hits2[i].doc);
logger.info("HelloLucene.main: starting with O = "
+ hitDoc.get("name"));
}