package player.kent.chen.temp.lucene.miscquery; import java.io.IOException; public class MyLuceneMiscQueryDemo { public static void main(String[] args) throws Exception { //创建index writer对象 Directory indexDir = new RAMDirectory(); IndexWriter indexWriter = new IndexWriter(indexDir, new StandardAnalyzer(Version.LUCENE_30), IndexWriter.MaxFieldLength.UNLIMITED); String text1 = "adam"; Document doc1 = new Document(); doc1.add(new Field("content", text1, Field.Store.YES, Field.Index.ANALYZED)); indexWriter.addDocument(doc1); String text2 = "brings"; Document doc2 = new Document(); doc2.add(new Field("content", text2, Field.Store.YES, Field.Index.ANALYZED)); indexWriter.addDocument(doc2); String text3 = "cups"; Document doc3 = new Document(); doc3.add(new Field("content", text3, Field.Store.YES, Field.Index.ANALYZED)); indexWriter.addDocument(doc3); IndexSearcher indexSearcher = new IndexSearcher(indexWriter.getReader()); //term query doSearch(indexSearcher, new TermQuery(new Term("content", "adam"))); //命中admin //term range query doSearch(indexSearcher, new TermRangeQuery("content", "b", "c", true, true)); //命中adam, brings; 按字典序cups > c, 所以cups不会被命中 //prefix query doSearch(indexSearcher, new PrefixQuery(new Term("content", "b"))); //命中brings //wildcard query doSearch(indexSearcher, new WildcardQuery(new Term("content", "c*s"))); //命中cups //fuzzy query doSearch(indexSearcher, new FuzzyQuery(new Term("content", "caps"))); //命中cups doSearch(indexSearcher, new FuzzyQuery(new Term("content", "csp"))); //无命中 indexSearcher.close(); indexWriter.close(); } private static void doSearch(IndexSearcher indexSearcher, Query query) throws IOException { System.out.println("========================================"); System.out.println("The query is : " + query); TopDocs searchResult = indexSearcher.search(query, 10); System.out.println(MessageFormat.format("Found {0} matches", searchResult.totalHits)); System.out.println("They are:"); printResult(indexSearcher, searchResult); } private static void printResult(IndexSearcher indexSearcher, TopDocs result) throws CorruptIndexException, IOException { for (ScoreDoc scoreDoc : result.scoreDocs) { Document doc = indexSearcher.doc(scoreDoc.doc); System.out.println(doc.get("content")); } } }