lucene 创建索引

package com.cjr.lucene;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
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.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/**
 * 创建索引 对某个目录下的txt文件创建索引
 * 
 * @author chenjiarong
 * 
 */
public class Indexer {

	/**
	 * 索引存放目录
	 */
	private static String INDEXDIR = "F:\\工作区\\test";

	/**
	 * 文件存在目录
	 */
	private static String DATADIR = "F:\\其它\\文学";

	/**
	 * 后缀
	 */
	private static String SUFFIX = ".txt";

	/**
	 * 索引写入器
	 */
	private IndexWriter indexWriter;

	public static void main(String[] args) throws IOException {

		Indexer indexer = new Indexer(INDEXDIR);

		int numIndexed = 0;

		numIndexed = indexer.index(DATADIR, new TextFilesFilter());

		System.out.println("numIndexed: " + numIndexed);

		indexer.close();
	}

	/**
	 * 实例化索引写入器
	 * 
	 * @param inderDir
	 * @throws IOException
	 */
	public Indexer(String inderDir) throws IOException {
		// 目录
		Directory directory = FSDirectory.open(new File(inderDir));
		// 分词器
		Analyzer analyzer = new StandardAnalyzer();
		// 索引写入器配置
		IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_2,
				analyzer);
		config.setOpenMode(OpenMode.CREATE_OR_APPEND);
		indexWriter = new IndexWriter(directory, config);
	}

	/**
	 * 返回被索引文档数
	 * 
	 * @param dataDir
	 * @param fileFilter
	 * @return
	 * @throws IOException
	 */
	public int index(String dataDir, FileFilter fileFilter) throws IOException {
		File[] files = new File(dataDir).listFiles();
		for (File file : files) {
			if (!file.isDirectory() && !file.isHidden() && file.exists()
					&& file.canRead()
					&& (fileFilter == null || fileFilter.accept(file))) {
				indexFile(file);
			}
		}
		return indexWriter.numDocs();
	}

	/**
	 * 向Lucene索引中添加文档
	 * 
	 * @param file
	 * @throws IOException
	 */
	private void indexFile(File file) throws IOException {
		// 打印文本文件的完整路径
		System.out.println("Indexing " + file.getCanonicalPath());
		Document document = getDocument(file);
		indexWriter.addDocument(document);
	}

	/**
	 * 获取文件内容
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 */
	private Document getDocument(File file) throws IOException {
		Document document = new Document();
		// 文件内容
		document.add(new TextField("contents", getFileContent(file),Field.Store.YES));
		// 文件名称
		document.add(new TextField("filename", file.getName(), Field.Store.YES));
		// 文件完整路径
		document.add(new TextField("fullpath", file.getCanonicalPath(),
				Field.Store.YES));
		return document;
	}

	/**
	 * 根据文件的全路径获得所有的文件内容
	 * 
	 * @param fileName
	 * @param charset
	 * @return
	 * @throws Exception
	 */
	public String getFileContent(File file) {
		String everything = null;
		try {
			everything = new String(Files.readAllBytes(Paths.get(file.getCanonicalPath())),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return everything;
	}

	/**
	 * 关闭 indexWriter
	 * 
	 * @throws IOException
	 */
	public void close() throws IOException {
		indexWriter.close();
	}

	/**
	 * 文本文件过滤器
	 * 
	 * @author chenjiarong
	 * 
	 */
	private static class TextFilesFilter implements FileFilter {

		public boolean accept(File pathname) {
			return pathname.getName().toLowerCase().endsWith(SUFFIX);
		}

	}
}

以下是使用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]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值