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

  • Lucene 4 Cookbook
  • Edwood Ng Vineeth Mohan
  • 392字
  • 2021-07-16 14:07:49

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.

主站蜘蛛池模板: 宜昌市| 仙桃市| 蕉岭县| 鄂尔多斯市| 巴青县| 普兰店市| 遂平县| 常州市| 天长市| 伊川县| 商都县| 颍上县| 固原市| 康定县| 济南市| 平果县| 临清市| 延吉市| 托克托县| 伊通| 肇州县| 江口县| 霍林郭勒市| 始兴县| 台北县| 鹤岗市| 长丰县| 米泉市| 孝感市| 盐池县| 潜山县| 涿鹿县| 平和县| 龙州县| 隆尧县| 全州县| 大渡口区| 吉安市| 丰镇市| 乌鲁木齐市| 中牟县|