Lucene的配置及创建索引全文检索
Lucene
是一个开放源代码的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎(英文与德文两种西方语言)。Lucene的目的是为软件开发人员提供一个简单易用的工具包,以方便的在目标系统中实现全文检索的功能,或者是以此为基础建立起完整的全文检索引擎。
优点
概念

Lucene配置

public static void createindex() throws Exception {
//创建文件目录 创建在项目目录下的index中
Directory dir=FSDirectory.open(FileSystems.getDefault().getPath(System.getProperty("user.dir")+"/index"));
//分词处理 是一个抽象类 一种单字分词,标准的
Analyzer analyzer=new IKAnalyzer();
//创建IndexWriterConfig对象
IndexWriterConfig config=new IndexWriterConfig(analyzer);
//创建IndexWriter对象
IndexWriter iWriter=new IndexWriter(dir, config);
//清除之前的索引
iWriter.deleteAll();
//创建文档对象
Document doc=new Document();
//向文档中添加文本内容字段,及字段类型
doc.add(new Field("fieldname","坚持到底gl博主的博文,转载请注释出处", TextField.TYPE_STORED));
//将文档添加到indexWriter中,写入索引文件中
iWriter.addDocument(doc);
//关闭写入
iWriter.close();
}这样运行可以看到你的索引index中的内容文件已经创建出来了
索引已经创建,接下来查询一下试试索引 ,传入需要查询的词
public static void search(String string) throws Exception {
Directory dir=FSDirectory.open(FileSystems.getDefault().getPath(System.getProperty("user.dir")+"/search"));
//打开索引目录的
DirectoryReader dReader=DirectoryReader.open(dir);
IndexSearcher searcher=new IndexSearcher(dReader);
//第一个参数 field值 ,第二个参数用户需要检索的字符串
Term t=new Term("fieldname",string);
//将用户需要索引的字符串封装成lucene能识别的内容
Query query=new TermQuery(t);
//查询,最大的返回值10
TopDocs top=searcher.search(query, 10);
//命中数,那个字段命中,命中的字段有几个
System.out.println("命中数:"+top.totalHits);
//查询返回的doc数组
ScoreDoc[] sDocs= top.scoreDocs;
for (ScoreDoc scoreDoc : sDocs) {
//输出命中字段内容
System.out.println(searcher.doc(scoreDoc.doc).get(field));
}
}就这样一个全文检索的测试就出来了,多去思考总结,扩展出去
再给添加一个代码有益于理解
public static void main(String[] args) throws Exception {
String chString="坚持到底的文章,转载请注释出处";
Analyzer analyzer=new IKAnalyzer();
TokenStream stream=analyzer.tokenStream("word", chString);
stream.reset();
CharTermAttribute cta=stream.addAttribute(CharTermAttribute.class);
while (stream.incrementToken()) {
System.out.println(cta.toString());
}
stream.close();
}显示如下:

还可以添加这几个文件,有一点需要注意的是,注意你的编码格式
第一个:ext.dic 扩展词典,分词中那个需要组在一起的,如:分词处理可能将“坚持到底”四个字分为“坚持”和“到底”,可以在这个文件中直接添加坚持到底,就可以显示出坚持到底的这个索引
第三个:stopword.dic 扩展停止词典,分词中不想出现的,不希望他被分开出现或单独的,可以往里面写,检索的时候就不会有
第二个:是指定上面两个扩展词典的

这些就是最基本掌握的内容,还有很多分词算法等类型,需要去扩展
--------------------------------------分割线 --------------------------------------
--------------------------------------分割线 --------------------------------------
Lucene 的详细介绍:请点这里
Lucene 的下载地址:请点这里