lucene2.9.3简单代码入门demo

今天刚刚看了一点lucene的知识,简单写了一个小例子,使用的是lucene2.9.3,有些内容参考了网友[++yong],以备后用。

 

一、去http://apache.freelamp.com//lucene/java/ 下载windows下2.9.3jar包。

 

二、eclipse,创建工程,导包。

 

三、创建要被检索的几个测试文档,随便写几个就行了。

      我:创建文件夹D:\tests\lucene2.9.3\s

            创建文件D:\tests\lucene2.9.3\s\1.txt

            文件内容:任务管理器区域语言设置

    创建文件D:\tests\lucene2.9.3\s\2.txt

            文件内容:我的电脑

            创建文件D:\tests\lucene2.9.3\s\3.txt

            文件内容:我的任务

 

四、目标:在文档中检索关键字“任务”。开始写代码了。
      1、要使用lucene检索,那就要先为文档创建索引。

 

 

package com.juying.pop.test;
/**
 * 使用lucene2.9.3为文本文件创建索引
 */
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
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.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

public class FirstLuceneDemo {
	/**
	 * 主方法
	 */
	public static void main(String[] args) {
		File filedir = new File("D:\\tests\\lucene2.9.3\\s");
		// 为创建的索引指定路径,索引文件将来放在这个目录下面
		File fileIndex = new File("D:\\tests\\lucene2.9.3\\s\\index");
		File[] files = filedir.listFiles();
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29);
		try {
			IndexWriter indexWriter = new IndexWriter(new SimpleFSDirectory(
					fileIndex), analyzer, true,
					IndexWriter.MaxFieldLength.UNLIMITED);
			long startTime = new Date().getTime();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile()
						&& files[i].getName().toLowerCase().endsWith(".txt")) {
					System.out.println("File " + files[i].getCanonicalPath()
							+ "正在被索引...");
					String filecontent = getFileContent(files[i]
							.getAbsoluteFile(), "gbk");
					System.out.println(filecontent);
					// document对象可以当做数据库的一条记录
					Document doc = new Document();
					// filed对象可以当做数据库的一个字段
					Field fieldPath = new Field("path", files[i].getName(),
							Field.Store.YES, Field.Index.NO);
					Field fieldBody = new Field("body", filecontent,
							Field.Store.YES, Field.Index.ANALYZED,
							Field.TermVector.WITH_POSITIONS_OFFSETS);
					doc.add(fieldPath);
					doc.add(fieldBody);
					indexWriter.addDocument(doc);
				}
			}
			indexWriter.optimize();
			indexWriter.close();
			long endTime = new Date().getTime();
			System.out.println("花费了" + (endTime - startTime) + "毫秒创建索引"
					+ fileIndex.getPath());

		} catch (CorruptIndexException e) {
			e.printStackTrace();
		} catch (LockObtainFailedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 将文件中的所有内容读取出来
	 * @param absoluteFile 要读取的文件路径
	 * @param string 编码格式
	 * @return string 文件里面的内容
	 */
	private static String getFileContent(File absoluteFile, String string) {
		StringBuffer sb = new StringBuffer();
		BufferedReader r = null;
		String lineContent = "";
		try {
			r = new BufferedReader(new InputStreamReader(new FileInputStream(
					absoluteFile), string));
			while ((lineContent = r.readLine()) != null) {
				sb.append(lineContent);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				r.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}

 

 

    运行结果:

 

File D:\tests\lucene2.9.3\s\1.txt正在被索引...
任务管理器区域语言设置
File D:\tests\lucene2.9.3\s\2.txt正在被索引...
我的电脑
File D:\tests\lucene2.9.3\s\3.txt正在被索引...
我的任务
花费了1031毫秒创建索引D:\tests\lucene2.9.3\s\index

 

    2、文档索引创建完成后,就该到查询了。

 

package com.juying.pop.test;
/**
 * 使用lucene2.9.3创建的索引
 * 并且根据关键字查询
 */
import java.io.File;
import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
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.SimpleFSDirectory;
import org.apache.lucene.util.Version;

public class FirstQueryDemo {
	/**
	 * 主方法
	 * @param args
	 * @throws IOException 
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException, IOException {
		TopDocs topDocs = null ;
		// 检索关键字
		String inputQueryWords = "任务";
		Query query = null;
		IndexSearcher searcher = new IndexSearcher(new SimpleFSDirectory(new File("D:\\tests\\lucene2.9.3\\s\\index")), true);
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_29) ;
		
		QueryParser queryParser =  new QueryParser(Version.LUCENE_29,"body",analyzer) ;
		try {
			query = queryParser.parse(inputQueryWords) ;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if(searcher != null)
		{
			topDocs = searcher.search(query,null, 4) ;
			if(topDocs.totalHits!=0)
			{
				System.out.println("查找关键字为:"+inputQueryWords);
				System.out.println("找到了"+topDocs.totalHits+"个结果:");
			}
			ScoreDoc[] sd = topDocs.scoreDocs ;
			for (int i = 0; i < sd.length; i++) {
				Document doc = searcher.doc(sd[i].doc) ;
				System.out.println(doc.getField("body").stringValue());
			}
		}
	}
}

 

   运行结果:

 

查找关键字为:任务
找到了2个结果:
我的任务
任务管理器区域语言设置

 

最后 :

        我的代码里面基本上没有什么注释,所以各种类,方法的使用可以参考从上面链接地址下载下来的帮助文档。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值