lucene的索引查询

package com.hope.lucene;

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.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
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;

/**
* @author newcityman
* @date 2020/1/15 - 18:14
*/
public class SearchIndex {
private IndexReader indexReader;
private IndexSearcher indexSearcher;

@Before
public void init() throws Exception{
indexReader = DirectoryReader.open(FSDirectory.open(new File("G:\\workspace_idea3\\lucene\\temp\\index").toPath()));
indexSearcher = new IndexSearcher(indexReader);
}

/**
* 范围查询
* @throws Exception
*/
@Test
public void testRangeQuery() throws Exception{
//创建一个Query对象
Query query = LongPoint.newRangeQuery("size", 0L, 50L);
printResult(query);
}

public void printResult(Query query) throws Exception{

TopDocs topDocs = indexSearcher.search(query, 10);
System.out.println("总记录数:"+topDocs.totalHits);

ScoreDoc[] scoreDocs = topDocs.scoreDocs;
for(ScoreDoc scoreDoc : scoreDocs) {
//取文档id
int docId = scoreDoc.doc;
//根据id取文档对象
Document document = indexSearcher.doc(docId);
System.out.println(document.get("name"));
System.out.println(document.get("path"));
System.out.println(document.get("size"));
// System.out.println(document.get("content"));
System.out.println("++++++++++++++++++++++++++++++");
}
indexReader.close();
}

/**
* 使用QueryParser查询
* @throws Exception
*/

@Test
public void testQueryParser() throws Exception{
//创建一个QueryParser对象,两个参数
//参数一:默认搜索域, 参数2:分析器对象
QueryParser queryParser = new QueryParser("name",new IKAnalyzer());
//使用QueryParser对象创建一个Query对象
Query query = queryParser.parse("全文");
// 执行查询
printResult(query);
}
}
posted on 2020-01-15 19:13  小猪_佩奇  阅读(301)  评论(0编辑  收藏  举报