lucene搜索引擎配置续

来源:互联网 发布:网络捕鱼技巧打法 编辑:程序博客网 时间:2024/03/29 03:14

使用lucene索引HTML
lucene索引HTML原理与索引text类似,也是通过新建document对象,然后将HTML的各种信息比如title、content等信息以不同的字段保存到document对象中,具体过程介绍如下:
1、设置IndexWriter对象,及其索引文件保存目录、分词器等信息
2、读取HTML文件相应信息,提取文件的各个信息字段,将HTML中的信息一各种方式提取出来,本人采用正则表达式来提取。
3、将提取的信息写入到document对象中去
4、最后还是别忘了关闭IndexWriter对象
参考代码如下:

  1. import org.apache.lucene.document.Document;
  2. import org.apache.lucene.document.Field;
  3. import org.apache.lucene.index.IndexWriter;
  4. import java.io.BufferedReader;
  5. import java.io.File;
  6. import java.io.FileReader;
  7. import java.io.IOException;
  8. import java.text.DateFormat;
  9. import java.util.Date;
  10. import jeasy.analysis.MMAnalyzer;
  11. //还需调用demo的其他类。
  12. ;
  13. public class IndexHTML {
  14.     public static void main(String[] args) throws ClassNotFoundException,
  15.             IOException
  16.     {
  17.         try {
  18.             Date start = new Date();
  19.             IndexWriter writer = new IndexWriter("D://luceneIndex",
  20.                     new MMAnalyzer(), true); // 索引保存目录,必须存在
  21.             indexDocs(writer, new File("D://luceneData")); // HTML 文件保存目录
  22.             System.out.println("Optimizing ....");
  23.             writer.optimize();
  24.             writer.close();
  25.             Date end = new Date();
  26.             System.out.print("Total time: ");
  27.             System.out.println(end.getTime() - start.getTime());
  28.         } catch (Exception e) {
  29.             System.out.println("Class " + e.getClass()
  30.                     + " throws error!/n  errmsg: " + e.getMessage());
  31.         } // end try
  32.     } // end main
  33.     public static void indexDocs(IndexWriter writer, File file)
  34.             throws Exception
  35.     {
  36.         if (file.isDirectory()) {
  37.             String[] files = file.list();
  38.             for (int i = 0; i < files.length; i++) {//假如文件是文件夹则递归调用方法
  39.                 indexDocs(writer, new File(file, files[i]));
  40.             } // end for
  41.         } else if (file.getPath().endsWith(".htm") || file.getPath().endsWith(".html") || file.getPath().endsWith(".shtml")) { // 只对 HTML 文件做索引
  42.             System.out.print("Add file:" + file + " ....");
  43.             // Add html file ....
  44.             Document doc = new Document();
  45.             doc.add(new Field("file", file.getName(),Field.Store.YES,Field.Index.TOKENIZED)); // 索引文件名
  46.             doc.add(new Field("modified", DateFormat.getDateTimeInstance().format(new Date(file.lastModified())),Field.Store.YES,Field.Index.TOKENIZED)); // 索引最后修改时间
  47.             String content = "";
  48.             FileReader fReader = new FileReader(file);//读取文件
  49.             BufferedReader bReader = new BufferedReader(fReader);
  50.             String line = bReader.readLine();
  51.             while (line != null) {
  52.                 String readline = new String(line.getBytes(),"UTF-8");//读取文件后转换字符编码
  53.                 content += readline;
  54.                 // 截取 HTML 标题 <title>
  55.                 line = bReader.readLine();
  56.             } // end while
  57.             bReader.close();
  58.             fReader.close();
  59.             String tLowContentStr = content.toLowerCase();
  60.             //提取内容忽略script
  61.             int tScriptStartInt = tLowContentStr.indexOf("<script");//第一次出现script的位置
  62.             while(tScriptStartInt != -1){
  63.                 int tScriptEndInt = tLowContentStr.indexOf("</script>");
  64.                 String tStartStr = content.substring(0, tScriptStartInt);
  65.                 String tEndStr = content.substring(tScriptEndInt + 9, content.length());
  66.                 content = tStartStr + tEndStr;
  67.                 //截取字符串
  68.                 tLowContentStr = content.toLowerCase();
  69.                 tScriptStartInt = tLowContentStr.indexOf("<script");
  70.             }
  71.             tLowContentStr = content.toLowerCase();
  72.             //读取内容忽略style内容
  73.             tScriptStartInt = tLowContentStr.indexOf("<style");//第一次出现style的位置
  74.             while(tScriptStartInt != -1){
  75.                 int tScriptEndInt = tLowContentStr.indexOf("</style>");
  76.                 String tStartStr = content.substring(0, tScriptStartInt);
  77.                 String tEndStr = content.substring(tScriptEndInt + 8, content.length());
  78.                 content = tStartStr + tEndStr;
  79.                 //截取字符串
  80.                 tLowContentStr = content.toLowerCase();
  81.                 tScriptStartInt = tLowContentStr.indexOf("<style");
  82.             }
  83.             int tTitleStartInt = tLowContentStr.indexOf("<title");
  84.             int tTitleEndInt = tLowContentStr.indexOf("</title>");
  85.             String tTitleStr = tLowContentStr.substring(tTitleStartInt + 7 , tTitleEndInt);
  86.             doc.add(new Field("title",tTitleStr,Field.Store.YES,Field.Index.TOKENIZED));
  87.             content = content.replaceAll(" {1,}","");
  88.             content = content.replaceAll(" {1,}"" ");
  89.             content = content.replaceAll("/t{1,}"" ");
  90.             content = content.replaceAll(">{1,}""");
  91.             content = content.replaceAll("©{1,}""");
  92.             doc.add(new Field("contents", content.replaceAll("<[^<>]+>"""),Field.Store.YES,Field.Index.TOKENIZED)); // 索引内容
  93.             writer.addDocument(doc);
  94.             /*Document document = HTMLDocument.Document(file);
  95.             writer.addDocument(document);//使用系统HTML解析*/
  96.             System.out.println(" [OK]");
  97.         } // end if
  98.     }
  99. }

 

代码说明:

在读取HTML时因为分词器的原因,有些分词器不支持UTF-8的字符集,因此在读取文件之后,有必要将以前以UTF-8编码的文件以UTF-8的方式读取,否则分词器无法对文件的字符串建立正确索引。如:String readline = new String(line.getBytes(),"UTF-8");

关于如何获取读取字符串到底是GBK还是UTF-8的问题,我们可以获取刚才读取字符的Unicode编码,假如Unicode编码是属于GBK的那那就是GBK。关于有时要提取URL 的正则表达式这里给一个比较通用的正则表达式:

http(s)?://([//w-]+//.)+[//w-[:[//d]]]+(/[//w- ./?%@&=+#]*)?

5、查找,关于查找与以前查找一样也是通过新建查找对象,然后通过查找对象查找结果,参考代码如下:

  1. Searcher searcher = new IndexSearcher(indexFilePath);
  2.             Analyzer analyzer = new MMAnalyzer();
  3.             QueryParser queryParser = new QueryParser("contents", analyzer);//新建查询对象
  4.             Query query = queryParser.parse(line);
  5.             System.out.println("Searching for: " + query.toString("contents"));
  6.             this.hits = searcher.search(query);
  7.             if (this.hits.length() == 0)
  8.             System.out.println(this.hits.length() + " total matching documents");
  9.             for (int i = 0; i < hits.length(); i++) {
  10.                 Document doc = this.hits.doc(i);
  11.                 System.out.println(doc.get("file"));
  12.                 System.out.println(doc.get("title"));
  13.                 System.out.println(doc.get("modified"));
  14.                 System.out.println(hits.score(i));
  15.             }
  16.             searcher.close();

 

6、对数据库建立索引

对于数据库建立索引,只需要读取要建立索引的表的记录,然后将记录中各个字段保存到document中,最后将document字段通过IndexWriter写入到索引中去。这里不再赘述。