The previous article learned how to build an index. This article is also a basic usage for indexing.
Preparations
References
1) http://lucene.apache.org/core/4_9_0/demo/src-html/org/apache/lucene/demo/SearchFiles.html
Dependent jar package
The jar package in the searchfile of Lucene practice can be used in the previous article.
Main classes
1) indexreader reads the index file
2) indexsearcher: the Core class executes the search
3) queryparser, used to parse user query words
4) analyzer, word divider, preferably the same as building an index
Knife Test
Searchfile
1 package Lucene; 2 3 Import Java. io. file; 4 Import Java. io. ioexception; 5 6 Import Org. apache. lucene. analysis. analyzer; 7 Import Org. apache. lucene. analysis. standard. standardanalyzer; 8 Import org.apache.e.doc ument. document; 9 Import Org. apache. lucene. index. directoryreader; 10 Import Org. apache. lucene. index. indexreader; 11 import Org. apache. lucene. queryparser. classic. parseexception; 12 Import Org. apache. lucene. queryparser. classic. queryparser; 13 Import Org. apache. lucene. search. indexsearcher; 14 Import Org. apache. lucene. search. query; 15 Import Org. apache. lucene. search. scoredoc; 16 Import Org. apache. lucene. search. topdocs; 17 import Org. apache. lucene. store. fsdirectory; 18 Import Org. apache. lucene. util. version; 19 20 public class searcher {21 public static indexsearcher; 22 public static void search (string index, string querystr) throws ioexception, parseexception {23 long start = system. currenttimemillis (); 24 indexreader = directoryreader. open (fsdirectory. open (new file (INDEX); // read index 25 indexsearcher = new indexsearcher (indexreader); 26 analyzer anlyzer = new standardanalyzer (version. required e_46); // analyzer 27 queryparser parser = new queryparser (version. required e_46, "content", anlyzer); // resolution query, "content" specifies the query field 28 query = parser. parse (querystr); 29 topdocs Results = indexsearcher. search (query, 10); // returns 10 Results 30 scoredoc [] hits = results. scoredocs; 31 int totalhits = results. totalhits; 32 for (INT I = 0; I <totalhits; I ++) {33 document DOC = indexsearcher.doc(hits~ I }.doc); 34 system. out. println ("[" + Doc. get ("name") + "]" + Doc. get ("path"); 35 system. out. println (); 36} 37 long end = system. currenttimemillis (); 38 system. out. println ("found" + totalhits + "results, time consumed:" + (end-Start) + "Ms "); 39} 40 public static void main (string [] ARGs) throws ioexception, parseexception {41 search ("E:/data/Index", "never"); 42} 43}
Result Display
Export nevergrowold.txt] E: \ data \ data2 \ nevergrowold.txt found 1 result in 143 Ms