Lucene入门一(转)

说明一下,这一篇文章的用到的lucene,是用2.0版本的,主要在查询的时候2.0版本的lucene与以前的版本有了一些区别.
其实这一些代码都是早几个月写的,自己很懒,所以到今天才写到自己的博客上,高深的文章自己写不了,只能记录下一些简单的记录与点滴,其中的代码算是自娱自乐的,希望高手不要把重构之类的砸下来...

1、在windows系统下的的C盘,建一个名叫s的文件夹,在该文件夹里面随便建三个txt文件,随便起名啦,就叫"1.txt","2.txt"和"3.txt"啦
其中1.txt的内容如下:
Java代码 复制代码
  1. 中华人民共和国   
  2. 全国人民   
  3. 2006年  
中华人民共和国
全国人民
2006年

而"2.txt"和"3.txt"的内容也可以随便写几写,这里懒写,就复制一个和1.txt文件的内容一样吧

2、下载lucene包,放在classpath路径中
建立索引:
Java代码 复制代码
  1. package lighter.javaeye.com;   
  2.   
  3. import java.io.BufferedReader;   
  4. import java.io.File;   
  5. import java.io.FileInputStream;   
  6. import java.io.IOException;   
  7. import java.io.InputStreamReader;   
  8. import java.util.Date;   
  9.   
  10. import org.apache.lucene.analysis.Analyzer;   
  11. import org.apache.lucene.analysis.standard.StandardAnalyzer;   
  12. import org.apache.lucene.document.Document;   
  13. import org.apache.lucene.document.Field;   
  14. import org.apache.lucene.index.IndexWriter;   
  15.   
  16. /**  
  17.  * author lighter date 2006-8-7  
  18.  */  
  19. public class TextFileIndexer {   
  20.     public static void main(String[] args) throws Exception {   
  21.         /* 指明要索引文件夹的位置,这里是C盘的S文件夹下 */  
  22.         File fileDir = new File("c://s");   
  23.   
  24.         /* 这里放索引文件的位置 */  
  25.         File indexDir = new File("c://index");   
  26.         Analyzer luceneAnalyzer = new StandardAnalyzer();   
  27.         IndexWriter indexWriter = new IndexWriter(indexDir, luceneAnalyzer,   
  28.                 true);   
  29.         File[] textFiles = fileDir.listFiles();   
  30.         long startTime = new Date().getTime();   
  31.            
  32.         //增加document到索引去   
  33.         for (int i = 0; i < textFiles.length; i++) {   
  34.             if (textFiles[i].isFile()   
  35.                     && textFiles[i].getName().endsWith(".txt")) {   
  36.                 System.out.println("File " + textFiles[i].getCanonicalPath()   
  37.                         + "正在被索引....");   
  38.                 String temp = FileReaderAll(textFiles[i].getCanonicalPath(),   
  39.                         "GBK");   
  40.                 System.out.println(temp);   
  41.                 Document document = new Document();   
  42.                 Field FieldPath = new Field("path", textFiles[i].getPath(),   
  43.                         Field.Store.YES, Field.Index.NO);   
  44.                 Field FieldBody = new Field("body", temp, Field.Store.YES,   
  45.                         Field.Index.TOKENIZED,   
  46.                         Field.TermVector.WITH_POSITIONS_OFFSETS);   
  47.                 document.add(FieldPath);   
  48.                 document.add(FieldBody);   
  49.                 indexWriter.addDocument(document);   
  50.             }   
  51.         }   
  52.         //optimize()方法是对索引进行优化   
  53.         indexWriter.optimize();   
  54.         indexWriter.close();   
  55.            
  56.         //测试一下索引的时间   
  57.         long endTime = new Date().getTime();   
  58.         System.out   
  59.                 .println("这花费了"  
  60.                         + (endTime - startTime)   
  61.                         + " 毫秒来把文档增加到索引里面去!"  
  62.                         + fileDir.getPath());   
  63.     }   
  64.   
  65.     public static String FileReaderAll(String FileName, String charset)   
  66.             throws IOException {   
  67.         BufferedReader reader = new BufferedReader(new InputStreamReader(   
  68.                 new FileInputStream(FileName), charset));   
  69.         String line = new String();   
  70.         String temp = new String();   
  71.            
  72.         while ((line = reader.readLine()) != null) {   
  73.             temp += line;   
  74.         }   
  75.         reader.close();   
  76.         return temp;   
  77.     }   
  78. }  
package lighter.javaeye.com;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

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.index.IndexWriter;

/**
 * author lighter date 2006-8-7
 */
public class TextFileIndexer {
	public static void main(String[] args) throws Exception {
		/* 指明要索引文件夹的位置,这里是C盘的S文件夹下 */
		File fileDir = new File("c://s");

		/* 这里放索引文件的位置 */
		File indexDir = new File("c://index");
		Analyzer luceneAnalyzer = new StandardAnalyzer();
		IndexWriter indexWriter = new IndexWriter(indexDir, luceneAnalyzer,
				true);
		File[] textFiles = fileDir.listFiles();
		long startTime = new Date().getTime();
		
		//增加document到索引去
		for (int i = 0; i < textFiles.length; i++) {
			if (textFiles[i].isFile()
					&& textFiles[i].getName().endsWith(".txt")) {
				System.out.println("File " + textFiles[i].getCanonicalPath()
						+ "正在被索引....");
				String temp = FileReaderAll(textFiles[i].getCanonicalPath(),
						"GBK");
				System.out.println(temp);
				Document document = new Document();
				Field FieldPath = new Field("path", textFiles[i].getPath(),
						Field.Store.YES, Field.Index.NO);
				Field FieldBody = new Field("body", temp, Field.Store.YES,
						Field.Index.TOKENIZED,
						Field.TermVector.WITH_POSITIONS_OFFSETS);
				document.add(FieldPath);
				document.add(FieldBody);
				indexWriter.addDocument(document);
			}
		}
		//optimize()方法是对索引进行优化
		indexWriter.optimize();
		indexWriter.close();
		
		//测试一下索引的时间
		long endTime = new Date().getTime();
		System.out
				.println("这花费了"
						+ (endTime - startTime)
						+ " 毫秒来把文档增加到索引里面去!"
						+ fileDir.getPath());
	}

	public static String FileReaderAll(String FileName, String charset)
			throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(FileName), charset));
		String line = new String();
		String temp = new String();
		
		while ((line = reader.readLine()) != null) {
			temp += line;
		}
		reader.close();
		return temp;
	}
}


索引的结果:
Java代码 复制代码
  1. File C:/s/1.txt正在被索引....   
  2. 中华人民共和国全国人民2006年   
  3. File C:/s/2.txt正在被索引....   
  4. 中华人民共和国全国人民2006年   
  5. File C:/s/3.txt正在被索引....   
  6. 中华人民共和国全国人民2006年   
  7. 这花费了297 毫秒来把文档增加到索引里面去!c:/s  
File C:/s/1.txt正在被索引....
中华人民共和国全国人民2006年
File C:/s/2.txt正在被索引....
中华人民共和国全国人民2006年
File C:/s/3.txt正在被索引....
中华人民共和国全国人民2006年
这花费了297 毫秒来把文档增加到索引里面去!c:/s


3、建立了索引之后,查询啦....
Java代码 复制代码
  1. package lighter.javaeye.com;   
  2.   
  3. import java.io.IOException;   
  4.   
  5. import org.apache.lucene.analysis.Analyzer;   
  6. import org.apache.lucene.analysis.standard.StandardAnalyzer;   
  7. import org.apache.lucene.queryParser.ParseException;   
  8. import org.apache.lucene.queryParser.QueryParser;   
  9. import org.apache.lucene.search.Hits;   
  10. import org.apache.lucene.search.IndexSearcher;   
  11. import org.apache.lucene.search.Query;   
  12.   
  13. public class TestQuery {   
  14.     public static void main(String[] args) throws IOException, ParseException {   
  15.         Hits hits = null;   
  16.         String queryString = "中华";   
  17.         Query query = null;   
  18.         IndexSearcher searcher = new IndexSearcher("c://index");   
  19.   
  20.         Analyzer analyzer = new StandardAnalyzer();   
  21.         try {   
  22.             QueryParser qp = new QueryParser("body", analyzer);   
  23.             query = qp.parse(queryString);   
  24.         } catch (ParseException e) {   
  25.         }   
  26.         if (searcher != null) {   
  27.             hits = searcher.search(query);   
  28.             if (hits.length() > 0) {   
  29.                 System.out.println("找到:" + hits.length() + " 个结果!");   
  30.             }   
  31.         }   
  32.     }   
  33.   
  34. }  
package lighter.javaeye.com;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;

public class TestQuery {
	public static void main(String[] args) throws IOException, ParseException {
		Hits hits = null;
		String queryString = "中华";
		Query query = null;
		IndexSearcher searcher = new IndexSearcher("c://index");

		Analyzer analyzer = new StandardAnalyzer();
		try {
			QueryParser qp = new QueryParser("body", analyzer);
			query = qp.parse(queryString);
		} catch (ParseException e) {
		}
		if (searcher != null) {
			hits = searcher.search(query);
			if (hits.length() > 0) {
				System.out.println("找到:" + hits.length() + " 个结果!");
			}
		}
	}

}


其运行结果:
引用
找到:3 个结果!

建立索引

为了对文档进行索引,Lucene 提供了五个基础的类,他们分别是 Document, Field, IndexWriter, Analyzer, Directory。下面我们分别介绍一下这五个类的用途:

Document

Document 是用来描述文档的,这里的文档可以指一个 HTML 页面,一封电子邮件,或者是一个文本文件。一个 Document 对象由多个 Field 对象组成的。可以把一个 Document 对象想象成数据库中的一个记录,而每个 Field 对象就是记录的一个字段。

Field

Field 对象是用来描述一个文档的某个属性的,比如一封电子邮件的标题和内容可以用两个 Field 对象分别描述。

Analyzer

在一个文档被索引之前,首先需要对文档内容进行分词处理,这部分工作就是由 Analyzer 来做的。Analyzer 类是一个抽象类,它有多个实现。针对不同的语言和应用需要选择适合的 Analyzer。Analyzer 把分词后的内容交给 IndexWriter 来建立索引。

IndexWriter

IndexWriter 是 Lucene 用来创建索引的一个核心的类,他的作用是把一个个的 Document 对象加到索引中来。

Directory

这个类代表了 Lucene 的索引的存储的位置,这是一个抽象类,它目前有两个实现,第一个是 FSDirectory,它表示一个存储在文件系统中的索引的位置。第二个是 RAMDirectory,它表示一个存储在内存当中的索引的位置。

 

我们注意到类 IndexWriter 的构造函数需要三个参数,第一个参数指定了所创建的索引要存放的位置,他可以是一个 File 对象,也可以是一个 FSDirectory 对象或者 RAMDirectory 对象。第二个参数指定了 Analyzer 类的一个实现,也就是指定这个索引是用哪个分词器对文挡内容进行分词。第三个参数是一个布尔型的变量,如果为 true 的话就代表创建一个新的索引,为 false 的话就代表在原来索引的基础上进行操作。接着程序遍历了目录下面的所有文本文档,并为每一个文本文档创建了一个 Document 对象。然后把文本文档的两个属性:路径和内容加入到了两个 Field 对象中,接着在把这两个 Field 对象加入到 Document 对象中,最后把这个文档用 IndexWriter 类的 add 方法加入到索引中去。这样我们便完成了索引的创建。

 

利用Lucene进行搜索就像建立索引一样也是非常方便的。在上面一部分中,我们已经为一个目录下的文本文档建立好了索引,现在我们就要在这个索引上进行搜索以找到包含某个关键词或短语的文档。Lucene提供了几个基础的类来完成这个过程,它们分别是呢IndexSearcher, Term, Query, TermQuery, Hits. 下面我们分别介绍这几个类的功能。

Query

这是一个抽象类,他有多个实现,比如TermQuery, BooleanQuery, PrefixQuery. 这个类的目的是把用户输入的查询字符串封装成Lucene能够识别的Query。

Term

Term 是搜索的基本单位,一个Term对象有两个String类型的域组成。生成一个Term对象可以有如下一条语句来完成:Term term = new Term(“fieldName”,”queryWord”); 其中第一个参数代表了要在文档的哪一个Field上进行查找,第二个参数代表了要查询的关键词。

TermQuery

TermQuery是抽象类Query的一个子类,它同时也是Lucene支持的最为基本的一个查询类。生成一个TermQuery对象由如下语句完成: TermQuery termQuery = new TermQuery(new Term(“fieldName”,”queryWord”)); 它的构造函数只接受一个参数,那就是一个Term对象。

IndexSearcher

IndexSearcher是用来在建立好的索引上进行搜索的。它只能以只读的方式打开一个索引,所以可以有多个IndexSearcher的实例在一个索引上进行操作。

Hits

Hits是用来保存搜索的结果的。

介绍完这些搜索所必须的类之后,我们就开始在之前所建立的索引上进行搜索了,清单2给出了完成搜索功能所需要的代码。

 

类IndexSearcher的构造函数接受一个类型为Directory的对象,Directory是一个抽象类,它目前有两个子类:FSDirctory和RAMDirectory. 我们的程序中传入了一个FSDirctory对象作为其参数,代表了一个存储在磁盘上的索引的位置。构造函数执行完成后,代表了这个 IndexSearcher以只读的方式打开了一个索引。然后我们程序构造了一个Term对象,通过这个Term对象,我们指定了要在文档的内容中搜索包含关键词”lucene”的文档。接着利用这个Term对象构造出TermQuery对象并把这个TermQuery对象传入到 IndexSearcher的search方法中进行查询,返回的结果保存在Hits对象中。最后我们用了一个循环语句把搜索到的文档的路径都打印了出来。好了,我们的搜索应用程序已经开发完毕,怎么样,利用Lucene开发搜索应用程序是不是很简单。

 

http://www.ibm.com/developerworks/cn/java/j-lo-lucene1/#N1004B

开源全文搜索工具包Lucene2.9.1的使用。 1. 搭建Lucene的开发环境:在classpath中添加lucene-core-2.9.1.jar包 2. 全文搜索的两个工作: 建立索引文件,搜索索引. 3. Lucene的索引文件逻辑结构 1) 索引(Index)由若干块(片段)(Segment)组成 ★2) 块由若干文档(Document)组成: 个文件映射成文档。数据库表中的条记录映射成文档。 ★3) 文档由若干域(Field)组成:文件的属性(文件路径,文件的内容)映射成个域。记录的某个字段映射成个域。 ☆4) 域由若干词(关键字)(Term)组成:文件的属性的内容中某个字符串映射成个词。 4. Lucene包结构 1) analysis模块:负责词法分析及语言处理而形成Term()。提供了些内置的分析器:最常用的是StandardAnalyzer 2) index模块:负责索引的读写。 对索引文件的segment进行写、合并、优化的IndexWriter类。对索引进行读取和删除操作的IndexReader类。 3) store模块:负责索引的存储。提供索引的各种存储类:FSDirectory,RAMDirectory等。 4) document模块:索引文件内部的基础存储结构封装。如:Document类和Field类等。 5) search模块:负责对索引的搜索。提供了索引搜索器IndexSearcher类和各种Query类,如TermQuery、BooleanQuery等。 6) queryParser模块:负责查询语句的语法分析。提供了解析查询语句的QueryParser类 7) util模块:包含些公共工具类。 5. 创建索引 1) IndexWriter:索引写出器 a) 构造方法: IndexWriter(Directory d, Analyzer a, IndexWriter.MaxFieldLength mfl) 如果索引不存在,就会被创建。如果索引存在,就追加. IndexWriter(Directory d, Analyzer a, boolean create, IndexWriter.MaxFieldLength mfl) create为true时,原索引文件不存在就创建,存在就覆盖。 create为false时,原索引文件不存在就报错,存在就追加。 b) 常用方法: void addDocument(Document doc); //把指定文档添加到索引写出器中 void iw.close(); //关闭索引写出器,此时才把索引写到目标存储地 2) Directory: 索引存放地。 a) 文件系统:FSDirectory: FSDirectory.open(File file); b) 内存RAMDirectory: new RAMDirectory(); 3) Analyzer: 分词器。 a) StandardAnalyzer: 标准分词器。对英文采用空白, 标点符号进行分词。对中文采用单字分词。 b) SmartChineseAnalyzer: 智能中文分词器。(LUCENE_HOME/contrib/analyzers/smartcn/lucene-smartcn-2.9.1.jar) C) 第三方的中文分词器:如PaodingAnalyzer、IKAnalyzer 4) IndexWriter.MaxFieldLength: 指定域值的最大长度。 a) UNLIMITED 无限制的。 b) LIMITED 有限制的。值为10000 5) Document: 索引的组成单元. 组Field的集合. a) 构造方法: Document(); b) 常用方法: void add(Field f); //添加指定域到这个文档中 6) Field: 域,代表文档的某个索引域. a) 构造方法: Field(String name, String value, Field.Store.YES, Field.Index.ANALYZED) name: 域的名称, 只能是字符串. value: 域的值, 只能是字符串. Field.Store: 指定Field的值是否存储或怎样存储. NO(不存储), YES(存储),COMPRESS(压缩后存储) Field.Index: 指定Field是否被索引或怎么被索引. NO(不索引), ANALYZED(分词后索引), NOT_ANALYZED(不分词直接索引)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值