- Lucene 教程
- Lucene - 首页
- Lucene - 概述
- Lucene - 环境设置
- Lucene - 第一个应用程序
- Lucene - 索引类
- Lucene - 搜索类
- Lucene - 索引过程
- Lucene - 索引操作
- Lucene - 搜索操作
- Lucene - 查询编程
- Lucene - 分析
- Lucene - 排序
- Lucene 有用资源
- Lucene - 快速指南
- Lucene - 有用资源
- Lucene - 讨论
Lucene - 第一个应用程序
在本章中,我们将学习使用 Lucene 框架进行实际编程。在开始使用 Lucene 框架编写第一个示例之前,您必须确保已正确设置了 Lucene 环境,如 Lucene - 环境设置 教程中所述。建议您具备 Eclipse IDE 的使用经验。
现在让我们继续编写一个简单的搜索应用程序,该应用程序将打印找到的搜索结果数量。我们还将查看在此过程中创建的索引列表。
步骤 1 - 创建 Java 项目
第一步是使用 Eclipse IDE 创建一个简单的 Java 项目。选择 文件 > 新建 -> 项目 选项,然后从向导列表中选择 Java 项目 向导。现在使用向导窗口将您的项目命名为 LuceneFirstApplication,如下所示:
项目创建成功后,您将在 项目资源管理器 中看到以下内容:
步骤 2 - 添加所需的库
现在让我们在项目中添加 Lucene 核心框架库。为此,右键单击您的项目名称 LuceneFirstApplication,然后选择上下文菜单中提供的以下选项:构建路径 -> 配置构建路径 以显示 Java 构建路径窗口,如下所示:
现在使用 库 选项卡下可用的 添加外部 JAR 按钮,从 Lucene 安装目录添加以下核心 JAR 文件:
- lucene-core-3.6.2
步骤 3 - 创建源文件
现在让我们在 LuceneFirstApplication 项目下创建实际的源文件。首先,我们需要创建一个名为 com.tutorialspoint.lucene. 的包。为此,右键单击包资源管理器部分中的 src,然后选择选项:新建 -> 包。
接下来,我们将在 com.tutorialspoint.lucene 包下创建 LuceneTester.java 和其他 Java 类。
LuceneConstants.java
此类用于提供将在整个示例应用程序中使用的各种常量。
package com.tutorialspoint.lucene;
public class LuceneConstants {
public static final String CONTENTS = "contents";
public static final String FILE_NAME = "filename";
public static final String FILE_PATH = "filepath";
public static final int MAX_SEARCH = 10;
}
TextFileFilter.java
此类用作 .txt 文件 过滤器。
package com.tutorialspoint.lucene;
import java.io.File;
import java.io.FileFilter;
public class TextFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".txt");
}
}
Indexer.java
此类用于索引原始数据,以便我们可以使用 Lucene 库对其进行搜索。
package com.tutorialspoint.lucene;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Indexer {
private IndexWriter writer;
public Indexer(String indexDirectoryPath) throws IOException {
//this directory will contain the indexes
Directory indexDirectory =
FSDirectory.open(new File(indexDirectoryPath));
//create the indexer
writer = new IndexWriter(indexDirectory,
new StandardAnalyzer(Version.LUCENE_36),true,
IndexWriter.MaxFieldLength.UNLIMITED);
}
public void close() throws CorruptIndexException, IOException {
writer.close();
}
private Document getDocument(File file) throws IOException {
Document document = new Document();
//index file contents
Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file));
//index file name
Field fileNameField = new Field(LuceneConstants.FILE_NAME,
file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED);
//index file path
Field filePathField = new Field(LuceneConstants.FILE_PATH,
file.getCanonicalPath(),Field.Store.YES,Field.Index.NOT_ANALYZED);
document.add(contentField);
document.add(fileNameField);
document.add(filePathField);
return document;
}
private void indexFile(File file) throws IOException {
System.out.println("Indexing "+file.getCanonicalPath());
Document document = getDocument(file);
writer.addDocument(document);
}
public int createIndex(String dataDirPath, FileFilter filter)
throws IOException {
//get all files in the data directory
File[] files = new File(dataDirPath).listFiles();
for (File file : files) {
if(!file.isDirectory()
&& !file.isHidden()
&& file.exists()
&& file.canRead()
&& filter.accept(file)
){
indexFile(file);
}
}
return writer.numDocs();
}
}
Searcher.java
此类用于搜索 Indexer 创建的索引以搜索请求的内容。
package com.tutorialspoint.lucene;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Searcher {
IndexSearcher indexSearcher;
QueryParser queryParser;
Query query;
public Searcher(String indexDirectoryPath)
throws IOException {
Directory indexDirectory =
FSDirectory.open(new File(indexDirectoryPath));
indexSearcher = new IndexSearcher(indexDirectory);
queryParser = new QueryParser(Version.LUCENE_36,
LuceneConstants.CONTENTS,
new StandardAnalyzer(Version.LUCENE_36));
}
public TopDocs search( String searchQuery)
throws IOException, ParseException {
query = queryParser.parse(searchQuery);
return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
}
public Document getDocument(ScoreDoc scoreDoc)
throws CorruptIndexException, IOException {
return indexSearcher.doc(scoreDoc.doc);
}
public void close() throws IOException {
indexSearcher.close();
}
}
LuceneTester.java
此类用于测试 lucene 库的索引和搜索功能。
package com.tutorialspoint.lucene;
import java.io.IOException;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
public class LuceneTester {
String indexDir = "E:\\Lucene\\Index";
String dataDir = "E:\\Lucene\\Data";
Indexer indexer;
Searcher searcher;
public static void main(String[] args) {
LuceneTester tester;
try {
tester = new LuceneTester();
tester.createIndex();
tester.search("Mohan");
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
private void createIndex() throws IOException {
indexer = new Indexer(indexDir);
int numIndexed;
long startTime = System.currentTimeMillis();
numIndexed = indexer.createIndex(dataDir, new TextFileFilter());
long endTime = System.currentTimeMillis();
indexer.close();
System.out.println(numIndexed+" File indexed, time taken: "
+(endTime-startTime)+" ms");
}
private void search(String searchQuery) throws IOException, ParseException {
searcher = new Searcher(indexDir);
long startTime = System.currentTimeMillis();
TopDocs hits = searcher.search(searchQuery);
long endTime = System.currentTimeMillis();
System.out.println(hits.totalHits +
" documents found. Time :" + (endTime - startTime));
for(ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = searcher.getDocument(scoreDoc);
System.out.println("File: "
+ doc.get(LuceneConstants.FILE_PATH));
}
searcher.close();
}
}
步骤 4 - 数据和索引目录创建
我们使用了从 record1.txt 到 record10.txt 的 10 个文本文件,其中包含学生姓名和其他详细信息,并将它们放在 E:\Lucene\Data 目录中。 测试数据。应创建索引目录路径为 E:\Lucene\Index。运行此程序后,您可以在该文件夹中看到创建的索引文件列表。
步骤 5 - 运行程序
完成源代码、原始数据、数据目录和索引目录的创建后,您就可以编译和运行程序了。为此,保持 LuceneTester.Java 文件选项卡处于活动状态,然后使用 Eclipse IDE 中可用的 运行 选项或使用 Ctrl + F11 编译并运行您的 LuceneTester 应用程序。如果应用程序成功运行,它将在 Eclipse IDE 的控制台中打印以下消息:
Indexing E:\Lucene\Data\record1.txt Indexing E:\Lucene\Data\record10.txt Indexing E:\Lucene\Data\record2.txt Indexing E:\Lucene\Data\record3.txt Indexing E:\Lucene\Data\record4.txt Indexing E:\Lucene\Data\record5.txt Indexing E:\Lucene\Data\record6.txt Indexing E:\Lucene\Data\record7.txt Indexing E:\Lucene\Data\record8.txt Indexing E:\Lucene\Data\record9.txt 10 File indexed, time taken: 109 ms 1 documents found. Time :0 File: E:\Lucene\Data\record4.txt
成功运行程序后,您的 索引目录 中将包含以下内容: