Lucene3.0学习笔记3(给数据库建立索引)

 - by Hector

 给数据库字段建立索引的方法和给文件建立索引的方法类似。(可见这篇文章:) [Lucene3.0学习笔记1(建立索引)]

只是需要将待索引的源换为从数据库里面读取的字段值就可以了。

代码中用到的数据库操作类在这里:[java通用数据库操作类]

请对照 [Lucene3.0学习笔记1(建立索引)]加以理解。

代码如下:

[CODE=java]
package com.hector.firstlucene;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;



/**********************
*
* @author Hector
* 建立数据库索引 lucene3.0+
*/

public class DataBaseIndexer{
public static void main(String[] args) throws IOException,SQLException{
String indexDir = “d:\\lucene\\index”;
DBConn conn = new DBConn();
conn.OpenConnection();
ResultSet rs = conn.ExecuteQuery(“select * from Article”);
// 为表字段建立索引
Directory dir = new SimpleFSDirectory(new File(indexDir));
IndexWriter indexWriter = new IndexWriter(dir,
new StandardAnalyzer(Version.LUCENE_30), true,
IndexWriter.MaxFieldLength.UNLIMITED);
while (rs.next()) {
System.out.println(rs.getString(“Article_Title”));
Document doc = new Document();
doc.add(new Field(“Article_Title”, rs.getString(“Article_Title”),Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field(“Article_Content”, rs.getString(“Article_Content”),Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field(“indexDate”,DateTools.dateToString(new Date(), DateTools.Resolution.DAY),Field.Store.YES,Field.Index.NOT_ANALYZED));
indexWriter.addDocument(doc);
}
System.out.println(“numDocs”+indexWriter.numDocs());
indexWriter.close();
}
}
[/CODE]

Leave a comment