投影
CustomMusicRepository接口中增加:
public ScoredPage<Music> searchByNameProjection(String searchName, long pageIndex, int pageSize);
MusicRepositoryImpl实现:
@Override
public ScoredPage<Music> searchByNameProjection(String searchName, long pageIndex, int pageSize) {
String[] words = searchName.toUpperCase().split(" ");
String[] contidionFields = new String[]{Music.FIELD_SONG_NAME, Music.FIELD_SINGER_NAME};
Criteria conditions = createSearchConditions(contidionFields, words);
SimpleQuery search = new SimpleQuery(conditions);
// 投影
search.addProjectionOnField(Music.FIELD_SONG_NAME);
search.setOffset(pageIndex);
search.setRows(pageSize);
ScoredPage<Music> page = solrTemplate.queryForPage(Music.CORE_NAME, search, Music.class);
return page;
}
以上代码将songName加入到投影中,那么输出就只有songName才会有值,其余字段均为null。
测试代码:
@Test
public void searchByNameProjection() {
ScoredPage<Music> musicList = musicRepository.searchByNameProjection("刘德华", 0, 10);
for (Music music : musicList.getContent()) {
System.out.println(music);
}
}
结果如下:
com.ali.model.Music@64a8c844[resId=<null>,songId=<null>,songName=《追龙》持续超车 刘德华身兼化妆师搬运工,singerName=<null>,keywords=<null>]
com.ali.model.Music@3f6db3fb[resId=<null>,songId=<null>,songName=情深的一句,singerName=<null>,keywords=<null>]
com.ali.model.Music@52de51b6[resId=<null>,songId=<null>,songName=无心快意,singerName=<null>,keywords=<null>]
com.ali.model.Music@18c5069b[resId=<null>,songId=<null>,songName=刘德华,singerName=<null>,keywords=<null>] |