16、遍历所有关键字的api方式

之前的一些讲述中,我们介绍了查询索引的功能,但一般都是通过域和关键字进行的查询,那如果我们不知道域或想要查询出所有的关键字怎么办呢,下面我就给出两个解决方案,代码很简单

通过指定域方式获取该域中所有的关键字

//遍历指定域中的所有关键字的方式
@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实战陆续发布中………

扫描下方二维码关注公众号 ↓↓↓↓↓↓↓↓↓↓



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值