官术网_书友最值得收藏!

Obtaining an IndexSearcher

Having reviewed the indexing cycle in Lucene, let's now turn our attention towards search. Keep in mind that indexing is a necessary evil you have to go through to make your text searchable. We take all the pain to customize a search engine now, so we can obtain good search experiences for the users. This will be well worth the effort when users can find information quickly and seamlessly. A well-tuned search engine is the key to every search application.

Consider a simple search scenario where we have an index built already. User is doing research on Lucene and wants to find all Lucene-related documents. Naturally, the term Lucene will be used in a search query. Note that Lucene leverages an inverted index (see the preceding image). Lucene can now locate documents quickly by stepping into the term Lucene in the index, and returning all the related documents by their DocIds. A term in Lucene contains two elements—the value and field in which the term occurs.

How do we specifically perform a search? We create a Query object. In simple terms, a query can be thought of as the communication with an index. This action is also referred to as querying an index. We issue a query to an index and get matched documents back.

The IndexSearcher class is the gateway to search an index as far as Lucene is concerned. An IndexSearcher takes an IndexReader object and performs a search via the reader. IndexReader talks to the index physically and returns the results. IndexSearcher executes a search by accepting a query object. Next, we will learn how to perform a search and create a Query object with a QueryParser. For now, let's take a look at how we can obtain an IndexSearcher.

How to do it...

Here is a code snippet that shows you how to obtain an IndexSearcher:

Directory directory = getDirectory();
IndexReader indexReader = DirectoryReader.open(directory);
IndexSearcher indexSearcher = new IndexSearcher(indexReader);

How it works…

The first line assumes we can gain access to a Directory object by calling getDirectory(). Then, we obtain an IndexReader by calling DirectoryReader.open(directory). The open method in DirectoryReader is a static method that opens an index to read, which is analogous to IndexWriter opening a directory to write. With an IndexReader initialized, we can instantiate an IndexSearcher with the reader.

主站蜘蛛池模板: 乌兰浩特市| 新营市| 当雄县| 珠海市| 大丰市| 邮箱| 玛曲县| 太仓市| 噶尔县| 紫金县| 绍兴市| 安达市| 精河县| 黄浦区| 历史| 郴州市| 旌德县| 思茅市| 凉山| 常山县| 班玛县| 浮梁县| 岐山县| 淮南市| 白朗县| 新蔡县| 新泰市| 邯郸市| 平山县| 邵东县| 上犹县| 肥西县| 海晏县| 菏泽市| 措勤县| 绥中县| 长垣县| 保山市| 台州市| 闵行区| 凤冈县|