Lucene-构建索引的2种方式及加权

1、根据文件来生成索引,如后缀为.txt等的文件

步骤:

第一步:FSDirectory.open(Paths.get(url));根据路径获取存储索引的目录。

FSDirectory:表示对文件系统目录的操作。RAMDirectory :内存中的目录操作。

Paths为NIO(new io)的一个类;Path 类是 java.io.File 类的升级版,File file=newFile("index.html")而Path path=Paths.get("index.html");由于 Path 类基于字符串创建,因此它引用的资源也有可能不存在。

关于nio:传统的io流都是通过字节的移动来处理的,也就是说输入/输出流一次只能处理一个字节,因此面向流的输入/输出系统通常效率不高;因此引进了新IO(new IO),NIO采用内存映射文件的方式来处理输入/输出,NIO将文件或文件的一段区域映射到内存中,这样就可以向访问内存一样来访问文件了(这种方式模拟了操作系统上的虚拟内存的概念),所以NIO的效率很快。

第二步:new IndexWriter(Directory,IndexWriterConfig)创建索引

第三步:索引指定目录的文件

第四步:将文件写入lucene中的文档(Document)

package com.wp.util;

import java.io.File;
import java.io.FileReader;
import java.nio.file.Paths;

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.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class Indexer {

    private IndexWriter writer; // 写索引实例

    /**
     * 构造方法 实例化IndexWriter
     * 
     * @param indexDir
     * @throws Exception
     */
    public Indexer(String indexDir) throws Exception {
        Directory dir = FSDirectory.open(Paths.get(indexDir));// 根据路径获取存储索引的目录
        Analyzer analyzer = new StandardAnalyzer(); // 这里用了多态,StandardAnalyzer是标准分词器,Analyzer是一个分词器
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer); 
        writer = new IndexWriter(dir, iwc); 
    } 
    /** 
     * 关闭写索引 * * 
     * @throws Exception 
     */ 
    public void close() throws Exception { 
        writer.close(); 
    } 
    /** 
     * 索引指定目录的

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值