Lucene开发,垂直搜索(比如淘宝,京东类似搜索功能)——第五节 lucene搜索索引。

以下是通过刚刚建立的索引进行索引查询。

       以下是通过lucene自带的  TermQuery来查询,即使用lucene自带的默认分词器,英文分词器进行分词。

       在以后的文章中会将到中文分词等相关内容。

(以下代码用在项目中会由io问题,最好再改进一下,这里只用了测试。考虑到公司代码安全问题,这里只给出开发中的部分测试代码。)


public ArrayList<String> queryByString(String queryStr){

        //上面文章中建立索引的文件目录
        File indexDir = new File("D:\\luceneIndex");
        FSDirectory directory;
        ArrayList<String> resultList=new ArrayList<String>(10);
        try {
            directory=FSDirectory.open(indexDir);
            
            IndexSearcher searcher=new IndexSearcher(directory);
             if(!indexDir.exists()){
                 System.out.println("The Lucene index is not exist");
                 return null;
            }
            //定义搜索的基本单位。第一个参数代表了要在文档的哪一个 Field 上进行查找,第二个参数代表了要查询的关键词。
            Term term = new Term("GoodsName",queryStr);
            //构造查询对象。构造函数只接受一个 Term 对象
            TermQuery luceneQuery = new TermQuery(term);
            //搜索需要查询对象,并返回结果
            TopDocs hit=searcher.search(luceneQuery, 10);
            
            for(int i=0;i<hit.totalHits;i++){
                ScoreDoc scoreDoc=hit.scoreDocs[i];
                Document hitDoc=searcher.doc(scoreDoc.doc);
                System.out.println("GoodsName: " + hitDoc.get("GoodsName"));
                String tempStr=hitDoc.get("GoodsName");
                resultList.add(tempStr);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return resultList;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值