创建索引后如何查询?应该从什么方面下手?去获取我们想要的数据通过索引
检索索引思路
用户通过搜索界面——>创建查询——>执行搜索,搜索器从索引库中搜索——>渲染搜索结果
具体实现步骤:
1、 配置依赖jar包(lucene-core-4.10.3.jar、lucene-analyzers-common-4.10.3.jar)
2、 创建IndexSearcher对象
/**
* 从索引库中检索
* @author LEE.SIU.WAH
* @email lixiaohua7@163.com
* @version 1.0
*/
public class IndexSearcherTest {
/** 检索数据 */
@Test
public void test() throws Exception{
/** 创建读索引库对象 */
IndexReader indexReader = DirectoryReader.open(FSDirectory.open(new File("D:\\传智播客\\Lucene4\\lucene_index")));
/** 创建IndexSearcher对象 */
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
3、 调用indexSearcher.search("检索条件", "检索的记录数")进行检索
/** 创建查询对象(检索条件) */
Query query = new TermQuery(new Term("content", "我"));
/** 进行检索,返回最前面的5条记录 */
TopDocs topDocs = indexSearcher.search(query, 5);
4、 TopDocs最前面的文档对象
-- topDocs.getMaxScore()
最好分数
-- topDocs.totalHits
命中的总记录数
-- SocreDoc[] scoreDocs = topDocs.scoreDocs
分数文档数组
System.out.println("最大分数:" + topDocs.getMaxScore());
System.out.println("总命中数:" + topDocs.totalHits);
5、 迭代分数文档数组
-- scoreDoc.doc
文档在索引库的id
-- scoreDoc.score
分数
6、 根据分数文档id获取索引库中的文档
-- Document document = indexSearcher.doc(docId);
-- document.get("
字段名");
获取字段值
// 获取分数文档数组
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs){
System.out.println("分数:" + scoreDoc.score);
System.out.println("文档ID:" + scoreDoc.doc);
// 通过文档id获取文档
Document d = indexSearcher.doc(scoreDoc.doc);
System.out.println(d.get("id") + "\t" + d.get("fileName") + "\t" + d.get("filePath")+ "\t" + d.get("fileContent"));
}
indexReader.close();
分页搜索
/** 分页检索数据 */
@Test
public void test() throws Exception{
/** 创建读索引库对象 */
IndexReader indexReader = DirectoryReader
.open(FSDirectory.open(
new File("D:\\Lucene4\\lucene_index")));
/** 创建IndexSearcher对象 */
IndexSearcher indexSearcher = new IndexSearcher(indexReader);
/** 创建查询对象(检索条件) */
Query query = new TermQuery(new Term("content", "爱"));
/** 当前页码 */
int pageIndex = 1;
/** 每页显示的数量 */
int pageSize = 2;
/** 进行检索,返回最前面的5条记录 */
TopDocs topDocs = indexSearcher.search(query, pageIndex * pageSize);
System.out.println("命中的总记录数:" + topDocs.totalHits);
System.out.println("最大的分数:" + topDocs.getMaxScore());
/** 获取分数文档数组 */
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
/** 迭代检索到得分数文档数组 */
for (int i = (pageIndex - 1) * pageSize; i < scoreDocs.length; i++){
ScoreDoc scoreDoc = scoreDocs[i];
System.out.println("文档分数:" + scoreDoc.score);
System.out.println("文档索引号:" + scoreDoc.doc);
/** 根据索引号docId,获取文档 */
Document doc = indexSearcher.doc(scoreDoc.doc);
System.out.println(doc.get("id") + "\t" + doc.get("name")
+ "\t" + doc.get("filePath")
+ "\t" + doc.get("content"));
}
indexReader.close();
}
这里是延迟加载的,用到才会去加载数组内的内容,并不是一次性加载全部文档,需要用到才回去搜索加载