通配符搜索
Lucene支持單一條款範圍內的單個和多個字符通配符搜索(未內短語查詢)。
要執行單字符通配符檢索,可用「?」符號。
要進行多字符通配符搜索使用「*」符號。
單字符通配符搜索查找匹配以單個字符替換了條件。例如,要搜索「文本」或「測試」,可以使用以下搜索:
te?t 多字符通配符搜索查找0個或更多個字符。例如,要搜索測試,測試或測試儀,你可以使用搜索:
測試*
例如,使用正則表達式
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"));
}
你可以看到我的帖子更新,並運行示例? – jrey