Lucene创建索引

所有的代码都是基于maven管理的.
    环境:
        maven: 3.3.3
        eclipse
        jdk7, tomcat7, mac系统
    pom.xml展示

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zero.lucene</groupId>
  <artifactId>Lucene</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-core</artifactId>
        <version>5.1.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-queryparser</artifactId>
        <version>5.1.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-analyzers-common</artifactId>
        <version>5.1.0</version>
    </dependency>

    <!-- 中文分词 -->
    <dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-analyzers-smartcn</artifactId>
        <version>5.1.0</version>
    </dependency>

    <!-- 关键词高亮 -->
    <dependency>
        <groupId>org.apache.lucene</groupId>
        <artifactId>lucene-highlighter</artifactId>
        <version>5.1.0</version>
    </dependency>

  </dependencies>
</project>

    创建索引

package com.zero.lucene;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
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.Store;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;

/**
 * 建立索引
 * @author samuel
 */
public class Indexer {
    private IndexWriter writer;

    /**
     * 实例化写入索引的对象
     * @param saveDir       索引写入的位置(建立好的索引存放的位置)
     * @throws Exception
     */
    public Indexer(String saveDir) throws Exception{
        FSDirectory fsdDir = FSDirectory.open(Paths.get(saveDir));
        // 标准分词器
        Analyzer analyzer = new StandardAnalyzer();
        IndexWriterConfig conf = new IndexWriterConfig(analyzer);
        writer = new IndexWriter(fsdDir, conf);
    }

    /**
     * 关闭写入流
     * @throws IOException
     */
    public void close() throws IOException {
        writer.close();
    }

    public void index(String dataDir) throws Exception {

        // 需要索引数据的目录
        /**
         * 1. 查询到目录下所有的文件
         * 2. 对每个文件进行建立索引
         */
//      String dataDir = "/Users/samuel/Documents/lucene/lucene/";
        // 1
        File[] files = new File(dataDir).listFiles();
        for (File file : files) {
            // 2 对每个文件进行索引
            indexFile(file);
        }
        System.out.println(writer.numDocs());
        writer.close();
    }

    private void indexFile(File file) throws IOException {
        Document doc = getDcoument(file);
        writer.addDocument(doc);
    }

    private Document getDcoument(File file) throws FileNotFoundException {
        Document doc = new Document();
        doc.add(new TextField("contents", new FileReader(file)));
        doc.add(new TextField("fileName", file.getName(), Store.YES));
        return doc;
    }


    public static void main(String[] args) {
        String saveDir = "/Users/samuel/Documents/lucene";
        String dataDir = "/Users/samuel/Documents/lucene/lucene";
        Indexer indexer = null;
        try {
            indexer = new Indexer(saveDir);
            indexer.index(dataDir);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                indexer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

一个原生态的Lucene创建索引就这样OK啦.

以下是使用Lucene创建索引的一个完整代码示例。该示例展示了如何配置`IndexWriter`以及如何向索引中添加文档。 ### 使用Lucene创建索引的代码示例 ```java import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.StringField; 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; import org.apache.lucene.util.Version; import java.io.File; import java.nio.file.Paths; public class LuceneIndexExample { public static void main(String[] args) throws Exception { // 定义存储索引的位置 Directory directory = FSDirectory.open(Paths.get("indexDir")); // 创建StandardAnalyzer实例用于分词 StandardAnalyzer analyzer = new StandardAnalyzer(); // 配置IndexWriter IndexWriterConfig config = new IndexWriterConfig(analyzer); IndexWriter indexWriter = new IndexWriter(directory, config); // 创建Document对象 Document doc = new Document(); // 添加字段到Document中 String id = "1"; String content = "This is the content of a sample document."; doc.add(new StringField("id", id, Field.Store.YES)); doc.add(new TextField("content", content, Field.Store.NO)); // 将Document写入索引 indexWriter.addDocument(doc); // 提交更改并关闭IndexWriter indexWriter.commit(); indexWriter.close(); System.out.println("索引创建完成!"); } } ``` 这段代码实现了以下几个功能: - 设置索引存储位置,这里选择了文件系统中的指定路径[^2]。 - 初始化了一个`StandardAnalyzer`来解析文本内容[^3]。 - 配置了`IndexWriter`及其对应的分析器[^5]。 - 构建了一个包含两个字段(`id` 和 `content`)的`Document`对象,并将其添加至索引中[^4]。 #### 关键点说明 - `StringField` 是一种不可分割的字段类型,适合用来保存唯一标识符等不需要进一步处理的内容。 - `TextField` 则适用于需要被全文检索的文本数据,在加入索引前会被分析器分解成多个词条[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值