Lucene's Full Search example

Source: Internet
Author: User
Tags gettext gtk

1. Create an indexer:

Package Yushibujue;import Java.awt.borderlayout;import Java.awt.container;import java.awt.gridlayout;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.io.file;import java.io.IOException; Import Java.text.simpledateformat;import java.util.date;import Javax.swing.jbutton;import Javax.swing.JFileChooser ; Import Javax.swing.jframe;import javax.swing.jlabel;import javax.swing.joptionpane;import Javax.swing.JPanel; Import Javax.swing.jscrollpane;import Javax.swing.jtextarea;import Javax.swing.jtextfield;import Javax.swing.swingutilities;import Javax.swing.uimanager;import Org.apache.lucene.analysis.cjk.cjkanalyzer;import Org.apache.lucene.document.document;import Org.apache.lucene.document.field;import Org.apache.lucene.index.indexwriter;import Org.apache.lucene.index.indexwriterconfig;import Org.apache.lucene.store.simplefsdirectory;import Org.apache.lucene.util.version;import tool. Filelist;import tool. Filetext;public class Luceneindexer {private JTextField Jtfa Private JButton JBA; Private JTextField JTFB; Private JButton Jbb; Private JButton JBC;  private static JTextArea JTA;  Indexer appearance class private void Createandshowgui () {//Set cross-platform appearance sensation String lf=uimanager.getcrossplatformlookandfeelclassname ();  GTK appearance sensation//string lf= "Com.sun.java.swing.plaf.gtk.GTKLookAndFeel";  Sysetm appearance sensation//String lf=uimanager.getsystemlookandfeelclassname ();   Windows appearance sensation//String lf= "Com.sun.java.swing.plaf.WindowsLookAndFeel";  Metal appearance feeling//string lf= "Javax.swing.plaf.metal.MetalLookAndFeel";  Common use try{uimanager.setlookandfeel (LF); }catch (Exception e) {joptionpane.showmessagedialog (null, "Unable to set the appearance feeling!  "); } Java Sense jframe.setdefaultlookandfeeldecorated (true); JFrame frame=new JFrame ("Yushibujue");  Frame.setdefaultcloseoperation (Jframe.exit_on_close); Final JFileChooser fc=new JFileChooser ();  Fc.setfileselectionmode (jfilechooser.directories_only); Container Con=frame.getcontentpane ();  Con.setlayout (New BorderLayout ()); JPanel jpup=new JPanel (); jpup.seTlayout (New GridLayout (3,2)); Jtfa=new JTextField (30); Jba=new JButton ("Select the file path to be indexed"); Jba.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {int r=fc.showopend      Ialog (NULL);      if (r==jfilechooser.approve_option) {Jtfa.settext (Fc.getselectedfile (). GetPath ());      Jbc.setenabled (TRUE);  }      }      } ); Jtfb=new JTextField (30); JButton jbb=new JButton ("Storage path for select Index"); Jbb.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {int r= fc.showopendialog    (null);    if (r==jfilechooser.approve_option) {Jtfb.settext (Fc.getselectedfile (). GetPath ());    Jbc.setenabled (TRUE);  }    }        }  ); JLabel jl=new JLabel (""); Jbc=new JButton ("Build Index"); Jbc.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {try{Luceneindee    Rtool.index (Jtfa.gettext (), Jtfb.gettext ());    Jbc.setenabled (FALSE);    }catch (Exception ee) {ee.printstacktrace (); Jbc.sEtenabled (TRUE);    Joptionpane.showmessagedialog (NULL, "Index creation failed!");    System.out.println (Ee.getmessage ()); }    }    }  ); Jpup.add (JTFA); Jpup.add (JBA); Jpup.add (JTFB); Jpup.add (JBB); Jpup.add (JL);  Jpup.add (JBC); Jta=new JTextArea (10,60); JScrollPane jsp=new JScrollPane (JTA); Con.add (Jpup,borderlayout.north);  Con.add (Jsp,borderlayout.center); Frame.setsize (200,100); Frame.pack ();  Frame.setvisible (TRUE);    public static void Main (string[] args) {Swingutilities.invokelater (new Runnable () {public void run () {try{    New Luceneindexer (). Createandshowgui ();    }catch (Exception e) {joptionpane.showmessagedialog (NULL, "The program failed to load!"); }    }    });} Use the internal class Luceneindexertool to do the indexing work, so that the index can be set up to reflect the situation in the text box inside the static class luceneindeertool{//create an index, the path of the indexed file, the path of the index public static void index (String filespath,string indexpath) throws ioexception{//build indexer, I use lucene4.7 notation file Path=new file (Inde  XPath); Simplefsdirectory indexdir=new simplefsdirectory (path);//Read the indexed file directory Cjkanalyzer aNalyzer=new Cjkanalyzer (version.lucene_47);//Create a dichotomy Analyzer Indexwriterconfig conf=new indexwriterconfig (  VERSION.LUCENE_47, analyzer);  IndexWriter writer=new IndexWriter (indexdir,conf); /* Directory Dir=fsdirectory.open (new File (Indexpath)); Analyzer analyzer=new StandardAnalyzer (); Indexwriterconfig config=new Indexwriterconfig (Version.lucene_4_10_2,analyzer); IndexWriter writer=new IndexWriter (dir,config); *//recursive traversal of file directories to index String s[]=filelist.getfiles (Filespath); int len=s.length; for (int i=0;i<len;i++) {file F=new file (S[i]); String Ext=getext (f);//Gets the extension if (ext.equalsignorecase ("htm") | |  Ext.equalsignorecase ("html")) {document Doc=new document (); filename field String filename=f.getname (); Field field=new field ("FileName", filename,field.store.yes,field.index.analyzed);  Doc.add (field); Uri Field String Uri=f.getpath (); Field=new Field ("uri", uri,field.store.yes,field.index.no);  Doc.add (field); CDate Field Date Dt=new date (f.lastmodified ()); SimpleDateFormat sdf= New simpledAteformat ("Yyyy-mm-dd E"); String cdate=sdf.format (DT); Field=new Field ("CDate", cdate,field.store.yes,field.index.no);  Doc.add (field); Size field double si=f.length ();  String size= ""; if (si>1024) {size=string.valueof (Math.floor (si/1024) + "K");} else{size=string.valueof (SI) + "Bytes";} field=new field ("Size", size,field.store.yes,field.index.no);  Doc.add (field); Text field String Text=filetext.gettext (f); Field=new Field ("text", text,field.store.yes,field.index.analyzed);  Doc.add (field); Digest field String digest= "";  if (Text.length () >200) {digest=text.substring (0, 200);  }else{Digest=text;}     Field=new Field ("Digest", digest,field.store.yes,field.index.analyzed);           Doc.add (field);     Indexed writer.adddocument (DOC); Jta.settext (Jta.gettext () + "already indexed:" +f+ "\ n"); }}//Close indexer writer.close (); Joptionpane.showmessagedialog (NULL, "Indexing is complete!") "," hint ", joptionpane.information_message); } public static string Getext (File f) {string s=f.getname (); try{s=s.substring (s. LastIndexOf (".")  +1);  }catch (Exception e) {s= "";} return S; }    }                }

2. Create the Finder:

Package Yushibujue;import Java.awt.borderlayout;import Java.awt.container;import java.awt.flowlayout;import Java.awt.gridlayout;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.io.File; Import Java.io.filewriter;import java.io.ioexception;import Java.io.printwriter;import Javax.swing.JButton;import Javax.swing.jfilechooser;import Javax.swing.jframe;import Javax.swing.joptionpane;import Javax.swing.JPanel; Import Javax.swing.jscrollpane;import Javax.swing.jtextarea;import Javax.swing.jtextfield;import Javax.swing.swingutilities;import Javax.swing.uimanager;import Org.apache.lucene.document.document;import Org.apache.lucene.document.field;import Org.apache.lucene.index.directoryreader;import Org.apache.lucene.index.term;import Org.apache.lucene.search.indexsearcher;import Org.apache.lucene.search.scoredoc;import Org.apache.lucene.search.termquery;import Org.apache.lucene.search.topdocs;import Org.apache.lucene.store.fsdirectory;public class LuceneSearcher{Private JTextField JTFA;   Private JButton JBA;   Private JTextField JTFB;   Private JButton Jbb;   Private JButton JBC;   private static JTextArea JTA;   Private JTextField JTFC;   Private JButton JBD;      Private JButton Jbe;  private void Createandshowgui () {//Set cross-platform appearance sensation String lf=uimanager.getcrossplatformlookandfeelclassname ();  GTK appearance sensation//string lf= "Com.sun.java.swing.plaf.gtk.GTKLookAndFeel";  Sysetm appearance sensation//String lf=uimanager.getsystemlookandfeelclassname ();   Windows appearance sensation//String lf= "Com.sun.java.swing.plaf.WindowsLookAndFeel";  Metal appearance feeling//string lf= "Javax.swing.plaf.metal.MetalLookAndFeel"; Common use try{uimanager.setlookandfeel (LF);} catch (Exception CE) {joptionpane.showmessagedialog (null, "Unable to set the appearance feeling!  "); }//java feel//java feel jframe.setdefaultlookandfeeldecorated (true); JFrame frame=new JFrame ("Yushibujue");  Frame.setdefaultcloseoperation (Jframe.exit_on_close); Final JFileChooser fc=new JFileChooser (); Fc.setfileselectionmode (Jfilechooser.directoriES_ONLY); Container Con=frame.getcontentpane ();  Con.setlayout (New BorderLayout ()); JPanel jpup=new JPanel (); Jpup.setlayout (New GridLayout (2,2)); Jtfa=new JTextField (30); Jba=new JButton ("Choose the storage Path of the index"); Jba.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {int r=fc.showopend      Ialog (NULL);      if (r==jfilechooser.approve_option) {Jtfa.settext (Fc.getselectedfile (). GetPath ()); }      }      }    ); Jtfb=new JTextField (30); JButton jbb=new JButton ("search"); Jbb.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {try{String Indexpa     Th=jtfa.gettext ();     String Phrase=jtfb.gettext ();     New Lucenesearchertool (). Search (Phrase,indexpath);     }catch (Exception ex) {Joptionpane.showmessagedialog (null, "Search failed", "hint", joptionpane.error_message); }    }    }  ); Jpup.add (JTFA); Jpup.add (JBA); Jpup.add (JTFB);  Jpup.add (JBB); Jta=new JTextArea (10,30);  JScrollPane jsp=new JScrollPane (JTA); JpaNel jpdown=new JPanel (); Jpdown.setlayout (New FlowLayout ()); Jtfc=new JTextField (35); Jbd=new JButton ("Set export path"); Fc.setfileselectionmode (jfilechooser.files_and_directories); Jbd.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {int r=fc.showopendialog (NULL) ;  if (r==jfilechooser.approve_option) {Jtfc.settext (Fc.getselectedfile (). GetPath ());}}  }); Jbe=new JButton ("Export search results"); Jbe.addactionlistener (new ActionListener () {public void actionperformed (ActionEvent e) {try{file F=new file ( Jtfc.gettext ()); FileWriter fw=new FileWriter (f); PrintWriter pw=new PrintWriter (FW); Pw.write (Jta.gettext ()); Pw.flush (); Pw.close ();        Joptionpane.showmessagedialog (NULL, "Write file succeeded!", "hint", joptionpane.information_message);   }catch (IOException IoE) {Joptionpane.showmessagedialog (null, "Write file failed!", "hint", joptionpane.error_message);   }    } }                      ); Jpdown.add (JTFC); Jpdown.add (JBD);  Jpdown.add (JBE); Con.add (Jpup,borderlayout.north); Con.add (Jsp,borderLayout.center);  Con.add (Jpdown,borderlayout.south); Frame.setsize (200,100); Frame.pack ();     Frame.setvisible (TRUE);      } public static void Main (string[] args) {Swingutilities.invokelater (new Runnable () {public void run () {   New Lucenesearcher (). Createandshowgui ();   }      }); } static class lucenesearchertool{//Perform search--search keyword, index path public static void search (String phrase,string indexpath) t Hrows ioexception{//Build indexer Indexsearcher searcher = new Indexsearcher (Directoryreader.open (Fsdirectory.open (New File (i      Ndexpath)));      Search text field term t=new term ("text", phrase);   Generate the Query object Termquery query=new termquery (t);      Topdocs Topdocs=searcher.search (query,20);   Scoredoc[] Scoredocs=topdocs.scoredocs;   Jta.settext ("Number of records retrieved:" +topdocs.totalhits+ "\ n");   Jta.settext (Jta.gettext () + "*******************" + "\ n");   SYSTEM.OUT.PRINTLN ("Total number of query results:" +topdocs.totalhits+ "max Rating:" +topdocs.getmaxscore ()); for (int i=0;i<scoredocs.length;i++) {int doc=scoredOcs[i].doc;    Document document = Searcher.doc (DOC);   if (document==null) {continue;   }//Gets the filename field, where a cast (try) field field= (field) Document.getfield ("filename") is used;      String Filename=field.stringvalue ();   Uri field field= (field) Document.getfield ("uri");      String Uri=field.stringvalue ();   CDate field field= (field) Document.getfield ("CDate");      String CDate =field.stringvalue ();   Digest field field= (field) Document.getfield ("Digest");      String Digest=field.stringvalue ();   StringBuffer sb=new StringBuffer ();   Sb.append ("URI:" +uri+ "\ n");   Sb.append ("FileName:" +filename+ "\ n");   Sb.append ("CDate:" +cdate+ "\ n");   Sb.append ("Digest:" +digest+ "\ n");      Sb.append ("-------------------" + "\ n");                         Jta.settext (Jta.gettext () +sb.tostring ());   /* SYSTEM.OUT.PRINTLN ("Content:" +document.get ("Content"));   SYSTEM.OUT.PRINTLN ("ID:" + scoredocs[i].doc + "scors:" + scoredocs[i].score+ "---index--" +scoredocs[i].shardindex); */     }      }   }  }

Indexer:



Finder:


Lucene's Full Search example

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.