阿翔编程学-Lucene的例子

来源:互联网 发布:返利网好还是淘宝客 编辑:程序博客网 时间:2024/05/16 09:30

package src.com;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
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.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;

/**
 * 索引模板类
 * @author CaoXiang
 *
 */
class TempClass {
 
 //文件ID
 private int id;
 
 //文件名
 private String name;
 
 //创建时间
 private String time;
 
 /**
  * @return the id
  */
 public int getId() {
  return id;
 }
 /**
  * @param id the id to set
  */
 public void setId(int id) {
  this.id = id;
 } 
 /**
  * @return the name
  */
 public String getName() {
  return name;
 }
 /**
  * @param name the name to set
  */
 public void setName(String name) {
  this.name = name;
 }
 /**
  * @return the time
  */
 public String getTime() {
  return time;
 }
 /**
  * @param time the time to set
  */
 public void setTime(String time) {
  this.time = time;
 }
}

/**
 * 全文搜索
 * @author CaoXiang
 *
 */
public class OaisIndexFiles {

 //索引文件存放的文件路径
 private final static String INDEX_FILE_ADDRESS = "C://index";
 
 //不需要建立索引的文件内容
 private final static String[] STOP_INDEX_STR = {
         "他奶奶的", "***","你妈妈的","嬲"};

 public static void main(String[] args) throws IOException, ParseException, SQLException {
  OaisIndexFiles oais = new OaisIndexFiles();
  oais.createIndexFiles();
  oais.searchFilesByIndex("入门");
 }
 
 /**
  * 获得文件信息
  * @return
  */
 public List<TempClass> getAllMessage() {
  List<TempClass> list = new ArrayList<TempClass>();
  for(int i=1;i<500;i++) {
   TempClass t = new TempClass();
   t.setId(i);
   t.setName("iiiii");
   list.add(t);
   System.out.println(t);
  }
  return list;
 }
 
 /**
  * 创建全文索引
  * @throws IOException
  *
  */
 public void createIndexFiles() throws IOException {
  //创建索引文件存放路径
        File indexDir = new File(INDEX_FILE_ADDRESS);
        //创建索引开始时间
        Date start = new Date();
        //创建标准分析器 (主要功能进行筛选) , 主要用于从文本中抽取那些需要建立索引的内容 , 把不需要参与建索引的文本内容去掉
        StandardAnalyzer standardAnalyzer = new StandardAnalyzer(STOP_INDEX_STR);
        //参数 true 用于确定是否覆盖原有索引的 , 写入到对应的索引文件中
        IndexWriter indexWriter = new IndexWriter(indexDir, standardAnalyzer, true);
        //缓存在内存中的document数目
        // 只索引这个 Field 的前 5000 个字,默认为 10000
        //indexWriter.maxFieldLength = 5000;
        //indexWriter.mergeFactor = 100;
        indexWriter.setMergeFactor(100);
        indexWriter.setMaxBufferedDocs(100);
        // 只索引这个 Field 的前 5000 个字,默认为 10000
        indexWriter.setMaxFieldLength(5000);
        //添加一条文档 (相当于往数据库的数据表中添加了一条数据)
        List<TempClass> allList = new ArrayList<TempClass>();
  for(int i=1;i<500;i++) {
   Date createTime = new Date();
   TempClass t = new TempClass();
   t.setId(i);
   t.setName("file_"+i+"_read");
   t.setTime(createTime.toString());
   allList.add(t);
  }
        //对数据文本
  for(int i=0;i<allList.size();i++) {
         Document doc = new Document();
         Field fieldId = new Field("id", String.valueOf(allList.get(i).getId()), Field.Store.YES, Field.Index.UN_TOKENIZED, Field.TermVector.YES);
         Field fileName = new Field("filename", String.valueOf(allList.get(i).getName()), Field.Store.YES, Field.Index.UN_TOKENIZED, Field.TermVector.YES);
         Field time = new Field("time", String.valueOf(allList.get(i).getTime()), Field.Store.YES, Field.Index.UN_TOKENIZED, Field.TermVector.YES);
         //db 中的每条纪录对应一个 doc ,每个字段对应一个 field
            doc.add(fieldId);
            doc.add(fileName);
            doc.add(time);
         indexWriter.addDocument(doc);
        }
  //对HTML格式
  /*声明字符串strLine,用于读取一行信息*/  
  String   strLine = null;  
  /*声明url对象,该对象将连接到清华邮箱网页上*/  
  //URL   urlObj   =   new   URL("http://mails.tsinghua.edu.cn");  
  /*将通过URL对象的openStream方法获得的InputStream对象赋给streamObj*/
  //InputStream   streamObj   =   urlObj.openStream();
  Document doc = new Document();
  InputStream stream = this.getClass().getResourceAsStream("conf.xml");
  /*通过上面的streamObj生成InputStreamReader类对象readerObj*/  
  InputStreamReader readerObj = new InputStreamReader(stream);  
  /*生成BufferedReader类对象buffObj*/  
  BufferedReader  buffObj = new BufferedReader(readerObj);
  // 用 HTMLParser 把 detail 字段中的 HTML 分析成文本在索引
        // HTMLParser 这个类可以在 lucene 的 demo 中找到
        //HTMLParser htmlParser = new HTMLParser(read);
        //BufferedReader breader = new BufferedReader(htmlParser.getReader());
        // Optimize 的过程就是要减少剩下的 Segment 的数量 , 尽量让它们处于一个文件中
        String htmlContent ="";
        //String tempContent = buffObj.readLine();
        //System.out.println(tempContent +" ddd");
//        while (tempContent != null && tempContent.length() > 0) {
//            htmlContent = htmlContent + tempContent;
//            tempContent = buffObj.readLine();
//        }
        String tempContent = buffObj.readLine();
        while(tempContent != null && tempContent.length() > 0) {
          //System.out.println(buffObj.readLine() + " d");
          strLine = strLine + tempContent;
          //System.out.println(strLine);
          tempContent = buffObj.readLine();
        }
        System.out.println(strLine);
        //Field fieldContents = new Field("content", htmlContent,
        //Field.Store.COMPRESS, Field.Index.TOKENIZED,Field.TermVector.YES);
        //doc.add(new Field("title","ddd",Field.Store.YES,Field.Index.TOKENIZED));
        doc.add(new Field("content","aa",Field.Store.YES,Field.Index.UN_TOKENIZED));
        //Field fieldContents = new Field("content",htmlContent,new Filed);
        //doc.add(fieldContents);
        indexWriter.optimize();
        //关闭索引
        indexWriter.close();
        //创建索引结束时间
        Date end = new Date();
        System.out.println("建立索引用时: " + (end.getSeconds() - start.getSeconds()) + " 秒...");
 }
 
 /**
  * 搜索文件 (根据指定的索引名称查询数据)
  * @param searchIndex
  * @throws IOException
  * @throws ParseException
  */
 public void searchFilesByIndex(String searchIndex) throws IOException, ParseException {
  // HitsList 用来保存 db 的纪录,这些纪录可以通过查询结果取到
  List hitsList = new ArrayList();
        //开始查询的时间
        Date start = new Date();
        //创建索引读取对象
        IndexReader reader = IndexReader.open(INDEX_FILE_ADDRESS);
        //根据索引创建读取对象
        Searcher searcher = new IndexSearcher(reader);
        //分析器的创建
        Analyzer analyzer = new StandardAnalyzer();
        //构造读取器
        QueryParser parser = new QueryParser("content", analyzer);
        // 解析查询关键字,比如输入的是以空格等分开的多个查询关键字,这里解析后,可以多条件查询
        Query query = parser.parse("aa");
        // hits 用来保存查询结果,这里的 hits 相当于 sql 中的 result
        Hits hits = searcher.search(query);
        for (int i = 0; i < hits.length(); i++) {
            Document doc = hits.doc(i);
            String id = doc.get("content");
            System.out.println("found " + "入门" + " on the id:" + id);
        }
        //关闭查询对象
        searcher.close();
        reader.close();
        //查询结束时间
        Date end = new Date();
        System.out.println("查询文件用时 : " + (end.getSeconds() - start.getSeconds()) + " 秒...");
 }

 /**
  * 删除索引
  *
  */
    public void deleteIndex(){
        try {
         //开始删除索引时间
            Date start = new Date();
            //索引对象的读取
            IndexReader reader = IndexReader.open(INDEX_FILE_ADDRESS);
            int numFiles = reader.numDocs();
            for (int i = 0; i < numFiles; i++) {
                // 这里的删除只是给文档做一个删除标记,你可以看到执行 deleteDocument 后会产生一个 del 后缀的文件,
                // 用来记录这些标记过的文件
                reader.deleteDocument(i);
            }
            //关闭
            reader.close();
            //删除索引的结束时间
            Date end = new Date();
            System.out.println("删除索引用时: " + (end.getSeconds() - start.getSeconds()) + " 秒");
        } catch (IOException e) {
         System.out.println(" 捕捉 " + e.getClass() + "/n 错误信息: " + e.getMessage());
        }
    }

    /**
     * 恢复已删除的索引
     */
    public void unDeleteIndex(){
        try {
         //读取索引的对象
            IndexReader reader = IndexReader.open(INDEX_FILE_ADDRESS);
            reader.undeleteAll();
            //关闭
            reader.close();
        } catch (IOException e) {
            System.out.println(" 捕捉 " + e.getClass() + "/n 错误信息: " + e.getMessage());
        }
    }
   
    /**
  * 获得文件
  * @param filePath
  * @throws Exception
  */
 public File[] getFolderByFilePath(String filePath) throws Exception {
  File file = new File(filePath);
  File[] tempFile = file.listFiles();
  return tempFile;
 }
   
}
 

原创粉丝点击