下面說的主要是lucene如何進行搜索,相比於建索引,搜索可能更能提起大家的興趣。
lucene的主要搜索的API
下面通過表格來看一下lucene用到的主要的搜索API
類 | 目的 |
IndexSeacher | 搜索操作的入口,所有搜索操作都是通過IndexSeacher實例使用一個重載的search方法來實現 |
Query(及其子類) | 具體的Query子類為每一種特定類型的查詢進行邏輯上的封裝。Query實例被傳遞到IndexSearcher的search方法中 |
QueryParser | 將用戶輸入的(並且可讀的)查詢表達式處理為一個具體的Query對象 |
TopDocs | 保持由IndexSearcher.search()方法返回的具有較高評分的頂部文檔 |
ScoreDoc | 提供對TopDocs中每條搜索結果的訪問接口 |
對特定項進行搜索
其中IndexSearcher是對索引中文檔進行搜索的核心類,我們下面的例子中就會對subject域進行索引,使用的是Query的子類TermQuery。
測試程序如下:

1 public void testTerm() throws Exception { 2 Directory dir = TestUtil.getBookIndexDirectory(); //A 3 IndexSearcher searcher = new IndexSearcher(dir); //B 4 5 Term t = new Term("subject", "ant"); 6 Query query = new TermQuery(t); 7 TopDocs docs = searcher.search(query, 10); 8 assertEquals("Ant in Action", //C 9 1, docs.totalHits); //C 10 11 t = new Term("subject", "junit"); 12 docs = searcher.search(new TermQuery(t), 10); 13 assertEquals("Ant in Action, " + //D 14 "JUnit in Action, Second Edition", //D 15 2, docs.totalHits); //D 16 17 searcher.close(); 18 dir.close(); 19 }
當然在不同的情況下你可以改變其中的代碼來搜索你想要的東西。
解析用戶查詢
lucene中解析用戶的查詢需要一個Query對象作為參數。那么也就是將Expression組合成Query的過程,這里邊有一個對象叫QueryParser,它將前面傳過來的規則的解析成對象然后進行查詢。下面我們看下流程是如何處理的:
圖:QueryParser對象處理復雜的表達式的過程
下面看一個程序示例,這個是基於lucene 3.0的,在后面的版本中會有所變化。
程序結構如下:

1 public void testQueryParser() throws Exception { 2 Directory dir = TestUtil.getBookIndexDirectory(); 3 IndexSearcher searcher = new IndexSearcher(dir); 4 5 QueryParser parser = new QueryParser(Version.LUCENE_30, //A 6 "contents", //A 7 new SimpleAnalyzer()); //A 8 9 Query query = parser.parse("+JUNIT +ANT -MOCK"); //B 10 TopDocs docs = searcher.search(query, 10); 11 assertEquals(1, docs.totalHits); 12 Document d = searcher.doc(docs.scoreDocs[0].doc); 13 assertEquals("Ant in Action", d.get("title")); 14 15 query = parser.parse("mock OR junit"); //B 16 docs = searcher.search(query, 10); 17 assertEquals("Ant in Action, " + 18 "JUnit in Action, Second Edition", 19 2, docs.totalHits); 20 21 searcher.close(); 22 dir.close(); 23 }
其實主要就是A和B兩部分,將規則解析成lucene能識別的表達式。
下面的表格中列出了查詢表達式的范例:
表達式 | 匹配文檔 |
java | 在字段中包含java |
java junit java or junit |
在字段中包含java或者junit |
+java +junit java and junit |
在字段中包含java以及junit |
title:ant | 在title字段中包含ant |
title:extreme -subject:sports title:extreme AND NOT subject:sports |
在title字段中包含extreme並且在subject字段中不能包含sports |
(agile OR extreme) AND methodology | 在字段中包含methodology並且同時包括agile或者extreme |
title:"junit in action" | 在title字段中包含junit in action |
title:"junit action"~5 | 包含5次junit和action |
java* | 包含以java開頭的,例如:javaspaces,javaserver |
java~ | 包含和java相似的,如lava |
lastmodified:[1/1/04 TO 12/31/04] | 在lastmodified字段中值為2004-01-01到2004-12-31中間的 |
接下來測試一下QueryParser的各個表達式,程序結構如下:

1 public class TestQueryParser { 2 3 public static void main(String[] args) throws Exception { 4 5 String[] id = { "1", "2", "3" }; 6 String[] contents = { "java and lucene is good", 7 "I had study java and jbpm", 8 "I want to study java,hadoop and hbase" }; 9 10 Directory directory = new RAMDirectory(); 11 IndexWriter indexWriter = new IndexWriter(directory, 12 new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer( 13 Version.LUCENE_36))); 14 for (int i = 0; i < id.length; i++) { 15 Document document = new Document(); 16 document.add(new Field("id", id[i], Field.Store.YES, 17 Field.Index.ANALYZED)); 18 document.add(new Field("contents", contents[i], Field.Store.YES, 19 Field.Index.ANALYZED)); 20 indexWriter.addDocument(document); 21 } 22 indexWriter.close(); 23 24 System.out.println("String is :java"); 25 search(directory, "java"); 26 27 System.out.println("\nString is :lucene"); 28 search(directory, "lucene"); 29 30 System.out.println("\nString is :+java +jbpm"); 31 search(directory, "+java +jbpm"); 32 33 System.out.println("\nString is :+java -jbpm"); 34 search(directory, "+java -jbpm"); 35 36 System.out.println("\nString is :java jbpm"); 37 search(directory, "java jbpm"); 38 39 System.out.println("\nString is :java AND jbpm"); 40 search(directory, "java AND jbpm"); 41 42 System.out.println("\nString is :java or jbpm"); 43 search(directory, "java or jbpm"); 44 } 45 46 public static void search(Directory directory, String str) throws Exception { 47 IndexSearcher indexSearcher = new IndexSearcher(directory); 48 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_34); 49 QueryParser queryParser = new QueryParser(Version.LUCENE_34, 50 "contents", analyzer); 51 Query query = queryParser.parse(str); 52 TopDocs topDocs = indexSearcher.search(query, 10); 53 ScoreDoc[] scoreDoc = topDocs.scoreDocs; 54 for (int i = 0; i < scoreDoc.length; i++) { 55 Document doc = indexSearcher.doc(scoreDoc[i].doc); 56 System.out.println(doc.get("id") + " " + doc.get("contents")); 57 } 58 indexSearcher.close(); 59 } 60 }
運行程序就會得到輸出結果。
搜索用到的各個類的相互關系
我想看圖應該會比較清晰,下面的圖比較清晰的組合了程序的結構:
圖:搜索用到的各個類的相互關系
搜索結果分頁
其實這個所謂的分頁跟數據庫的分頁功能差不多,只是一個是從數據庫中讀取數據,而一個是從索引文件中找到對應的數據。
在lucene搜索分頁過程中,可以有兩種方式:
- 一種是將搜索結果集直接放到session中,但是假如結果集非常大,同時又存在大並發訪問的時候,很可能造成服務器的內存不足,而使服務器宕機
- 還有一種是每次都重新進行搜索,這樣雖然避免了內存溢出的可能,但是,每次搜索都要進行一次IO操作,如果大並發訪問的時候,你要保證你的硬盤的轉速足夠的快,還要保證你的cpu有足夠高的頻率
而我們可以將這兩種方式結合下,每次查詢都多緩存一部分的結果集,翻頁的時候看看所查詢的內容是不是在已經存在在緩存當中,如果已經存在了就直接拿出來,如果不存在,就進行查詢后,從緩存中讀出來。比如:現在我們有一個搜索結果集 一個有100條數據,每頁顯示10條,就有10頁數據。按照第一種的思路就是,我直接把這100條數據緩存起來,每次翻頁時從緩存種讀取而第二種思路就是,我直接從搜索到的結果集種顯示前十條給第一頁顯示,第二頁的時候,我在查詢一次,給出10-20條數據給第二頁顯示,我每次翻頁都要重新查詢。
第三種思路就變成了
我第一頁僅需要10條數據,但是我一次讀出來50條數據,把這50條數據放入到緩存當中,當我需要10--20之 間的數據的時候,我的發現我的這些數據已經在我的緩存種存在了,我就直接存緩存中把數據讀出來,少了一次查詢,速度自然也提高了很多. 如果我訪問第六頁的數據,我就把我的緩存更新一次.這樣連續翻頁10次才進行兩次IO操作同時又保證了內存不容易被溢出.而具體緩存設置多少,要看你的服務器的能力和訪問的人數來決定。
下面是一個示例程序沒有做緩存,緩存的部分可以自己實現,也可以選擇ehcache等開源的實現。
程序結構如下:

1 public class TestPagation { 2 3 public void paginationQuery(String keyWord, int pageSize, int currentPage) 4 throws ParseException, CorruptIndexException, IOException { 5 String[] fields = { "title", "content" }; 6 // 創建一個分詞器,和創建索引時用的分詞器要一致 7 Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36); 8 9 QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_36, 10 fields, analyzer); 11 Query query = queryParser.parse(keyWord); 12 13 // 打開索引目錄 14 File indexDir = new File("./indexDir"); 15 Directory directory = FSDirectory.open(indexDir); 16 17 IndexReader indexReader = IndexReader.open(directory); 18 IndexSearcher indexSearcher = new IndexSearcher(indexReader); 19 20 // TopDocs 搜索返回的結果 21 TopDocs topDocs = indexSearcher.search(query, 100);// 只返回前100條記錄 22 int totalCount = topDocs.totalHits; // 搜索結果總數量 23 ScoreDoc[] scoreDocs = topDocs.scoreDocs; // 搜索返回的結果集合 24 25 // 查詢起始記錄位置 26 int begin = pageSize * (currentPage - 1); 27 // 查詢終止記錄位置 28 int end = Math.min(begin + pageSize, scoreDocs.length); 29 30 // 進行分頁查詢 31 for (int i = begin; i < end; i++) { 32 int docID = scoreDocs[i].doc; 33 Document doc = indexSearcher.doc(docID); 34 int id = NumericUtils.prefixCodedToInt(doc.get("id")); 35 String title = doc.get("title"); 36 System.out.println("id is : " + id); 37 System.out.println("title is : " + title); 38 } 39 40 } 41 42 public static void main(String[] args) throws CorruptIndexException, ParseException, IOException { 43 TestPagation t = new TestPagation(); 44 //每頁顯示5條記錄,顯示第三頁的記錄 45 t.paginationQuery("RUNNING",5,3); 46 } 47 48 }