Lucene quickstart-Basic Search

Source: Internet
Author: User

With the previous index established, you can retrieve it.

The database query uses Sql,lucene retrieval to use query.

Lucene provides a Indexsearcher class that retrieves the functionality that is accomplished by this class, which requires a Indexreader object for its construction method. Indexreader is used to read index library directory.

Indexsearcher has many refactoring methods in which the return value is the simplest of the Topdocs type. This article uses this method for demonstration purposes. Topdocs saves the results of the search, where the Scoredocs attribute holds the recorded docid and scores, and the corresponding records can be obtained according to the DocId.

As already known in the previous article to initialize the directory object requires the path of the index library, we provide a searcher class that simplifies the operation of the index.

The pseudo code is as follows:

public class searcher {    /**     *  Search       *      *  @param  indexDir      *             Index Store Directory       *  @param  query     *              search Conditions      *  @param  n      *             returns the number of results       *  @return      *  @throws  exception     * /    public list<document> search (string indexdir, query  Query, int n)  throws Exception {         Create a directory object;         Create Indexreader Object;         Create Indexsearcher Objects;         use Indexsearcher objects for retrieval;     }}

The implementation code is as follows:

Package cn.lym.lucene.quickstart.search;import java.io.file;import java.util.arraylist;import  java.util.List;import org.apache.log4j.LogManager;import org.apache.log4j.Logger;import  org.apache.lucene.document.document;import org.apache.lucene.index.directoryreader;import  org.apache.lucene.index.indexreader;import org.apache.lucene.search.indexsearcher;import  org.apache.lucene.search.query;import org.apache.lucene.search.scoredoc;import  org.apache.lucene.search.topdocs;import org.apache.lucene.store.directory;import  org.apache.lucene.store.fsdirectory;/** *  provides retrieval of classes  *  *  @author  liuyimin  * */public class Searcher {    /**      * logger     */    private static final  Logger logger = logmanager.getlogger (searcher.class);     /**     *  Search      *       *  @param  indexDir     *              Index Store directory      *  @param  query      *             Search Conditions       *  @param  n     *              returns the number of results      *  @return       *  @throws  exception     */    public list <document> search (string indexdir, query query, int n)  throws  exception {        if  (logger.isdebugenabled ())  {       &nbsP;     logger.debug ("search "  + indexDir +  "for"  +  n +  " documents, with query: "  + query);         }        Directory directory =  Fsdirectory.open (New file (indexdir));        indexreader  Reader = directoryreader.open (directory);         Indexsearcher searcher = new indexsearcher (reader);         topdocs topdocs = searcher.search (query, n);         ScoreDoc[] scoreDocs = topDocs.scoreDocs;         if  (logger.isdebugenabled ())  {             logger.debug ("Totally  " + scoreDocs.length + "  documents hit. ");         }        List< Document> documents = new arraylist<> (scoredocs.length);         for  (Scoredoc scoredoc : scoredocs)  {             documents.add (Searcher.doc (scoredoc.doc));         }        return documents;     }}

Write unit tests according to the requirements of the previous article.

Package cn.lym.lucene.quickstart.search;import static org.junit.assert.assertequals;import  static org.junit.assert.asserttrue;import java.util.date;import java.util.list;import  org.apache.lucene.document.Document;import org.apache.lucene.index.Term;import  org.apache.lucene.search.numericrangequery;import org.apache.lucene.search.query;import  Org.apache.lucene.search.termquery;import org.junit.before;import org.junit.test;public class  SearcherTest {    /**     *  Index Store Directory       */    private static final string indexdir =   "e:\\documents\\lucene-quickstart\\";    private searcher searcher;      @Before     public void init ()  {         this.searcher = new&nbsP Searcher ();    }    /**     *  search files by file name      */     @Test     public void  Testsearchwithfilename ()  throws exception {        //   Search file name is jdk-8u60-windows-x64.exe        query query =  new termquery (new term ("filename",  "Jdk-8u60-windows-x64.exe");         int n = 10;        List< Document> documents = this.searcher.search (indexdir, query, n);         system.out.println (Documents.size ()  +  " documents hit.");         for  (document document : documents)  {     &nbSp;       system.out.println (document);         }        assertequals (1, documents.size ());     }    /**     *  Search files by file type       */     @Test     public void  Testsearchwithfiletype ()  throws exception {        //   Search for files of file type EXE         Query query = new  Termquery (New term ("type",  "EXE"));         int n =  integer.max_value;        list<document> documents  = this.searcher.search (indexdir, query, n);         system.out.println (Documents.size ()  +  "  documents hit. ");         asserttrue (Documents.size ()  > 0);     }    /**     *  Search files by file type       */     @Test     public void testsearchwithfiletype2 ()  throws Exception {        //  Search for files of file type EXE          query query = new termquery (New Term ("type" ,  "TXT");        int n = integer.max_value;         list<document> documents = this.searcher.search (indexdir, query, n);         system.out.println ( Documents.size ()  +  " documents hit.");         for  (document document : documents)  {             system.out.println (Document.get ("pathname"));         }        asserttrue (Documents.size ()  >  0);    }    /**     *  search files by file size       */     @Test     public void  Testsearchwithfilesize ()  throws exception {        //   Search files with a file size of 195,200,088 bytes (jdk-8u60-windows-x64.exe)         long  size = 195_200_088l;        query query =  numericrangequery.newlongrange ("size",  size, size, true, true);         int n = 10;        list<document> documents =  This.searcher.search (indexdir, query, n);         System.out.println (Documents.size ()  +  " documents hit.");         for  (document document : documents)  {             system.out.println (document);         }        assertequals (1,  documents.size ());     }    /**     *   Search files by file size      */     @Test     public  void testsearchwithfilesize2 ()  throws Exception {         //  search file size between 1024~2048 bytes     &Nbsp;   long min = 1024l;        long  max = 2048L;        Query query =  Numericrangequery.newlongrange ("size",  min, max, true, true);         int n = 10;        List< Document> documents = this.searcher.search (indexdir, query, n);         system.out.println (Documents.size ()  +  " documents hit.");         for  (document document : documents)  {             system.out.println (document);         }        asserttrue ( Documents.size ()  > 0);     }    /**     *  search files by file size       */     @Test     public void  TestSearchWithFileSize3 ()  throws exception {        //   Search file size less than 1024 bytes of file         Long min = null;         Long max = 1024L;         query query = numericrangequery.newlongrange ("Size",  min, max, true,  true);        int n = 10;         list<document> documents = this.searcher.search (indexDir,  Query, n);         system.out.println (Documents.size ()  +   " documents hit.");         for  (document document : documents)  {             system.out.println (document);         }        asserttrue (documents.size ()  > 0);    }    /**     *  Search files by file size      */     @Test     public void  testsearchwithfilesize4 ()  throws Exception {         //  search files with file size greater than 1024 * 1024 * 1024 bytes          Long min = 1024 * 1024 * 1024L;         long max = null;        query query  = numericrangeQuery.newlongrange ("size",  min, max, true, true);         int n = 10;        List<Document>  documents = this.searcher.search (indexdir, query, n);         system.out.println (Documents.size ()  +  " documents hit.");         for  (document document : documents)  {             system.out.println (document);         }        asserttrue ( Documents.size ()  > 0);    }    /**      *  Search files by file modification date      */     @Test      public void testsearchwithmodifiedtiMe ()  throws Exception {        //  Search for files modified in the last week         long max = new date (). GetTime ();         long min = max - 7 * 24 *  3600 * 1000L;        Query query =  Numericrangequery.newlongrange ("LastModified",  min, max, true, true);         int n = 10;        list <document> documents = this.searcher.search (indexdir, query, n);         system.out.println (Documents.size ()  +  " documents hit.");         for  (document document : documents)  {      &Nbsp;      system.out.println (document);         }        asserttrue (Documents.size ()  > 0);     }    /**     *  search files by file contents       */     @Test     public void  Testsearchwithcontent ()  throws exception {        //   Search content contains success files         Query query = new  Termquery (New term ("Content",  "success");         int n  = Integer.MAX_VALUE;        List<Document>  Documents = this.searcher.search (indexdir, query, n);         system.out.println (DOCUMENTS.SIze ()  +  " documents hit.");         for  (document document : documents)  {             system.out.println (Document.get (" Pathname "));        }         Asserttrue (Documents.size ()  > 0);     }}

A few points to note:

    1. About query. Query has several seed classes:

      1. Equivalent query: Termquery. Filenames, file paths, file types, and file contents all belong to this.

      2. Scope query: Numericrangequery. File size, modification time belongs to this. Numericrangequery is created from a static factory method, with several parameters: field name, minimum value, maximum value, whether the minimum value is included, and whether the maximum value is included. The maximum value, the minimum value, or null, indicates infinity and infinity.

    2. About retrieving the result document object. We can get the stored option set to the stored field from the Document object, through the Get (String name) method , when the index is built. When an attempt is made to obtain a value for a non-stored field, NULL is returned.


This article code can be obtained from Https://git.oschina.net/coding4j/lucene-quickstart.

Lucene quickstart-Basic Search

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.