这是从mysql中取出数据,并建立索引的代码
package com.cheea;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.wltea.analyzer.lucene.IKAnalyzer;
public class Indexer {
private File indexDir = new File("E:\\DataBaseIndexDir");
public Indexer() {
if (!this.indexDir.exists()) {
return;
}
}
@SuppressWarnings("deprecation")
public void createIndex() {
try {
Class.forName("com.mysql.jdbc.Driver");//装载驱动
String url="jdbc:mysql://localhost:3306/test?user=root&password=123";
Connection con=DriverManager.getConnection(url);
Statement st=con.createStatement();
String sql="select * from cheea";
ResultSet rs=st.executeQuery(sql);
IndexWriter writer = new IndexWriter(
FSDirectory.open(indexDir),
new IKAnalyzer(false),
true,
IndexWriter.MaxFieldLength.LIMITED);
indexDirectory(writer, rs);
writer.optimize(); //优化合并
writer.close();
System.out.println("索引完毕");
} catch (CorruptIndexException e) {
e.printStackTrace();
} catch (LockObtainFailedException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private void indexDirectory(IndexWriter writer, ResultSet rs) throws SQLException, CorruptIndexException, IOException {
try {
while(rs.next()){
indexFile(writer,rs);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
rs.close();
//commit is here
writer.commit();
}
}
private void indexFile(IndexWriter writer, ResultSet rs) {
try {
System.out.println("正在索引第"+rs.getInt("id")+"个数据");
Document doc = new Document();
doc.add(new Field("id", "" + rs.getInt("id"), Field.Store.YES , Field.Index.NO , Field.TermVector.NO));
doc.add(new Field("name", "" + rs.getString("name"), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
writer.addDocument(doc);// 调用addDocument()方法,Lucene会建立doc的索引
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Indexer lucene = new Indexer();
lucene.createIndex();
}
}