`
lxwt909
  • 浏览: 570893 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Lucene5学习之创建索引入门示例

阅读更多

    Lucene更新实在太快了,只好紧跟脚步开始学习Lucene5,花了点时间写了一个demo,就是程序根据用户提供的一个文件夹,读取该文件夹下的所有文件,然后读取文件里的内容写入索引。读取文件部分采用的是最新的NIO2.0API,因此,JDK必须使用1.7及以上版本。Lucene5开发压缩包请在Lucene官网下载。不多说了,对于码农来说,最直接的就是上代码。

package com.yida.framework.lucene5.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

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.LongField;
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.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

/**
 * 读取硬盘文件,创建索引
 * 
 * @author Lanxiaowei
 * 
 */
@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
public class IndexFile {
	public static void main(String[] args) throws IOException {
		String dirPath = "D:/docPath";
		String indexPath = "D:/lucenedir";
		createIndex(dirPath, indexPath);
	}
	
	/**
	 * 创建索引
	 * @param dirPath       需要读取的文件所在文件目录
	 * @param indexPath     索引存放目录
	 * @throws IOException
	 */
	public static void createIndex(String dirPath, String indexPath) throws IOException {
		createIndex(dirPath, indexPath, false);
	}
	
	/**
	 * 创建索引
	 * @param dirPath         需要读取的文件所在文件目录
	 * @param indexPath       索引存放目录
	 * @param createOrAppend  始终重建索引/不存在则追加索引
	 * @throws IOException
	 */
	public static void createIndex(String dirPath, String indexPath,
			boolean createOrAppend) throws IOException {
		long start = System.currentTimeMillis();
		Directory dir = FSDirectory.open(Paths.get(indexPath, new String[0]));
		Path docDirPath = Paths.get(dirPath, new String[0]);
		Analyzer analyzer = new StandardAnalyzer();
		IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);

		if (createOrAppend) {
			indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
		} else {
			indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
		}
		IndexWriter writer = new IndexWriter(dir, indexWriterConfig);
		indexDocs(writer, docDirPath);
		writer.close();
		long end = System.currentTimeMillis();
		System.out.println("Time consumed:" + (end - start) + " ms");
	}

	/**
	 * 
	 * @param writer
	 *            索引写入器
	 * @param path
	 *            文件路径
	 * @throws IOException
	 */
	public static void indexDocs(final IndexWriter writer, Path path)
			throws IOException {
		// 如果是目录,查找目录下的文件
		if (Files.isDirectory(path, new LinkOption[0])) {
			System.out.println("directory");
			Files.walkFileTree(path, new SimpleFileVisitor() {
				@Override
				public FileVisitResult visitFile(Object file,
						BasicFileAttributes attrs) throws IOException {
					Path path = (Path)file;
					System.out.println(path.getFileName());
					indexDoc(writer, path, attrs.lastModifiedTime().toMillis());
					return FileVisitResult.CONTINUE;
				}
			});
		} else {
			indexDoc(writer, path,
					Files.getLastModifiedTime(path, new LinkOption[0])
							.toMillis());
		}
	}

	/**
	 * 读取文件创建索引
	 * 
	 * @param writer
	 *            索引写入器
	 * @param file
	 *            文件路径
	 * @param lastModified
	 *            文件最后一次修改时间
	 * @throws IOException
	 */
	public static void indexDoc(IndexWriter writer, Path file, long lastModified)
			throws IOException {
		InputStream stream = Files.newInputStream(file, new OpenOption[0]);
		Document doc = new Document();

		Field pathField = new StringField("path", file.toString(),
				Field.Store.YES);
		doc.add(pathField);

		doc.add(new LongField("modified", lastModified, Field.Store.NO));
		doc.add(new TextField("contents", new BufferedReader(
				new InputStreamReader(stream, StandardCharsets.UTF_8))));

		if (writer.getConfig().getOpenMode() == IndexWriterConfig.OpenMode.CREATE) {
			System.out.println("adding " + file);
			writer.addDocument(doc);
		} else {
			System.out.println("updating " + file);
			writer.updateDocument(new Term("path", file.toString()), doc);
		}
		writer.commit();
	}
}

 项目采用的是Maven构建,怎么创建Maven Project就不用介绍了吧,我就贴下pom配置吧。

<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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.yida.framework</groupId>
	<artifactId>lucene5</artifactId>
	<packaging>war</packaging>
	<version>1.0</version>
	<name>lucene5 Maven Webapp</name>
	<url>http://maven.apache.org</url>
	
	<properties>
	    <lucene.version>5.0.0</lucene.version>
	</properties>
	
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.lucene</groupId>
			<artifactId>lucene-core</artifactId>
			<version>${lucene.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.lucene</groupId>
			<artifactId>lucene-analyzers-common</artifactId>
			<version>${lucene.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.lucene</groupId>
			<artifactId>lucene-queryparser</artifactId>
			<version>${lucene.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.lucene</groupId>
			<artifactId>lucene-highlighter</artifactId>
			<version>${lucene.version}</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>lucene5</finalName>
	</build>
</project>

 项目结构图如图:



 运行之前,先在D盘新建两个文件夹,如图:



 然后在docPath文件夹里随便放几个文本文件,如图:



 然后运行测试类,就会在lucenedir文件夹下创建索引。

代码很简单,没什么需要过多解释的,demo源码请在附件里下载。

希望能对大家学习Lucene有所帮助,其次也算是对自己学习轨迹的一个记录,写博客这个习惯

我会努力保持下去。

若你还有什么疑问,请加我Q-Q:7-3-6-0-3-1-3-0-5,或者加裙:


,欢迎你加入一起交流学习。
 

  • 大小: 135.9 KB
  • 大小: 168.5 KB
  • 大小: 102.7 KB
  • 大小: 6 KB
分享到:
评论
3 楼 徐小白520 2015-12-05  
不知道你这篇Lucene5学习之分页查询是否基于这个IndexFile 产生的索引文件。我想说的是
doc.add(new TextField("contents", new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))));

这个不会把文件内容存储到索引文件中,也就是查询索引文件,输出contens内容会为null。
如果你们继续学博主下一篇文章,你们要注意,不要奇怪为什么输出结果不一样。 
2 楼 majiedota 2015-06-29  
1 楼 rubricate 2015-03-31  
终于看到写lucene5的 牛人了
欢迎加入我们的elasticsearch群 211682609
还有我们的 问答社区 http://elasticsearch.cn

相关推荐

    Lucene 4.8全文检索引擎入门示例文档

    1. **创建索引** 首先,创建一个 Directory 对象,然后使用 IndexWriter 初始化,设置好 Analyzer。接着,创建 Document 对象,添加 Field,如标题、内容等,最后通过 IndexWriter 将文档写入索引。 2. **分析...

    Lucene创建与搜索索引

    本文将重点介绍如何使用Lucene创建索引以及如何基于这些索引进行高效的搜索。 #### 二、创建索引 ##### 2.1 准备工作 在开始之前,我们需要做一些准备工作: - **安装Java环境**:Lucene基于Java开发,因此首先...

    Lucene入门示例

    以上就是一个基础的Lucene入门示例,展示了如何使用Lucene创建索引、添加文档以及执行搜索。当然,实际应用中,Lucene的功能远不止这些,还包括更复杂的查询表达式、评分机制、多字段索引、倒排索引优化、近实时搜索...

    lucene入门小例子

    在“lucene入门小例子”中,可能包含创建索引、添加文档、查询和显示结果等基本操作的示例代码。这些代码将帮助你了解如何在实际项目中集成和使用Lucene,进一步熟悉全文检索的原理和实践。 在学习过程中,你可能会...

    lucene 入门

    `lucene入门小实例.txt` 文件中可能包含了一个简单的Lucene使用示例,例如: 1. 创建 `Directory` 对象,比如使用 `FSDirectory.open()` 打开一个文件系统的目录来存储索引。 2. 实例化 `Analyzer`,如使用 `...

    Lucene索引搜索简介以及入门实例源码.rar

    这个压缩包中的内容可能是关于如何使用Lucene进行全文检索的一个基础教程和示例代码。 **一、Lucene的基本概念** 1. **文档(Document)**:在Lucene中,每个要被搜索的信息被看作一个文档,可以包含多个字段...

    lucene学习入门程序

    **Lucene学习入门程序** Lucene是一个开源的全文搜索引擎库,由Apache软件基金会开发并维护。它是Java编写,可以被集成到各种应用中,提供强大的文本检索功能。本程序是针对初学者设计的,旨在帮助开发者快速理解并...

    lucene搜索的简单入门例子源代码

    1. **创建索引**:首先,你需要创建一个`Directory`对象,这可以是内存中的`RAMDirectory`或磁盘上的`FSDirectory`。然后,使用`IndexWriter`实例化一个对象,设置好分词器(如这里提到的JE分词器),将文档添加到...

    最新全文检索 lucene-5.2.1 入门经典实例

    在提供的"lucene5.2.1入门经典案例"中,你可以找到如何创建索引、执行查询、高亮显示结果等具体操作的示例代码。这些案例可以帮助初学者快速理解和应用Lucene-5.2.1的核心功能。通过实践,你可以更深入地了解Lucene...

    lucene学习资料

    通常会涵盖如何创建索引、如何添加、更新和删除文档,以及如何对索引进行查询。 2. **关于lucene2.0的创建、检索和删除功能的完整实现.doc** Lucene 2.0版本的教程,可能讲解了如何利用Lucene API实现文档的索引...

    Lucene 3.0完成入门

    通过以上内容的学习,你可以掌握 Lucene 3.0 的基本操作,包括如何创建索引、执行查询、优化搜索性能等。同时,了解 Compass 如何简化 Lucene 的使用,以及如何结合实际业务需求来设计和实现一个搜索引擎。在实践中...

    lucene 入门资料包

    1. **创建索引**: 首先,你需要创建一个`IndexWriter`实例,选择合适的`Directory`和`Analyzer`,然后添加文档到索引。 2. **搜索索引**: 使用`IndexSearcher`和`QueryParser`来构造和执行查询,`Searcher`会返回...

    lucene3.0.0 入门DEMO

    "luceneTest"这个文件可能是DEMO的主程序或测试代码,包含创建索引和执行搜索的示例。在学习这个DEMO时,重点应放在理解如何配置Analyzer,如何创建和管理IndexWriter,如何解析和执行查询,以及如何处理搜索结果。 ...

    Lucene建立索引

    - `LuceneTest`可能是这个项目的主要测试类,它可能包含创建索引、查询索引以及展示结果的代码示例。 - 学习该项目,应关注如何实例化`Directory`(如`FSDirectory`)、选择合适的`Analyzer`(如`StandardAnalyzer...

    Lucene简单实例记录

    3. **创建索引**: - 遍历数据文件目录下的所有文本文件。 - 对于每个文本文件,创建一个`Document`对象,并添加字段,如文件路径和内容。 - 使用`IndexWriter`将`Document`写入索引。 #### 进行搜索 搜索功能...

    lucene3.6入门实例教程

    这份教程通过完整的代码示例,为学习者提供了实践操作的机会,从而深入理解Lucene的核心机制。 首先,了解Lucene的基本架构至关重要。Lucene的核心组件包括索引器(Indexer)、查询解析器(Query Parser)和搜索器...

Global site tag (gtag.js) - Google Analytics