用户在搜索段落之后,可以点击段落查询上下文。
一、具体实现
与根据关键词查询段落不同的是,前者是在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,之后再查询,以下是两者的速度对比。
两者查询速度查询不大,最后我们选择采用第一种方式。