Author: gdsean (original)
In this article, I mentioned Lucene, in the Java industry, mentioned the full-text search, almost no one knows it. Search with Google, the world is relevant. Representative is the "Java-based full-text index engine lucene" in the car. I want to write only the simplest three-ax ax, and then support Chinese ChineseAlyzer and sorted by time sorting. These can find relevant information elsewhere, I just put them out, as a hassle solution that is often encountered in Lucence applications. Last year, I had a friend who mentioned me to I hope to build a website with Lucene. I felt very simple. I didn't have any problems. However, he mentioned a requirement to install time sorting, I check Some information, found that Lucene does not provide user-defined sorting methods, but only in accordance with their own correlation algorithm. Later I found indexordersearcher in the WEBLUCENE project in the car. Solved the results sorted regular needs. IndexOrderSearcher with the average IndexSearch use almost exclusively when building one more object parameter IndexOrderSearcher.ORDER_BY_DOCID_DESCIndexOrderSearcher indexsearcher = new IndexOrderSearcher ( "/ home / lucenetest / index", IndexOrderSearcher.ORDER_BY_DOCID_DESC); lucene new version also offers a MultiFieldQueryParser, can at the same time Retrieve multiple fields, before queryparser is more troublesome.
private static ChineseAnalyzer chineseAnalyzer = new ChineseAnalyzer (); public Hits search (String queryText) {if (queryText == null) {return null;} Query query; try {query = MultiFieldQueryParser.parse (queryText, new String [] { "title "}, chineseanalyzer; return indexsearcher.search (query);} catch (Exception e) {return null;}} The following is to build an index, take out the data index from the database, completed the completion time, I am writing time A TXT file. package com.test.search; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.cn *;. import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene .Document. *; import org.apache.lucene.index. *;
Import java.io. *; import java.sql. *; import java.util.date;
Import com.test.db. *; import com.test.utility. *;
/ ** * Title: SearchIndexer * Description: full-text index * Copyright: Copyright (c) 2001 * Company: test * @author Sean * @version 1.0 * / public class SearchIndexer {private String indexPath = null; protected Analyzer analyzer = new ChineseAnalyzer (); public searchindexer (string s) {this.indexpath = s;} / ** * All documents before index * @Param fromDate * @return * / public final void updateIndex (String fromDate) {connection conn = dButil .getCon (); IndexWriter indexWriter = null; try {indexWriter = getWriter (false); // index distribution system internal file PreparedStatement pstm = conn.prepareStatement ( "select title, body, creationtime from document where creationtime> '" fromdate "'ORDER BY CREATIONTIME"); ResultSet RS = PSTM.ExecuteQuery (); while (rs.next ()) { String CreationTime = rs.getstring ("creeiontime"); string title = rs.getstring ("title"); string body = rs.getstring ("body");
IF (title == null || body == null) {Continue;} Try {adddocstoIndex (Title, Body, CreationTime, IndexWriter);} catch (exception ex) {EX.PrintStackTrace ();}} indexwriter.Optimize () } Catch (exception ex) {ex.printstacktrace ();} finally {type (); conn.close (); catch (exception e) {E.PrintStackTrace ();}}} / ** * Check if the index file exists * @Param s * @return index exists * / private bolean indexexists (String s) {file file = new file (s file.separator "segments"); return file.exists (); } / ** * Add a set of index * @Param Title * @Param body * @Param CreationTT ime * @param indexwriter * @return * / private final void addNewsToIndex (String docid, String url, String title, String body, String ptime, IndexWriter indexwriter) throws IOException {if (indexwriter == null) {return;} else {try {Document Document = New Document (); Document.Add (Field.Text ("Title", Title); Document.Add (Field.Text ("Body", Body); Document.Add ("CRETIONTIME "
, CreationTime, True, True, False); IndexWriter.addDocument (Document);} catch (Exception EX) {EX.PrintStackTrace ();} return;}} / ** * gets indexwriter * @Param flag Whether to create a new index * @return IndexWriter * / private IndexWriter getWriter (boolean flag) throws IOException {String s = indexPath; if (s == null) {throw new IOException ( "index file path setting error.");} indexPath = s File.separator "search"; IndexWriter indexwriter = null; if (flag) {try {indexwriter = new IndexWriter (indexPath, analyzer, true);} catch (Exception exception) {System.err.println ( "ERROR: Failed to create a new Index Writer. "); Exception.PrintStackTrace ();}} else {if (Indexexists (IndexPath)) { try {indexwriter = new IndexWriter (indexPath, analyzer, false);} catch (Exception exception1) {System.err.println ( "ERROR:. Failed to open an index writer"); exception1.printStackTrace ();}} else { try {indexwriter = new IndexWriter (indexPath, analyzer, true);} catch (Exception exception2) {System.err.println ( "ERROR: Failed to create a new index writer."); exception2.printStackTrace ();
}}} Return indexwriter;} public static void main (String [] args) {String lastUpdate = "/home/lucenetest/lastUpdate.txt"; SearchIndexer searchIndexer = new SearchIndexer ( "/ home / lucenetest / index"); // Remove the last update time str = util.readtxtFile (LastUpdate); if (str == null || str.length () == 0) {str = new java.util.date (). Tostring ();} SearchIndexer .updateIndex (STR); // Write the current time util.writetxtfile (Lastupdate, New java.util.date (), false;}}
Write a CMD or SH to perform SearchIndexer in the appropriate operating system.