依赖
配置文件
SpringContext-solr.xml
<!-- solr服务器地址 -->
<solr:solr-server id="solrServer" url="http://127.0.0.1:8080/solr" />
<!-- solr模板,使用solr模板可对索引库进行CRUD的操作 -->
<bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
<constructor-arg ref="solrServer" />
</bean>
javaBean
增加索引库
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations=”classpath:applicationContext-solr.xml”)
public class TestTemplate {
@Autowired
private SolrTemplate solrTemplate;
@Test
public void testAdd(){
TbItem item=new TbItem();
item.setId(1L);
item.setBrand("华为");
item.setCategory("手机");
item.setGoodsId(1L);
item.setSeller("华为2号专卖店");
item.setTitle("华为Mate9");
item.setPrice(new BigDecimal(2000));
solrTemplate.saveBean(item);
solrTemplate.commit();
}
}
按主键查询
public void testFindOne(){
TbItem item = solrTemplate.getById(1, TbItem.class);
System.out.println(item.getTitle());
}
按主键删除
public void testDelete(){
solrTemplate.deleteById("1");
solrTemplate.commit();
}
分页查询
public void testPageQuery(){
Query query=new SimpleQuery("*:*");
query.setOffset(20);//开始索引(默认0)
query.setRows(20);//每页记录数(默认10)
ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class);
System.out.println("总记录数:"+page.getTotalElements());
List<TbItem> list = page.getContent();
for(TbItem item:list){
System.out.println(item.getTitle() +item.getPrice());
}
}
条件查询
public void testPageQueryMutil(){
Query query=new SimpleQuery("*:*");
Criteria criteria=new Criteria("item_title").contains("2");
criteria=criteria.and("item_title").contains("5");
query.addCriteria(criteria);
ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class);
System.out.println("总记录数:"+page.getTotalElements());
List<TbItem> list = page.getContent();
for(TbItem item:list){
System.out.println(item.getTitle() +item.getPrice());
}
}