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

  • 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.

主站蜘蛛池模板: 凤翔县| 嘉峪关市| 沅江市| 嘉峪关市| 郴州市| 抚顺县| 西贡区| 鹤山市| 米林县| 上高县| 黄浦区| 甘洛县| 湛江市| 林芝县| 阿拉尔市| 临西县| 凤凰县| 彭阳县| 镇江市| 竹溪县| 察隅县| 新疆| 五指山市| 清水河县| 彭山县| 东乡| 改则县| 白沙| 社会| 金平| 晴隆县| 昭觉县| 陆川县| 青铜峡市| 洛隆县| 大方县| 齐河县| 山东省| 彭泽县| 镇平县| 信丰县|