基于lucenen实现文档索引功能

lucenen是一个实现高性能、进行全文索引和搜索功能的开源库,它是搜索引擎领域的重要组成部分。

以下是关于如何使用lucene实现一个简单的文档索引的一个demo示例,基于lucenen4.x版本,code 如下:

public class Indexer {

    private IndexWriter indexWriter ;

    public static void main(String[] args) throws IOException {
         String indexDir = "/home/drainli/file/index" ;
         String dataDir = "/home/drainli/file" ;
        int numIndexed ;
        Indexer indexer = new Indexer(indexDir) ;
         try {
             numIndexed = indexer.index(dataDir,new TextFilter());
         }catch (Exception e){
             System.out.println("exception:" + e.getMessage());
             e.printStackTrace();
         }finally {
             indexer.close();
         }
    }

    public Indexer(String indexDir) throws IOException {
        Directory dir = FSDirectory.open(new File(indexDir));
        Analyzer analyzer = new StandardAnalyzer() ;
        IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_0,analyzer) ;
        indexWriter = new IndexWriter(dir,config);
    }

    private Document getDocument(File file) throws IOException {
        Document document = new Document();
        document.add(new TextField("文档",new FileReader(file)));
        document.add(new TextField("文件名",file.getName(),Field.Store.YES));
        document.add(new TextField("路径名",file.getCanonicalPath(),Field.Store.YES));

        return document ;
    }

    private int index(String dataDir, FileFilter fileFilter) throws IOException {
        File dataFile = new File(dataDir) ;
        File[] listFiles = dataFile.listFiles() ;
        for (File file : listFiles){
            if (!file.isDirectory()
            && file.canRead()
            && !file.isHidden()
            && file.exists()
            && (fileFilter == null || fileFilter.accept(file))){
                indexFile(file) ;
            }
        }
        return indexWriter.numDocs();
    }

    private void indexFile(File file) throws IOException {
        System.out.println("indexing file : " + file.getCanonicalPath());
        Document document = getDocument(file);
        indexWriter.addDocument(document);
    }

    private void close() throws IOException {
        indexWriter.close();
    }

}

class TextFilter implements FileFilter {

    @Override
    public boolean accept(File pathname) {
        String fileName = pathname.getName();
        return fileName.endsWith(".doc") || fileName.endsWith("docx") ;
    }

}

程序运行截图:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值