一、solr安装到linux中
二、将数据库的tbItem中的字段信息添加到solr索引库中
1)pojo中对应的字段上要添加注解
2)solr中的索引库的scheml.xml文件中也要添加对应的字段
3)开启工具类
涉及的工具类:
public class SolrUtils {
//注入mapper接口代理对象
@Autowired
private TbItemMapper itemMapper;
//注入solr模板
@Autowired
private SolrTemplate solrTemplate;
/**
* 需求:
* 1,查询数据库
* 2,把数据导入索引库
*/
public void importDataToSolrIndex() {
//创建example对象
TbItemExample example = new TbItemExample();
//创建criteria对象
Criteria createCriteria = example.createCriteria();
//设置查询参数
createCriteria.andStatusEqualTo("1");
//查询数据库所有数据
List<TbItem> list = itemMapper.selectByExample(example);
//动态域
for (TbItem tbItem : list) {
//获取规格属性值
//{"网络制式":""}
String spec = tbItem.getSpec();
//把规格值转换成map对象
Map<String, String> specMap= (Map<String, String>) JSON.parse(spec);
//把规格属性添加到动态域字段
tbItem.setSpecMap(specMap);
}
solrTemplate.saveBeans(list);
//提交
solrTemplate.commit();
}
public static void main(String[] args) {
//加载配置文件
ApplicationContext app = new ClassPathXmlApplicationContext("classpath*:spring/*.xml");
//获取工具类对象
SolrUtils solrUtils = app.getBean(SolrUtils.class);
//调用数据导入方法
solrUtils.importDataToSolrIndex();
}
}
涉及的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:solr="http://www.springframework.org/schema/data/solr"
xsi:schemaLocation="http://www.springframework.org/schema/data/solr
http://www.springframework.org/schema/data/solr/spring-solr-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- solr 服务器地址 -->
<solr:solr-server id="solrServer" url="http://192.168.66.66:8081/solr/item" />
<!-- solr 模板,使用 solr 模板可对索引库进行 CRUD 的操作 -->
<bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate">
<constructor-arg ref="solrServer" />
</bean>
</beans>