开发手册 欢迎您!
软件开发者资料库

Lucene - 索引过程

Lucene索引过程 - 使用java从简单易用的步骤学习Lucene,使用从Lucene搜索引擎,索引类,搜索类,索引过程,索引操作,搜索操作,查询编程,分析,排序等基础到高级知识的初学者教程。

索引过程是Lucene提供的核心功能之一.下图说明了索引过程和类的使用. IndexWriter是索引过程中最重要和最核心的组件.

索引过程

我们将包含 Field 文档添加到IndexWriter,后者使用 Analyzer 分析文档,然后根据需要创建/打开/编辑索引,并在目录中存储/更新它们. IndexWriter 用于更新或创建索引.它不用于读取索引.

现在我们将逐步向您展示如何使用基本示例了解索引过程.

创建文档

  • 创建一个从文本文件中获取lucene文档的方法.

  • 创建各种类型的字段,这些字段是包含键作为名称和值的键值对,作为要编制索引的内容.


  • 设置要分析的字段.在我们的例子中,只分析内容,因为它可以包含搜索操作中不需要的数据,如a,am,are等.


  • 将新创建的字段添加到文档对象并将其返回给调用方法.

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;}

创建IndexWriter

IndexWriter类充当在此期间创建/更新索引的核心组件索引过程.按照以下步骤创建IndexWriter :

步骤1 : 创建IndexWriter的对象.

步骤2 : 创建一个Lucene目录,该目录应指向要存储索引的位置.

步骤3 : 初始化使用索引目录创建的IndexWriter对象,标准分析器具有版本信息和其他必需/可选参数.

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);}

开始索引过程

以下程序显示了如何启动索引过程 :

private void indexFile(File file) throws IOException {   System.out.println("Indexing "+file.getCanonicalPath());   Document document = getDocument(file);   writer.addDocument(document);}

示例应用程序

要测试索引过程,我们需要创建一个Lucene应用程序测试.

Step描述
1

在包 com.it1352.lucene下创建一个名为 LuceneFirstApplication 的项目 Lucene  -  First Application章节中所述.您还可以使用在 Lucene  -  First Application 章节中创建的项目来了解索引过程.

2

创建 LuceneConstants.java, TextFileFilter.java Indexer.java ,如 Lucene  -  First Application 章节中所述.保持其余文件不变.

3

创建 LuceneTester.java ,如下所述.

4

清理并构建应用程序确保业务逻辑按照要求运行.

LuceneConstants.java

此类用于提供在示例应用程序中使用的各种常量.

package com.it1352.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.it1352.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.it1352.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();   }}

LuceneTester.java

此类用于测试索引Lucene库的功能.

package com.it1352.lucene; import java.io.IOException;public class LuceneTester {   String indexDir = "E:\\Lucene\\Index";   String dataDir = "E:\\Lucene\\Data";   Indexer indexer;      public static void main(String[] args) {      LuceneTester tester;      try {         tester = new LuceneTester();         tester.createIndex();      } catch (IOException 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");   }}

数据&索引目录创建

我们使用了record1.txt中的10个文本文件到包含学生姓名和其他详细信息的record10.txt,并将它们放在 E:\ Lucene目录中\ Data. 测试数据.应将索引目录路径创建为 E:\Lucene\Index .运行此程序后,您可以看到在该文件夹中创建的索引文件列表.

运行程序

完成创建后您可以通过编译和运行程序来完成源,原始数据,数据目录和索引目录.为此,请保持LuceneTester.Java文件选项卡处于活动状态,并使用Eclipse IDE中提供的运行选项或使用 Ctrl + F11 编译并运行 LuceneTester 应用程序.如果您的应用程序成功运行,它将在Eclipse IDE的控制台中打印以下消息 :

Indexing E:\Lucene\Data\record1.txtIndexing E:\Lucene\Data\record10.txtIndexing E:\Lucene\Data\record2.txtIndexing E:\Lucene\Data\record3.txtIndexing E:\Lucene\Data\record4.txtIndexing E:\Lucene\Data\record5.txtIndexing E:\Lucene\Data\record6.txtIndexing E:\Lucene\Data\record7.txtIndexing E:\Lucene\Data\record8.txtIndexing E:\Lucene\Data\record9.txt10 File indexed, time taken: 109 ms

一旦你有了成功运行程序,您将在索引目录中删除以下内容 :  

Lucene索引目录