Lucene--001创建索引

本文介绍如何使用Lucene35版本创建文本索引,包括配置环境、编写代码等步骤,并提供了一个简单的示例程序。

这里使用两个版本我一个是Lucene35 ,另外一个版本是一个Lucene46

Lucene35就一个jar包,到了Lucene46中就分成了7个jar包了。

第一个Lucene35

具体步骤: 创建索引的步骤

1、创建目录

2、创建IndexWriter

3、创建Docment对象

4、为Document添加Field

5、通过Indexwriter添加文档到索引中

 <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
    </dependency>

    <dependency>
      <groupId>org.apache.lucene</groupId>
      <artifactId>lucene-core</artifactId>
      <version>3.5.0</version>
    </dependency>
创建索引

package com.lk;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by LK on 2016/12/16.
 */
public class HelloLucene {

    /*建立索引*/
    public void  index(){
        //2创建IndexWriter
        IndexWriter writer=null;
        try {
            //1创建Directory
            // Directory directory= new RAMDirectory();//建立内存中
            Directory directory = FSDirectory.open(new File("d:/lucene/index01")); //建立到硬盘上
            IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_35, new StandardAnalyzer(Version.LUCENE_35));
            writer=new IndexWriter(directory,iwc);
            //3创建docment对象(相当于表中的一条记录)
            Document document=null;
            //4为Document添加Field
            File f = new File("D:/lucene/example");
            for(File file:f.listFiles()){
                document = new Document();
                document.add(new Field("content",new FileReader(file)));
                document.add(new Field("filename",file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED));
                document.add(new Field("path",file.getAbsolutePath(),Field.Store.YES,Field.Index.NOT_ANALYZED));
                //5 通过IndexWriter添加文档到索引中
                writer.addDocument(document);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(writer!=null) try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
第三步进行测试

package com.lk;

import org.junit.Test;

/**
 * Created by LK on 2016/12/17.
 */

public class TestLucene {
    @Test
    public  void  testIndex(){
        HelloLucene h1= new HelloLucene();
        h1.index();
    }
}
得到的目录是这样的:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值