SpringBoot+solr
1.配置application.yml
spring.data.solr.host: http://192.168.6.168:8080/solr/ciri_core
2.引入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
3.使用solrj增删改查
@Service
public class SolrServiceImpl implements SolrService {
@Autowired
private SolrClient solrClient;
@Autowired
private SolrMapper solrMapper;
public List<SolrDto> query() throws IOException, SolrServerException {
SolrQuery solrQuery = new SolrQuery();
solrQuery.set("q","s_name:花");
QueryResponse response = solrClient.query(solrQuery);
//获取对象
List<Solr> beans = response.getBeans(Solr.class);
//Solr solr = beans.get(0);
return null;
}
//不使用实体返回solr查询结果
public List<SolrDto> queryNoBeans() throws IOException, SolrServerException {
List<SolrDto> solrList = new LinkedList<SolrDto>();
SolrQuery solrQuery = new SolrQuery();
//查询条件
solrQuery.set("q","s_name:花");
//过滤条件
//solrQuery.set("fq", "s_price:[30 TO 50]");
//排序
solrQuery.addSort("s_orderBy", SolrQuery.ORDER.asc);
//分页
solrQuery.setStart(0);
solrQuery.setRows(5);
//默认域
// params.set("df", "s_title");
//只查询指定域
//solrQuery.set("fl", "id,s_name,s_price");
//高亮
//打开开关
solrQuery.setHighlight(true);
//指定高亮域
solrQuery.addHighlightField("s_name");
//设置前缀
solrQuery.setHighlightSimplePre("<span style='color:red'>");
//设置后缀
solrQuery.setHighlightSimplePost("</span>");
System.out.println(solrQuery.toString());
QueryResponse response = solrClient.query(solrQuery);
SolrDocumentList results = response.getResults();
long numFound = results.getNumFound();
//获取高亮显示的结果, 高亮显示的结果和查询结果是分开放的
Map<String, Map<String, List<String>>> highlight = response.getHighlighting();
for (SolrDocument result : results) {
SolrDto solrDto = new SolrDto();
String id = (String) result.get("id");
solrDto.setId(Integer.parseInt(id));
solrDto.setPrice((Double) result.get("s_price"));
Map<String, List<String>> map = highlight.get(result.get("id"));
List<String> list = map.get("s_name");
solrDto.setName(list.get(0));
solrList.add(solrDto);
}
return solrList;
}
@Override
public void save() throws Exception {
Solr solr = solrMapper.selectByPrimaryKey(2);
//solr8小时时差
Date updatedtime = solr.getUpdatedtime();
updatedtime.setTime(updatedtime.getTime()+28800000L);
solr.setUpdatedtime(updatedtime);
solrClient.addBean(solr);
solrClient.commit();
}
public void delete(String id) throws Exception {
solrClient.deleteById(id);
solrClient.commit();
}
3.使用solrj对象 id为字符串 对应field
@SolrDocument(solrCoreName = "ciri_core")
public class Solr implements Serializable {
@Field("id")
private String id;
@Field("s_name")
private String name;
@Field("s_title")
private String title;
private Integer category;
@Field("s_content")
private String content;
@Field("s_price")
private Double price;
@Field("s_color")
private String color;
@Field("s_orderBy")
private Integer orderby;
@Field("s_updatetime")
private Date updatedtime;
get/set方法
}