The following describes how Lucene performs search. Compared with indexing, searching may be more interesting.
Lucene's main search API
The following table shows the main search APIs used by Lucene.
| Class |
Purpose |
| Indexseacher |
Search operation entry. All search operations are implemented through the indexseacher instance using an overloaded search method. |
| Query (and its subclass) |
The specific query subclass encapsulates each specific type of query logically. The query instance is passed to the search method of indexsearcher. |
| Queryparser |
Process the (and readable) query expression entered by the user as a specific query object. |
| Topdocs |
Keep the top document with a high score returned by indexsearcher. Search () |
| Scoredoc |
Provides access interfaces for each search result in topdocs |
Search for specific items
Here, indexsearcher is the core class for searching documents in the index. In the following example, we will index the subject domain and use the query subclass termquery.
The test procedure is as follows:
View code
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); //C10 11 t = new Term("subject", "junit");12 docs = searcher.search(new TermQuery(t), 10);13 assertEquals("Ant in Action, " + //D14 "JUnit in Action, Second Edition", //D15 2, docs.totalHits); //D16 17 searcher.close();18 dir.close();19 }
Of course, under different circumstances, you can change the code to search for what you want.
Parse user query
To parse a user's query in Lucene, a query object must be used as a parameter. That is to say, the expression is combined into a query. There is an object called queryparser, which parses the previously passed rule into an object and then queries it. Next, let's take a look at how the process is handled:
Figure: queryparser object processing of complex expressions
The following is a program example. It is based on Lucene 3.0 and will be changed in later versions.
The program structure is as follows:
View code
1 public void testQueryParser() throws Exception {
2 Directory dir = TestUtil.getBookInd