首先,先看下目录结构。
第一步,在eclipse中建立jave项目。需要引入jar包,只有3个,分别是lucene的分词器和核心包,还有高亮显示器。做法是建立一个lib文件夹,将jar包拷过来,然后右击,选择Build Path(构建路径),Addto Build Path(添加到项目的构建路径)。
然后建立datasource文件夹,添几个txt的文件进去,内容爱写啥写啥。(但是建议是一个是中文,一个是英文,可以测两种语言的分词)。还有luceneIndex文件夹,用来存放创建的索引.
其中,IndexWriteraddDocument's a javadoc.txt的内容是
Adds room adocument to this room index. If the room document contains room more than setMaxFieldLength(int) terms for agiven field, the remainder are discarded.
小笑话_总统的房间 Room .txt 的内容是
总统的房间
一位绅士到旅游胜地的一家饭店要开个房间,
侍者因为他没有预定而拒绝说:“房间全满,无法安排。”
“听着!”绅士说,“假如我告诉你总统要到这里来,你一定会马上向他提供一套客房吧?”
“当然啦,他是总……”
“好了,我荣幸地通知你:总统今晚不来了。你把他的房间给我吧!”
然后建立包,com.lucene.helloworld,新建一个HelloWorld的类。里面主要的两个方法就是建立索引,以及查询关键字。
package com.lucene.helloworld;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Filter;
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.junit.Test;
import com.lucene.units.File2DocumentUtils;
public class HelloWorld {
//需要查询的文件所在的路径
String filePath = "F:\\Users\\liuyanling\\workspace\\LuceneDemo\\datasource\\peoplewhocannot.txt";
//设置索引存放的路径
String indexPath = "F:\\Users\\liuyanling\\workspace\\LuceneDemo\\luceneIndex";
//设置分词器为标准分词器
Analyzer analyzer = new StandardAnalyzer();
/**
* 创建索引,先将文件File转化为Document类型,然后用IndexWriter,将Document按照设定的分词器和其他规则,创建索引,存到相应路径中
*/
@Test
public void createIndex() throws Exception {
Document doc = File2DocumentUtils.file2Document(filePath);
IndexWriter indexWriter = new IndexWriter(indexPath,analyzer,true,MaxFieldLength.LIMITED);
indexWriter.addDocument(doc);
indexWriter.close();
}
/**
* 搜索,查询关键字queryString,先设置查询的范围,在"名称"和"内容"中查询。然后用IndexSearcher来查询,
* 通过查询索引来将结果返回。返回的结果是TopDocs类型,还需要进行处理才能拿到结果。
*/
@Test
public void search() throws Exception {
String queryString = "Internet";
String[] fields = {"name","content"};
QueryParser queryParser = new MultiFieldQueryParser(fields,analyzer);
Query query = queryParser.parse(queryString);
IndexSearcher indexSearcher = new IndexSearcher(indexPath);
Filter filter = null;
//查询前10000条记录
TopDocs topDocs = indexSearcher.search(query,filter,10000);
System.out.println("总共有["+topDocs.totalHits+"]条匹配结果");
//将查询出的结果的scoreDocs进行遍历
for (ScoreDoc scoreDoc : topDocs.scoreDocs ) {
//取出文件的doc编号
int docSn = scoreDoc.doc;
//根据编号,用indexSearcher查找到document文件
Document doc = indexSearcher.doc(docSn);
//将Document文件内容打印出来
File2DocumentUtils.printDocumentInfo(doc);
};
}
}
接着,由于里面用了File2DocumentUtils类的printDocumentInfo()和file2Document(),打印Document内容和File转换为Document两个方法。看看File2DocummentUtils文件内容.
package com.lucene.units;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumberTools;
import org.apache.lucene.document.Field.Index;
import org.apache.lucene.document.Field.Store;
/**
* File转化为Document的工具类
* @author liuyanling
*
*/
public class File2DocumentUtils {
/**
* 文件File转为Document.先根据路径,读取出File文件.然后根据文件的Name,content,size,path来建立索引,确认是否存储.
* @param path
* @return Document,被转换好的结果
*/
public static Document file2Document(String path) {
File file = new File(path);
Document doc = new Document();
//将文件名和内容分词,建立索引,存储;而内容通过readFileContent方法读取出来。
doc.add(new Field("name",file.getName(),Store.YES,Index.ANALYZED));
doc.add(new Field("content",readFileContent(file),Store.YES,Index.ANALYZED));
//将文件大小存储,但建立索引,但不分词;路径则不需要建立索引
doc.add(new Field("size",String.valueOf(file.length()),Store.YES,Index.NOT_ANALYZED));
doc.add(new Field("path",file.getPath(),Store.YES,Index.NO));
return doc;
}
/**
* 读取文件内容。通过FileInputStream文件输入流,InputStreamReader读取输入流,再用BufferedReader包装,可以readLine
* 一行一行将数据取出。
* @param file 文件对象
* @return String,文件中的内容
*/
public static String readFileContent(File file) {
try {
BufferedReader reader = new BufferedReader (new InputStreamReader(new FileInputStream(file)));
//存储File的内容
StringBuffer content = new StringBuffer();
for(String line = null;(line = reader.readLine()) != null;) {
content.append(line).append("\n");
}
return content.toString();
} catch (Exception e) {
throw new RuntimeException();
}
}
/**
* 将Document文件的内容打印出来,直接根据之前建立索引的使用的字段名,get出字段内容,打印
* @param doc
*/
public static void printDocumentInfo(Document doc) {
// //第一种读取方式,先getfiled,然后stringValue
// Field r = doc.getField("name");
// r.stringValue();
//第二种读取方式,直接get
System.out.println("name ="+doc.get("name"));
System.out.println("content =" +doc.get("content"));
System.out.println("size =" +doc.get("size"));
System.out.println("path =" +doc.get("path"));
}
}
代码写完了,先创建索引,在createIndex方法上右击Run As选择Junit Test,进行单元测试。
测试成功之后,就可以看到index增加了,说明索引添加了。
然后测试测试,查询的结果如下。只查询到一个结果,将name,context,size和路径都打印出来了。