之前的一些讲述中,我们介绍了查询索引的功能,但一般都是通过域和关键字进行的查询,那如果我们不知道域或想要查询出所有的关键字怎么办呢,下面我就给出两个解决方案,代码很简单
通过指定域方式获取该域中所有的关键字
//遍历指定域中的所有关键字的方式
@Test
public void searchIndex() throws Exception {
//打开索引库
//指定索引库存放的位置
Directory directory = FSDirectory.open(new File("D:\\LucentTest\\luceneIndex2"));
//创建一个IndexReader对象
IndexReader indexReader = DirectoryReader.open(directory);
//创建TermsEnum对象 所有关键字存放的类
TermsEnum enumeration = null;
IndexSearcher searcher = new IndexSearcher(indexReader);
IndexReader reader = searcher.getIndexReader();//得到搜索器的索引阅读器
Fields fields = MultiFields.getFields(reader);
Terms terms = fields.terms("name");
BytesRef byteRef = null;
enumeration = terms.iterator(enumeration);
while((byteRef = enumeration.next()) != null) {
String term = new String(byteRef.bytes, byteRef.offset, byteRef.length);
System.out.println("term is : " + term);
}
}
只有索引目录获取所有域所有关键字的方法
//获取全部关键字的方法
@Test
public void sqlIndex() throws Exception{
//打开索引库
//指定索引库存放的位置
Directory indexDirectory = FSDirectory.open(new File("D:\\LucentTest\\luceneIndex2"));
//创建一个IndexReader对象 用来打开索引
IndexReader indexReader = DirectoryReader.open(indexDirectory);
//取出所有域的信息
Fields fields = MultiFields.getFields(indexReader);
//对索引域进行遍历
Iterator<String> fieldsIterator = fields.iterator();
while(fieldsIterator.hasNext()){
String field = fieldsIterator.next();
Terms terms = fields.terms(field);
TermsEnum termsEnums = terms.iterator(null);
BytesRef byteRef = null;
System.out.println("field : "+ field);
while((byteRef = termsEnums.next()) != null) {
String term = new String(byteRef.bytes, byteRef.offset, byteRef.length);
System.out.println("term is : " + term);
}
}
}
其实在这两个方法中,我们要关心的就是遍历的部分,及 MultiFields.getFields(indexReader);和 TermsEnum这个类的用法, TermsEnum 是存放所有索引关键字抽象类,看代码我们就能看的出来
下面是小编的微信转帐二维码,小编再次谢谢读者的支持,小编会更努力的
----请看下方↓↓↓↓↓↓↓
百度搜索 Drools从入门到精通:可下载开源全套Drools教程
深度Drools教程不段更新中:
更多Drools实战陆续发布中………
扫描下方二维码关注公众号 ↓↓↓↓↓↓↓↓↓↓