项目实训——上下文查询

用户在搜索段落之后,可以点击段落查询上下文。

一、具体实现

与根据关键词查询段落不同的是,前者是在lucene创建的索引文件中查询,而上下文的查询是到mongodb数据库中去查询。

业务流程:前端传递bookid,controller接收到之后传递给service,service调用dao,层层返回。

controller层:

    @Autowired
    private TextService txtService;
    @GetMapping("/getCont")
    public R getText(@RequestParam String id) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
        return new R(true, txtService.getText( id));
    }

service层:

    @Autowired
    private ContentDao contentDao;

    public List<ContentInfo> getText(String id) throws NoSuchFieldException, IllegalAccessException, ClassNotFoundException {
        return contentDao.findCont( id);
    }

dao层:

@Repository
public class ContentDao {

    private String[] books = {"zyjcll", "zykfx", "jlx", "nkx"};
    @Autowired
    private MongoTemplate mongoTemplate;

    /*
    查询上下文,小于当前id的前五个
    1、将小于当前id的按逆序查找,返回前五个放到list中list再反转
    2、先计算小于id的总数,skip过前面所有的,保留后五个
    3、计算出objectid的范围再精准查询
    */
    public List<ContentInfo> findCont(String id) throws NoSuchFieldException, IllegalAccessException {
        Query query1=new Query();
        ObjectId objectId = new ObjectId(id);
        query1.addCriteria(Criteria.where("_id").lt(objectId)).with(Sort.by(Sort.Direction.DESC, "_id"));
        query1.limit(5);
        Query query2=new Query();
        query2.addCriteria(Criteria.where("_id").gte(objectId));
        query2.limit(5);
        List<ContentInfo> res=mongoTemplate.find(query1, ContentInfo.class);
        Collections.reverse(res);
        res.addAll(mongoTemplate.find(query2, ContentInfo.class));
        return res;
    }

    /*
    将书本存放在不同的数据库中
     */
    public List<ContentInfo> findText(String book, String id) throws ClassNotFoundException {
        Class myclass = Class.forName("com.example.demo.entity.contents."+book);
        List<ContentInfo> res = new ArrayList<>();
        Query query1=new Query();
        ObjectId objectId = new ObjectId(id);
        query1.addCriteria(Criteria.where("_id").lt(objectId)).with(Sort.by(Sort.Direction.DESC, "_id"));
        query1.limit(5);
        Query query2=new Query();
        query2.addCriteria(Criteria.where("_id").gte(objectId));
        query2.limit(5);
        res.addAll(mongoTemplate.find(query1, myclass));
        Collections.reverse(res);
        res.addAll(mongoTemplate.find(query2, myclass));
        return res;
    }
}

二、查询优化

在设计数据库的时候考虑了两种数据库设计,一种是将所有书籍信息存放到一个数据库中查询时直接根据id让mongotemplate到mongodb中查询;另一种是将书籍段落分开存放在数据库中,查询的时候根据book名选择collection,之后再查询,以下是两者的速度对比。

 

两者查询速度查询不大,最后我们选择采用第一种方式。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值