(1)安装solr,修改配置文件中的数据库、实例(需要检索的字段)、分词器等;(详情见上篇博文)。
(2)控制台创建实例、导入数据(详情见上篇博文);
(3)导包:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
(3)全文检索时,将查询的字段、字段名传入solrClient的query方法,设置q、start、rows属性,得到SolrDocument的结果集,循环手动封装到实体类中。
public class SolrService {
@Autowired
private SolrClient solrClient;
@Autowired
private ProductDAO productDAO;
public List<Product> getSolr(String keyword) {
String p ="proName:"+"*"+keyword+"*";
ModifiableSolrParams params = new ModifiableSolrParams();
params.add("q",p);
//分页(默认10)
params.add("start","0");
params.add("rows","5");
List<Product> productList = new ArrayList<>();
try {
QueryResponse queryResponse = solrClient.query(params);
SolrDocumentList solrDocuments = queryResponse.getResults();
Product product = new Product();
for (SolrDocument solrDocument : solrDocuments) {
Object bookName = solrDocument.get("proName");
Object id = solrDocument.get("id");
String s = id.toString();
Product product1 = productDAO.selectProductById(Integer.valueOf(s));
productList.add(product1);
}
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return productList;
}
}
(4)写一个定时任务定时更新solr。
@Component
@Configurable
@EnableScheduling
public class ScheduledTasks {
/**
* 定时跟新solr服务器
*/
@Autowired
private SolrClient solrClient;
@Scheduled(cron = "0 0 0 1/1 * ?")
public void reportCurrentTime(){
SolrQuery query = new SolrQuery();
query.setRequestHandler("/dataimport");
String command = "delta-import";
String clean = "false";
String optimize = "false";
query.setParam("command", command)
.setParam("clean", false)
.setParam("commit", "true")
// .setParam("entity", "")
.setParam("optimize", optimize);
try {
solrClient.query(query);
solrClient.commit();
System.out.println(" ///"+command);
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}