javaEE Lucene,全文检索,站内搜索,入门程序。索引库的添加,IKAnalyzer(中文分词器)

Lucene的Jar包下载:https://pan.baidu.com/s/1ekc7ZWqukUjkSXxQp09hDA  密码:yvj3

注意:搜索使用的分析器(分词器)要和创建索引时使用的分析器一致。

javaEE Lucene,全文检索,站内搜索,入门程序。索引库的添加,IKAnalyzer(中文分词器)

Field类(域对象):

javaEE Lucene,全文检索,站内搜索,入门程序。索引库的添加,IKAnalyzer(中文分词器)

Test.java(入门程序 测试类):

package com.xxx.lucene;

import static org.junit.Assert.*;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

//Lucene入门案例。 创建索引、查询索引
public class Test {

	// 创建索引
	@Test
	public void testIndex() throws Exception {
		// 第一步:创建一个java工程,并导入jar包。
		// 第二步:创建一个indexwriter对象。
		// 1)指定索引库的存放位置Directory对象
		// 2)指定一个分析器,对文档内容进行分析(分词)。
		Directory directory = FSDirectory.open(new File("D:\\temp\\index"));
		// Directory directory = new RAMDirectory(); //保存索引到内存中 (内存索引库)
		//Analyzer analyzer = new StandardAnalyzer(); // 官方推荐(解析英文)
		Analyzer analyzer = new IKAnalyzer();  // 推荐使用的中文分析器
		IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer); //Version根据导入的Jar包选择,LATEST表示最新的。 
		IndexWriter indexWriter = new IndexWriter(directory, config);
		
		// 第三步:创建field对象和Document对象,将field添加到document对象中。
		File f = new File("D:\\Lucene&solr\\searchsource");
		File[] listFiles = f.listFiles();
		for (File file : listFiles) {
			// 创建document对象。
			Document document = new Document();
			// 文件名称 (Document对象的field对象)
			String file_name = file.getName();
			Field fileNameField = new TextField("fileName", file_name, Store.YES);
			// 文件大小 (field)
			long file_size = FileUtils.sizeOf(file);
			Field fileSizeField = new LongField("fileSize", file_size, Store.YES);
			// 文件路径 (field)
			String file_path = file.getPath();
			Field filePathField = new StoredField("filePath", file_path);
			// 文件内容 (field)
			String file_content = FileUtils.readFileToString(file);
			Field fileContentField = new TextField("fileContent", file_content, Store.YES);

			document.add(fileNameField);
			document.add(fileSizeField);
			document.add(filePathField);
			document.add(fileContentField);
			// 第四步:使用indexwriter对象将document对象写入索引库,此过程进行索引创建。并将索引和document对象写入索引库。
			indexWriter.addDocument(document);

		}
		// 第五步:关闭IndexWriter对象。
		indexWriter.close();
		
	}

	
	// 查询索引
	@Test
	public void testSearch() throws Exception {
		// 第一步:创建一个Directory对象,也就是索引库存放的位置。
		Directory directory = FSDirectory.open(new File("D:\\temp\\index"));// 磁盘
		// 第二步:创建一个indexReader对象,需要指定Directory对象。
		IndexReader indexReader = DirectoryReader.open(directory);
		// 第三步:创建一个indexsearcher对象,需要指定IndexReader对象
		IndexSearcher indexSearcher = new IndexSearcher(indexReader);
		// 第四步:创建一个TermQuery对象,指定查询的域(field)和查询的关键词。TermQuery表示精准查询条件
		Query query = new TermQuery(new Term("fileName", "abc"));  //fileName是(field)域名,abc是(域值)搜索关键字
		// 第五步:执行查询。 (查询索引,根据索引查询文档Document的id)
		TopDocs topDocs = indexSearcher.search(query, 10);  //10表示前10条
		// 第六步:返回查询结果。遍历查询结果并输出。
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			int doc = scoreDoc.doc; //获取文档Document的id。(从0开始,自增的id)
			Document document = indexSearcher.doc(doc); //根据id查询文档。
			// 文件名称
			String fileName = document.get("fileName"); //根据域名获取域值
			System.out.println(fileName);
			// 文件内容
			String fileContent = document.get("fileContent");
			System.out.println(fileContent);
			// 文件大小
			String fileSize = document.get("fileSize");
			System.out.println(fileSize);
			// 文件路径
			String filePath = document.get("filePath");
			System.out.println(filePath);
			System.out.println("------------");
		}
		// 第七步:关闭IndexReader对象(流)
		indexReader.close();

	}

	
	// 查看各种分析器的分词效果(代码了解)
	@Test
	public void testTokenStream() throws Exception {
		// 创建一个标准分析器对象
		//Analyzer analyzer = new StandardAnalyzer();  //标准分词器
		//Analyzer analyzer = new CJKAnalyzer();  //中日韩分词器  (二分法分词)
		//Analyzer analyzer = new SmartChineseAnalyzer();  //需要导入Jar包: lucene-analyzers-smartcn-4.10.3.jar (不能扩展词库,禁用词库同义词库不好处理) 
		Analyzer analyzer = new IKAnalyzer();  //推荐使用的中文分词器。 (需要导入IKAnalyzer2012FF_u1.jar;IKAnalyzer.cfg.xml、src/ext.dic、src/stopword.dic) 
		// 获得tokenStream对象
		// 第一个参数:域名,可以随便给一个
		// 第二个参数:要分析的文本内容
		//TokenStream tokenStream = analyzer.tokenStream("test",
		//		"The Spring Framework provides a comprehensive programming and configuration model.");
		TokenStream tokenStream = analyzer.tokenStream("test",
				"高富帅可以用二维表结构来逻辑表达实现的数据");
		// 添加一个引用,可以获得每个关键词
		CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
		// 添加一个偏移量的引用,记录了关键词的开始位置以及结束位置
		OffsetAttribute offsetAttribute = tokenStream.addAttribute(OffsetAttribute.class);
		// 将指针调整到列表的头部
		tokenStream.reset();
		// 遍历关键词列表,通过incrementToken方法判断列表是否结束
		while (tokenStream.incrementToken()) {
			// 关键词的起始位置
			System.out.println("start->" + offsetAttribute.startOffset());
			// 取关键词
			System.out.println(charTermAttribute);
			// 结束位置
			System.out.println("end->" + offsetAttribute.endOffset());
		}
		tokenStream.close();
	}

}

src/IKAnalyzer.cfg.xml(IK分词器的配置文件):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">  
<properties>  
	<comment>IK Analyzer 扩展配置</comment>
	<!-- 用户可以在这里配置自己的扩展字典 -->
	<entry key="ext_dict">ext.dic;</entry> 
	
	<!-- 用户可以在这里配置自己的扩展停止词字典 -->
	<entry key="ext_stopwords">stopword.dic;</entry> 
	
</properties>

src/ext.dic(扩展字典):

高富帅
流行词汇
新词

src/stopword.dic(停止词字典):

啊
的
吗
a
and
the