lyyb2001

只是为方便自己找记录而已
posts - 57, comments - 27, trackbacks - 0, articles - 5
  BlogJava :: 首页 :: 新随笔 :: 联系 ::  :: 管理

Lucene:日志查询(二)[创建索引二]

Posted on 2007-03-05 09:02 skycity 阅读(397) 评论(0)  编辑  收藏 所属分类: APACHE开源项目

此处添加一个logmanager类
package net.skycity.blog;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.sf.hibernate.Criteria;
import net.sf.hibernate.Session;
import net.sf.hibernate.expression.Expression;
import net.sf.hibernate.expression.Order;
import net.skycity.model.LogForm;
import net.skycity.search.SearchEnginePlugIn;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.FSDirectory;

public class LogManager extends SearchEnginePlugIn {
 
 public static List searchFor(String logTypeId,String state,String author,String query) throws Exception{
  List logs = new ArrayList();
        List ids = searchFor(1,logTypeId,query,0,-1);
        if(ids.size()>0){
         Session ssn=ManagerBase.getSession();
            Criteria crit = ssn.createCriteria(LogForm.class).add(Expression.eq("siteId", "1"));
            crit = crit.add(Expression.in("logId",ids));
      String orderField = "submitTime";
      crit = crit.addOrder(Order.desc(orderField));
            logs = crit.list();
            ssn.close();
        }
  return logs;
 }
 
 public static List searchFor(String logTypeId,String state,String author) throws Exception {
  Session ssn=ManagerBase.getSession();
  List list = null;
  try{
   Criteria crit=ssn.createCriteria(LogForm.class).add(Expression.eq("author",author));
   if(!logTypeId.equals("0"))
    crit.add(Expression.eq("logTypeId",logTypeId));
   if(!StringUtils.isEmpty(state))
    crit.add(Expression.eq("state",state));
   list=crit.list();
  }finally{
   ssn.close();
  }   
  return list;
 }
 
 public static List searchFor(int site, String logTypeId, String word, int from, int count) throws IOException, ParseException {
  List logs = new ArrayList();
  //从文件目录中
  FSDirectory searchDirectory = FSDirectory.getDirectory(SearchEnginePlugIn.getLogIndexPath(), false);
  IndexReader reader = IndexReader.open(searchDirectory);
  IndexSearcher searcher = new IndexSearcher(reader);
  if (searcher == null) return logs;
  
  if(!StringUtils.isEmpty(word)){
   BooleanQuery comboQuery = new BooleanQuery();
   
   Query query1 = QueryParser.parse(word,"logTitle",new StandardAnalyzer());
   comboQuery.add(query1, false, false);
   Query query2 = QueryParser.parse(word,"content",new StandardAnalyzer());
   comboQuery.add(query2, false, false);
   
   Hits hits = searcher.search(comboQuery);
   
   int numResults = hits.length();
   for (int i = 0; i < numResults; i++) {
    if (count > 0 && logs.size() >= count) break;
       if (i < from) continue;
             logs.add(new Integer(((Document) hits.doc(i)).get("logId")));
   }
  }
  reader.close();
  return logs;
 }
 
 public static void delLog(int logId) throws Exception{
  Session ssn=ManagerBase.getSession();
  LogForm log=(LogForm) ssn.load(LogForm.class,String.valueOf(logId));
  ssn.delete(log);
  delLogIndex(logId);
 }
 
 public static int createLogIndex(Object obj) throws Exception{
        LogForm log = (LogForm)obj;              
        Document doc = new Document();
        doc.add(Field.Keyword("logId", String.valueOf(log.getLogId())));
        doc.add(new Field("author", log.getAuthor(),false,true,false));
        doc.add(new Field("siteId", log.getSiteId(),false,true,false));
        doc.add(new Field("logTypeId",log.getLogTypeId(),false,true, false));
        doc.add(Field.UnStored("logTitle", StringUtils.deleteWhitespace(log.getLogTitle())));
        doc.add(Field.UnStored("content", log.getContent()));
        doc.add(new Field("submitTime", log.getSubmitTime(),false,true,false));

  IndexWriter writer = getLogIndexWriter();
  try {
      writer.addDocument(doc);
      writer.optimize();
  }finally {
      writer.close();
  }
        return 1;
    }
 
 public static int createAllLogIndex() throws Exception{
  String logPath=getLogIndexPath();
  File file=new File(logPath);
  delDirectory(file);
  Session ssn=ManagerBase.getSession();
  String hql="from "+LogForm.class.getName();
  net.sf.hibernate.Query query=ssn.createQuery(hql);
  List logs = query.list();
  IndexWriter writer = getLogIndexWriter();
  int logCount=0;
  for(int i=0;i<logs.size();i++){
   Document doc = new Document();
         LogForm log = (LogForm)logs.get(i);
         doc.add(Field.Keyword("logId", String.valueOf(log.getLogId())));
         doc.add(new Field("author", log.getAuthor(),false,true,false));
         doc.add(new Field("siteId", log.getSiteId(),false,true,false));
         doc.add(new Field("logTypeId",log.getLogTypeId(),false,true, false));
         doc.add(Field.UnStored("logTitle", StringUtils.deleteWhitespace(log.getLogTitle())));
         doc.add(Field.UnStored("content", log.getContent()));
         doc.add(new Field("submitTime", log.getSubmitTime(),false,true,false));
         logCount++;
         writer.addDocument(doc);
  }
  writer.optimize();
  writer.close();
  System.out.println("建立索引数目:"+logCount);
        return logCount;
    }
 public static int delLogIndex(int logId) throws Exception{
  IndexReader reader = IndexReader.open(getLogIndexPath());
  if (reader == null)
   return 0;
  int dc = 0;
  try {
   Term logIdTerm;
   logIdTerm = new Term("logId", Integer.toString(logId));
   try {
    dc += reader.delete(logIdTerm);
   }catch (Exception e) {}
  } finally {
   try {
    reader.close();
   } catch (Exception e) {}
  }
  return dc;
 }
 /**重建索引、删除索引目录下的所有文件
     *
     */
    public static void delDirectory(File file) throws IOException{
     if((file == null) || !file.isDirectory()){
      throw new IllegalArgumentException(file+"不是一个目录.");
     }
     File[] entries = file.listFiles();
     int sz = entries.length;
     for(int i=0;i<sz;i++) {
      if(entries[i].isDirectory()) {
        delDirectory(entries[i]);
      }else{
       System.out.println(entries[i].getName());
       System.out.println(entries[i].getAbsolutePath());
       entries[i].delete();
      }
     }
     file.delete();
    }
}
程序运行时调用createAllLogIndex()则会创建所有的索引
现在实现jsp添加一个日志来新增一个索引:
<%@ page contentType="text/html;charset=GBK"%>
<style type="text/css">
body {
 color: #333333;
 font-size: 11px;
 font-family: Tahoma, Verdana, sans-serif, "宋体";
 margin: 0px;
 padding: 0px;
 background-position: center top;
}
table {font: 12px Verdana, Tahoma, sans-serif, "宋体";}
</style>
<body>
<table cellspacing="0" cellpadding="2" width="100%">
  <tr>
    <td>
      <table width='100%' border='0' cellspacing='1' cellpadding='2'>
        <tr>
          <td align="left"><b><font color="#000000">新增日志:</font></b></td>
        </tr>
      </table>
      <table width="100%" border="0" cellspacing="1" cellpadding="2">
     <form action="addLog.do" name="log" method="post">
    <tr>
            <td align="center">日志标题</td>
            <td><input type="text" name="logTitle"/><font color="#FF0000"></td>
          </tr>
          <tr bgcolor="#f8f8f8">
            <td align="center">文章分类</td>
            <td>
              <select name="logTypeId">
             <option value="1">JAVA</option>
             <option value="2">AJAX</option>
               <option value="3">STRUTS</option>
       </select>
     </td>
          </tr>
    <tr bgcolor="#f8f8f8">
            <td align="center">文章类型</td>
            <td>
             <input type="text" name="comeForm">
             <a onclick="comeForm.value='原创'">原创</a>&nbsp;&nbsp;&nbsp;&nbsp;
             <a onclick="comeForm.value='转载'">转载</a>
            </td>
          </tr>
          <tr bgcolor="#f8f8f8">
            <td align="center">文章状态</td>
            <td>
             <select name="state">
              <option value="0">公开</option>
              <option value="1">草稿</option>
              <option value="2">已删除</option>
       </select>
            </td>
          </tr>
          <tr bgcolor="#f8f8f8">
            <td valign="top" align="center">内&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;容</td>
            <td rowspan="2">
             <textarea cols="50" rows="10" name="content"></textarea>
             <font color="#FF0000">*</font>
            </td>
          </tr>
          <tr bgcolor="#f8f8f8">
            <td align="center">&nbsp;</td>
          </tr>
          <tr bgcolor="#f8f8f8">
            <td align="center">评&nbsp;&nbsp;&nbsp;&nbsp;论</td>
            <td><input type="radio" name="canComment" value="0">不允许<input type="radio" name="canComment" value="1" checked>允许</td>
          </tr>
          <tr bgcolor="#f8f8f8">
            <td colspan="2" height="40" align="center">
             <input type="button" class="button" name="eventSubmit_addLog" onclick="CheckForm()" value="发表"/>
             <input type="reset" class="button" name="btn_reset" value="重填"/>
            </td>
          </tr>
         
      </form>
      </table></td>
  </tr>
</table>
</body>
<script language="javascript">
function CheckForm()
{
 with(document.log){
  if(logTitle.value==""){
   alert('日志标题不能为空');
   logTitle.focus();
   return false;
  }
  if(content.value==""){
   alert('日志内容不能为空');
   content.focus();
   return false;
  }
  submit();
 }
}
</script>
form的addLog.do在struts-config.xml中如下定义
<action path="/addLog" scope="request" name="LogForm" validate="false" type="net.skycity.action.LogAction" input="/index.jsp"/>
action的model层上面已经介绍过了,实现添加文档及索引的是LogAction
package net.skycity.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.hibernate.Session;
import net.skycity.blog.Globals;
import net.skycity.blog.LogManager;
import net.skycity.blog.ManagerBase;
import net.skycity.model.LogForm;
import net.skycity.util.WellsoonUtil;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LogAction extends Action {

 public ActionForward execute(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception
    {
     LogForm log=(LogForm)form;
     Session ssn=ManagerBase.getSession();
  try{
   log.setAuthor("admin");   //这里为了简便,都取了默认值
   log.setSiteId("1");
   log.setLogTitle(WellsoonUtil.transfer(log.getLogTitle()));
   log.setComeForm(WellsoonUtil.transfer(log.getComeForm()));
   log.setSubmitTime(Globals.FORMAT_DT.format(new Date()));
   log.setContent(WellsoonUtil.transfer(log.getContent()));
   ssn.save(log);
   LogManager.createLogIndex(log);
  }finally{
   ManagerBase.commitSession(ssn, true);
  }
     return mapping.findForward("success");
    }
}
  重点是:ssn.save(log); LogManager.createLogIndex(log);前一句,将提交的数据保存到数据库,后一句将提交的数据增加到索引中
通过这些程序,索引文件就已经创建了



Lyyb2001

只有注册用户登录后才能发表评论。


网站导航: