Lucene-2.2.0 源代码阅读学习(1)

xiaoxiao2026-09-15  17

package org.apache.lucene.demo;

import org.apache.lucene.analysis.standard.StandardAnalyzer;import org.apache.lucene.index.IndexWriter;

import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.util.Date;

//为指定目录下的所有文件建立索引public class IndexFiles {private IndexFiles() {}static final File INDEX_DIR = new File("index");   //存放建立索引的目录public static void main(String[] args) {    String usage = "java org.apache.lucene.demo.IndexFiles <root_directory>";

// 如果在DOS下直接输入命令java org.apache.lucene.demo.IndexFiles,而没有指定目录名。    if (args.length == 0) {   //args没有接收到任何输入      System.err.println("Usage: " + usage);      System.exit(1);    }

// 如果在DOS下输入命令java org.apache.lucene.demo.IndexFiles myDir,而myDir=index目录已经存在。    if (INDEX_DIR.exists()) {      System.out.println("Cannot save index to '" +INDEX_DIR+ "' directory, please delete it first");      System.exit(1);    }    // 如果在DOS下输入命令java org.apache.lucene.demo.IndexFiles myDir,而myDir目录不存在,则无法创建索引,退出。    final File docDir = new File(args[0]); // 通过输入的第一个参数构造一个File    if (!docDir.exists() || !docDir.canRead()) {      System.out.println("Document directory '" +docDir.getAbsolutePath()+ "' does not exist or is not readable, please check the path");      System.exit(1);    }    // 如果不存在以上问题,按如下流程执行:    Date start = new Date();    try {      // 通过目录INDEX_DIR构造一个IndexWriter对象      IndexWriter writer = new IndexWriter(INDEX_DIR, new StandardAnalyzer(), true);      System.out.println("Indexing to directory '" +INDEX_DIR+ "'...");      indexDocs(writer, docDir);      System.out.println("Optimizing...");      writer.optimize();      writer.close();      // 计算创建索引文件所需要的时间      Date end = new Date();      System.out.println(end.getTime() - start.getTime() + " total milliseconds");

    } catch (IOException e) {      System.out.println(" caught a " + e.getClass() +       "\n with message: " + e.getMessage());    }}

static void indexDocs(IndexWriter writer, File file)    throws IOException {    // file可以读取    if (file.canRead()) {      if (file.isDirectory()) { // 如果file是一个目录(该目录下面可能有文件、目录文件、空文件三种情况)        String[] files = file.list(); // 获取file目录下的所有文件(包括目录文件)File对象,放到数组files里        //如果files!=null        if (files != null) {          for (int i = 0; i < files.length; i++) { // 对files数组里面的File对象递归索引,通过广度遍历            indexDocs(writer, new File(file, files[i]));          }        }      } else { // 到达叶节点时,说明是一个File,而不是目录,则建立索引        System.out.println("adding " + file);        try {          writer.addDocument(FileDocument.Document(file)); // 通过writer,使用file对象构造一个Document对象,添加到writer中,以便能够通过建立的索引查找到该文件

        }        catch (FileNotFoundException fnfe) {          ;        }      }    }}}

上面是一个简单的Demo,主要使用了org.apache.lucene.index包里面的IndexWriter类。IndexWriter有很多构造方法,这个Demo使用了它的如下的构造方法,使用String类型的目录名作为参数之一构造一个索引器:

public IndexWriter(String path, Analyzer a, boolean create)       throws CorruptIndexException, LockObtainFailedException, IOException {    init(FSDirectory.getDirectory(path), a, create, true, null, true);}

这里,FSDirectory是文件系统目录,该类的方法都是static的,可以直接方便地获取与文件系统目录相关的一些参数,以及对文件系统目录的操作FSDirectory类继承自抽象类Directory。

如果想要建立索引,需要从IndexWriter的构造方法开始入手:

可以使用一个File对象构造一个索引器:

public IndexWriter(File path, Analyzer a, boolean create)       throws CorruptIndexException, LockObtainFailedException, IOException {    init(FSDirectory.getDirectory(path), a, create, true, null, true);}

可以使用一个Directory对象构造

public IndexWriter(Directory d, Analyzer a, boolean create)       throws CorruptIndexException, LockObtainFailedException, IOException {    init(d, a, create, false, null, true);}

使用具有两个参数的构造函数老构造索引器,指定一个与文件系统目录有关的参数,和一个分词工具,IndexWriter类提供了3个:

public IndexWriter(String path, Analyzer a)     throws CorruptIndexException, LockObtainFailedException, IOException {    init(FSDirectory.getDirectory(path), a, true, null, true);}

public IndexWriter(File path, Analyzer a)     throws CorruptIndexException, LockObtainFailedException, IOException {    init(FSDirectory.getDirectory(path), a, true, null, true);}

public IndexWriter(Directory d, Analyzer a)     throws CorruptIndexException, LockObtainFailedException, IOException {    init(d, a, false, null, true);}

另外,还有5个构造方法,可以参考源文件IndexWriter类。

Analyzer是一个抽象类,能够对数据源进行分析过滤主要功能是进行分词

package org.apache.lucene.analysis;

java.io.Reader;public abstract class Analyzer {public abstract TokenStream tokenStream(String fieldName, Reader reader);

public int getPositionIncrementGap(String fieldName){    return 0;}}

通过使用StandardAnalyzer类(继承自Analyzer抽象类),构造一个索引器IndexWriter。StandardAnalyzer类,对进行检索的word进行了过滤,因为在检索的过程中,有很多对检索需求没有用处的单词。比如一些英文介词:at、with等等,StandardAnalyzer类对其进行了过滤。看下StandardAnalyzer类的源代码:

package org.apache.lucene.analysis.standard;

import org.apache.lucene.analysis.*;

import java.io.File;import java.io.IOException;import java.io.Reader;import java.util.Set;

public class StandardAnalyzer extends Analyzer {private Set stopSet;

// StopAnalyzer类对检索的关键字进行过滤,这些关键字如果以STOP_WORDS数组中指定的word结尾public static final String[] STOP_WORDS = StopAnalyzer.ENGLISH_STOP_WORDS;

// 构造一个StandardAnalyzer分析器,下面的几个构造函数都是以不同的方式构造一个限制检索关键字结尾字符串的StandardAnalyzer分析器,可以使用默认的,也可以根据自己的需要设置public StandardAnalyzer() {    this(STOP_WORDS);}public StandardAnalyzer(Set stopWords) {    stopSet = stopWords;}public StandardAnalyzer(String[] stopWords) {    stopSet = StopFilter.makeStopSet(stopWords);}public StandardAnalyzer(File stopwords) throws IOException {    stopSet = WordlistLoader.getWordSet(stopwords);}public StandardAnalyzer(Reader stopwords) throws IOException {    stopSet = WordlistLoader.getWordSet(stopwords);}

看看StopAnalyzer类,它的构造方法和StandardAnalyzer类的很相似,其中默认的ENGLISH_STOP_WORDS指定了下面这些

public static final String[] ENGLISH_STOP_WORDS = {    "a", "an", "and", "are", "as", "at", "be", "but", "by",    "for", "if", "in", "into", "is", "it",    "no", "not", "of", "on", "or", "such",    "that", "the", "their", "then", "there", "these",    "they", "this", "to", "was", "will", "with"};

也可以使用带参数的构造函数,根据需要自己指定

转载请注明原文地址: https://www.6miu.com/read-5052717.html

最新回复(0)