---
title: "Lucene简介及入门使用"
author: "wadefall"
date: "2010-12-09T21:35:22Z"
tags: []
categories: ["非技术"]
slug: "lucene"
draft: false
lastmod: "2010-12-09T21:35:22Z"
id: 838000
url: "https://wadefall.iteye.com/blog/838000"
---

Lucene是apache软件基金会的一个子项目，是一个开放源代码的全文搜索引擎工具包，是一个全文搜索引擎的架构，而不是一个完整的全文搜索引擎。我使用它来建立一个垂直的全文搜索引擎，是课程大作业的一部分，用来记录一下实现过程。
    
    搜索引擎的工作过程大体可以分为建立索引和搜索两个阶段，按照这个过程来部署。

**一、相关环境的配置**

1.我使用的jdk版本是1.6.0_10-rc2。

2.Lucene本身包含有7个包：analysis，document，index，queryParser，search，store，util；一个一个地导入classpath太麻烦，可以使用集成过了的jar。我使用的是lucene-core-2.3.2.jar。
   
**二、建立索引阶段**

1.几个相关概念

1)**Index **
索引库，在Lucene中并不存在Index的类。通过IndexWriter来写索引，通过IndexReader来读索引。

2)**Analyzer**
分析器，就是实现分词的工具。一段有意义的文字通过Analyzer分割成一个个词语后才能按关键词搜索。最常用的分析器是StandardAnalyzer。不同的语言可以使用不同的分析器，由于我们的分析目标是SIGIR的论文，都是英文，因此我们采用StandardAnalyzer。

3)**Document**
一个Document代表索引库中的一条记录。要搜索的信息封装成Document后通过IndexWriter写入索引库。调用Searcher接口按关键词搜索后，返回的也是一个封装后的Document列表。

4)**field**
一个Document可以包含多个列，叫做field。例如一篇文章可以包含“标题”、“作者”、“正文”等field，创建这些列对象以后，可以通过Document的add方法增加这些列。

5)**Term**
Term是搜索语法的最小单位。复杂的搜索语法会分解成一个个的Term查询。它表示文档的一个词语。Term由两部分组成：它表示的词语和这个词语所出现的field。


2.需要使用到的几个接口

1)**IndexWriter**
IndexWriter(String path, Analyzer a, boolean create)，
path为文件路径，a为分析器，create表示是否重建索引(true：建立或者覆盖已存在的索引，false：扩展已存在的索引)。


```java
IndexWriter writer = new IndexWriter(path,
				new StandardAnalyzer(), true);

```

2)**Field**
Field(String name, String string, boolean store, boolean index, boolean token)，
Indexed：如果字段是Indexed的，表示这个字段是可检索的。
Stored：如果字段是Stored的，表示这个字段的值可以从检索结果中得到。
Tokenized：如果一个字段是Tokenized的，表示它是有经过Analyzer转变后成为一个tokens序列，在这个转变过程tokenization中，Analyzer提取出需要进行索引的文本，而剔除一些冗余的词句。


```java
Field field1 = new Field(name, strName, Field.Store.YES,
				Field.Index.TOKENIZED);
```



**三、索引阶段**
1.需要使用的接口

1)**QueryParser**
QueryParser .parse(String query, String field, Analyzer analyzer)
query为检索词，field为检索的字段名，analyzer为分析器。


```java
Query query = QueryParser.parse(serchString, fields,
				new StandardAnalyzer());
```


注：参考了《自己动手写搜索引擎》和网络上很多资料，涉及Lucene知识部分不是原创，只是自己整合了方便使用。


**四、一个示例程序**
1.**准备条件**
在F盘建立两个文件夹：article和index，其中article用来存放待索引的文件，index用来存放索引文件。
article中建立三个文件：
1.txt，内容为：“中国在亚运会上获得了最多的金牌。”
2.txt，内容为：“中国经济世界第三。”
3.txt，内容为：“刘翔是雅典奥运会冠军。”


2.**示例代码**

```java

/**
 * @author mayl
 * @since 1.6.0_10-rc2
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MultiSearcher;
import org.apache.lucene.search.Query;

public class LuceneTest {
	public static void main(String[] args) {
		try {
			LuceneTest luceneTest = new LuceneTest();
			luceneTest.createIndex();
			
			/**
			 * 改造成界面，然后读取数据传递过来
			 */
			String searchWord = "中国 金牌";
			luceneTest.search(searchWord);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void createIndex() throws Exception {
		String articleStr = "f:\\article\\";	// 待索引文件夹
		String indexStr = "f:\\index\\";		// 建立的索引文件夹
		
		File articleDir = new File(articleStr);
		File indexDir = new File(indexStr);
		
		File[] textFiles = articleDir.listFiles();
		
		IndexWriter indexWriter = new IndexWriter(indexDir,
				new StandardAnalyzer(), true);
		
		/**
		 * IndexWriter(String path, Analyzer a, boolean create)
		 * 第三个参数为true表示重建索引
		 */
		
		String suffix = ".txt";		// 后缀
		// 增加document到索引去
		for(int i = 0; i < textFiles.length; i++){
			if(textFiles[i].isFile() && textFiles[i].getName().endsWith(suffix)){
				String strName = FileReader(textFiles[i].getCanonicalPath(), "GBK");
				Document document = new Document();
				String name = "body";
				Field field = new Field(name, strName, Field.Store.YES,  
		                Field.Index.TOKENIZED);
				document.add(field);
				indexWriter.addDocument(document);
			}
		}
		indexWriter.close();	// 一定要注意close
	}
	
	public static String FileReader(String FileName, String charset) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader
				(new FileInputStream(FileName), charset));
		String line = "";
		String fileStr = "";
		while((line = reader.readLine()) != null){
			fileStr += line;
		}
		reader.close();
		return fileStr;
	} 

	public void search(String serchString) throws Exception {
		String path = "f:\\index\\";	// 从构建的索引中搜索
		String[] field = {"body"}; 		// 要搜索的域，正文本身

		IndexSearcher indexSearcher = new IndexSearcher(path);
		IndexSearcher indexSearchers[] = { indexSearcher };
		
		// 多域搜索以后用到，这里只简单尝试一个域，但是可以解析空格。 
		MultiFieldQueryParser qp = new MultiFieldQueryParser(field, 
                                                   new StandardAnalyzer());
		Query query = qp.parse(serchString);
		MultiSearcher searcher = new MultiSearcher(indexSearchers);
		
		if(searcher != null){
			Hits h = searcher.search(query);
			for (int i = 0; i < h.length(); i++) {
				System.out.println(h.doc(i).get(field[0]));
			}
			System.out.println("共找到" + h.length() + "个结果。\n");
		}
		searcher.close();
	}
}

```


运行结果为：

![](http://dl.iteye.com/upload/attachment/364573/af778ec8-a22d-3929-ae89-8d99cd909343.jpg)