Luncene学习 第一天 《入门程序》

时间:2022-07-26
本文章向大家介绍Luncene学习 第一天 《入门程序》,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

整个luncene 流程

下面贴出代码

package com.zuoyan.lucene.demo;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StoredField;
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 org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

/**
 * Lucene 的第一个程序
 * 
 * @author zuoyan
 *
 */
public class LuceneDemo01 {

    /*
     * 创建索引 1.首先创建IndexWriter对象 他有两个参数 1.Directory 2.IndexWriterConfig
     */
    @Test
    public void testCreateIndex() throws Exception {
        String filePath = "G:\temp\index";
        Directory directory = FSDirectory.open(new File(filePath));
        Analyzer analyzer = new IKAnalyzer();
        IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
        IndexWriter indexWriter = new IndexWriter(directory, config);
        // 创建field对象,将field添加到document对象中
        File f = new File("G:\temp\files");
        File[] listFiles = f.listFiles();
        for (File file : listFiles) {
            // 创建Document对象。
            Document document = new Document();
            // 文件名称
            String fileName = file.getName();
            Field fileNameField = new TextField("fileName", fileName, Store.YES);
            // 文件大小
            long fileSize = FileUtils.sizeOf(file);
            Field fileSizeField = new LongField("fileSize", fileSize, Store.YES);
            // 文件路径
            String file_path = file.getPath();
            Field filePathField = new StoredField("filePath", file_path);
            // 文件内容
            String file_content = FileUtils.readFileToString(file);
            Field fileContentField = new TextField("fileContent", file_content, Store.NO);

            document.add(fileNameField);
            document.add(fileSizeField);
            document.add(filePathField);
            document.add(fileContentField);
            // 第四步:使用indexwriter对象将document对象写入索引库,此过程进行索引创建。并将索引和document对象写入索引库。
            indexWriter.addDocument(document);

        }

    }

}

创建出来的文件索引

原来的文件