如何才能把索引存到数据库中

leon442 2010-08-06
小弟刚接触lucene开发中遇到了一些问题 向各位高手请教一下

项目中要求在查询中创建的索引 不创建文件 而是将索引信息存在数据库中  我在网上搜了一圈
第一步:在一位大哥的博客里看到了一个例子程序 实现了从数据库里查出数据库 把索引保存成索引文件的。
第二步:我不想要索引文件的形式,在百度里搜了一下,他们回答让我用RAMDirectory来代替FSDirectory把索引文件保存在内存中。

***********************
修改后的代码如下
1数据库用的mysql
--
-- 表的结构 `photo`
--
CREATE TABLE  `photo` (
  `photo_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(11) DEFAULT NULL,
  `descr` text,
  `user_name` varchar(11) DEFAULT NULL,
  `tag_name` varchar(11) DEFAULT NULL,
  PRIMARY KEY (`photo_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 ROW_FORMAT=REDUNDANT AUTO_INCREMENT=5 ;
--
-- 导出表中的数据 `photo`
--
INSERT INTO `photo` (`photo_id`, `title`, `descr`, `user_name`, `tag_name`) VALUES
(1, '美女', '美女', '好人5', '美女'),
(2, '美女', '美女', '美女', '美女'),
(3, 'hagh', '说的就是我的是', '', NULL),
(4, 'hagh', '说的就是我的是', ' ', NULL);

2、java文件有4个:

文件Photo.java是数据库的photo表的操作文件;内容如下:
package newTest;

import java.sql.Connection;
import java.util.ArrayList;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Photo {
private long photoId;
private String title;
private String description;
private String userName;
private String tag;
public String getDescription() {
  return description;
}
public void setDescription(String description) {
  this.description = description;
}
public long getPhotoId() {
  return photoId;
}
public void setPhotoId(long photoId) {
  this.photoId = photoId;
}
public String getTag() {
  return tag;
}
public void setTag(String tag) {
  this.tag = tag;
}
public String getTitle() {
  return title;
}
public void setTitle(String title) {
  this.title = title;
}
public String getUserName() {
  return userName;
}
public void setUserName(String userName) {
  this.userName = userName;
}
public static Photo[] loadPhotos(Connection con) throws Exception {
  ArrayList<Photo> list = new ArrayList<Photo>();
  PreparedStatement pstm = null;
  ResultSet rs = null;
  String sql = "select photo_id,title,descr,user_name,tag_name from photo";
  try {
   pstm = con.prepareStatement(sql);
   rs = pstm.executeQuery();
   while (rs.next()) {
    Photo photo = new Photo();
    photo.setPhotoId(rs.getLong(1));
    photo.setTitle(rs.getString(2));
    photo.setDescription(rs.getString(3));
    photo.setUserName(rs.getString(4));
    photo.setTag(rs.getString(5));
    list.add(photo);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   if (rs != null) {
    rs.close();
   }
   if (pstm != null) {
    pstm.close();
   }
  }
  return (Photo[]) list.toArray(new Photo[list.size()]);
}
}

文件IndexerFile.java是把数据库的内容备份成索引文件到磁盘中去;
package newTest;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.store.RAMDirectory;
public class TestDb {
// public final static String indexDir ="E:\\TestLucene";
private static Connection getConnection() {
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/demo";
  String userName = "root";
  String password = "realesoft";
  try {
   Class.forName("com.mysql.jdbc.Driver");
   conn = java.sql.DriverManager
     .getConnection(url, userName, password);
  } catch (Exception e) {
   e.printStackTrace();
   System.out.println("Error Trace in getConnection() : "
     + e.getMessage());
  }
  return conn;
}
public static void main(String[] args) throws IOException, ParseException, SQLException {
RAMDirectory ramDir = new RAMDirectory();
  index(ramDir);//做索引
  Searcher searcher=null;
  try{
  searcher = new IndexSearcher(ramDir,true);
  search(searcher);//搜索
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(searcher!=null)
   searcher.close();
  }
}
public static void search(Searcher searcher) throws IOException, ParseException{
  //以下是搜索的关键词
  String[] q = {"aa","说的就是我的是","11","好人2"};
  long start=new Date().getTime();
  SearcherFile.search(searcher,q);
  long end=new Date().getTime();
  System.out.println("花费时间:"+(double)(end-start)/1000+"秒");
}
public static void index(RAMDirectory ramDir) throws SQLException{
  Connection conn = null;
  try {
   conn = getConnection();
   Photo[] list = Photo.loadPhotos(conn);
   IndexerFile.indexFile(ramDir,list);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (conn != null) {
    conn.close();
   }
  }
}
}


文件SearcherFile.java是搜索磁盘索引文件内容的;
package newTest;

import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.util.Version;
public class SearcherFile {
public static void search(Searcher searcher, String[] q) throws IOException, ParseException {
  Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
  String[] fields = {"title","descr","user_name","tag_name"};     
        Query query = MultiFieldQueryParser.parse(Version.LUCENE_CURRENT, q, fields, analyzer);
        TopDocs topDocs = searcher.search(query, 100);//100是显示队列的Size
         ScoreDoc[] hits = topDocs.scoreDocs;
         System.out.println("共有" + searcher.maxDoc() + "条索引,命中" + hits.length + "条");
         for (int i = 0; i < hits.length; i++) {
             int DocId = hits[i].doc;
             Document document = searcher.doc(DocId);
             System.out.println("photoId==="+document.get("photoId"));
             System.out.println("title==="+document.get("title"));
             System.out.println("descr==="+document.get("descr"));
             System.out.println("user_name==="+document.get("user_name"));
             System.out.println("tag_name==="+document.get("tag_name"));
         }
}
}

文件TestDb.java是操作的主文件;
package newTest;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;

import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.store.RAMDirectory;
public class TestDb {
// public final static String indexDir ="E:\\TestLucene";
private static Connection getConnection() {
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/demo";
  String userName = "root";
  String password = "realesoft";
  try {
   Class.forName("com.mysql.jdbc.Driver");
   conn = java.sql.DriverManager
     .getConnection(url, userName, password);
  } catch (Exception e) {
   e.printStackTrace();
   System.out.println("Error Trace in getConnection() : "
     + e.getMessage());
  }
  return conn;
}
public static void main(String[] args) throws IOException, ParseException, SQLException {
RAMDirectory ramDir = new RAMDirectory();
  index(ramDir);//做索引
  Searcher searcher=null;
  try{
  searcher = new IndexSearcher(ramDir,true);
  search(searcher);//搜索
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(searcher!=null)
   searcher.close();
  }
}
public static void search(Searcher searcher) throws IOException, ParseException{
  //以下是搜索的关键词
  String[] q = {"aa","说的就是我的是","11","好人2"};
  long start=new Date().getTime();
  SearcherFile.search(searcher,q);
  long end=new Date().getTime();
  System.out.println("花费时间:"+(double)(end-start)/1000+"秒");
}
public static void index(RAMDirectory ramDir) throws SQLException{
  Connection conn = null;
  try {
   conn = getConnection();
   Photo[] list = Photo.loadPhotos(conn);
   IndexerFile.indexFile(ramDir,list);
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   if (conn != null) {
    conn.close();
   }
  }
}
}


****************
如此修改后 确实不用生成索引的文件,也不用创建索引的路径,但是每次查询的时候都是重新创建了一次索引,这样也不符合我们要求的把索引信息存入数据库的要求。
怎样才能保存索引信息呢?是保存的Document对象还是什么类型?如果保存了,怎么还原保存的索引信息到内存中呢?  期待各位高手们指教一下 ,最好能给出具体的实现方法或例子
galo 2010-09-07
麻烦先学学怎么贴代码,这样的看得眼花。
Global site tag (gtag.js) - Google Analytics