It is impossible to create an index with Lucene every time. Instead, it increases progressively according to the newly added records.
Indexwriter class for index creation, which has three parameters
Indexwriter writer = new indexwriter (path, new standardanalyzer (), isempty );
The third parameter is of the bool type, specifying whether it is an incremental index or re-indexing.
For records read from the database, for example, to create an index for an article, we can record the ID of the article, and then read the existing ID number when the index is created again next time, after this ID, the index is added. The logic is as follows.
The main code for creating an incremental index is as follows: public void createindex (string path)
{
Statement mystatement = NULL;
String ArticleID = "0 ";
// Read the file and obtain the Document ID. Only the Document ID of the last index is saved here.
Try {
Filereader Fr = new filereader ("**. txt ");
Bufferedreader BR = new bufferedreader (FR );
ArticleID = Br. Readline ();
If (ArticleID = NULL | ArticleID = "")
ArticleID = "0 ";
BR. Close ();
Fr. Close ();
} Catch (ioexception e ){
System. Out. println ("error343! ");
E. printstacktrace ();
}
Try {
// SQL statement, which reads the following content based on the ID
String sqltext = "*****" + ArticleID;
Mystatement = conn. createstatement ();
Resultset rs = mystatement.exe cutequery (sqltext );
// Write the index
While (Rs. Next ()){
Document Doc = new document ();
Doc. Add (field. Keyword ("**", dateadded ));
Doc. Add (field. Keyword ("**", ArticleID ));
Doc. Add (field. Text ("**", URL ));
Doc. Add (field. Text ("**", content ));
Doc. Add (field. Text ("**", title ));
Try {
Writer. adddocument (DOC );
}
Catch (ioexception e ){
E. printstacktrace ();
}
// Write the ID of the last article of my index to a file
Try {
Filewriter fw = new filewriter ("**. txt ");
Printwriter out = new printwriter (FW );
Out. Close ();
FW. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
Ind. Close ();
System. Out. println ("OK. End ");
}
Catch (sqlexception e ){
E. printstacktrace ();
}
Finally {
// Close the database
}
}
Then, when incremental indexes are created, you can set the third parameter of indexwriter to true or false based on whether the index value can be reached.
Boolean isempty = true;
Try {
Filereader Fr = new filereader ("**. txt ");
Bufferedreader BR = new bufferedreader (FR );
If (Br. Readline ()! = NULL ){
Isempty = false;
}
BR. Close ();
Fr. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
Writer = new indexwriter (directory, new standardanalyzer (), isempty );