索引库的查询有两类:
1.使用Query的子类
1)TerQuery
根据关键词进行查询.
需要制定要查询的域及要查询的关键词
2) RangeQuery
范围查询
2.使用QueryPaser进行查询
可以对要查询的内容先分词,然后基于分词的结果进行查询。
添加一个jar包
lucene-querypaeser-7.4.0.jar
代码部分如下:
package com.itheima;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.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.FSDirectory;
import org.junit.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;
import java.io.File;
import java.io.IOException;
/**
* @ClassName indexSearch
* @Description TODO
* @Author gkz
* @Date 2019/8/23 18:33
* @Version 1.0
**/
public class indexSearch {
private IndexReader indexReader;
private IndexSearcher indexSearcher;
@Before()
public void initIndexReader() throws IOException {
indexReader = DirectoryReader.open(FSDirectory.open(new File("E:\\Desktop").toPath()));
indexSearcher = new IndexSearcher(indexReader);
}
@Test
public void testRangeQuery() throws IOException {
//创建一个Query对象
Query query = LongPoint.newRangeQuery("size", 1L, 10000L);
printResult(query);
}
@Test
public void printResult(Query query) throws IOException {
//执行查询
TopDocs topDocs = indexSearcher.search(query, 10);
System.out.println("总记录数" + topDocs.totalHits);
ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for (ScoreDoc scoreDoc : scoreDocs) {
//取文档id
int id = scoreDoc.doc;
//根据id取文档对象
Document document = indexSearcher.doc(id);
System.out.println(document.get("name"));
System.out.println(document.get("path"));
System.out.println(document.get("size"));
indexReader.close();
}
}
@Test
public void testQueryParse()throws Exception{
//创建一个QueryParser对象,两个参数
//参数1:默认搜索域,参数2:分析器对象
QueryParser queryParser=new QueryParser("name",new IKAnalyzer());
//使用QueryParse对象来创建一个Query对象
Query query = queryParser.parse("lucene是一个Java开发的全文检索工具包");
//执行查询
printResult(query);
}
}