Solr介绍
Solr是一个高性能,采用Java5开发,基于Lucene的全文搜索服务器。同时对其进行了扩展,提供了比Lucene更为丰富的查询语言,同时实现了可配置、可扩展并对查询性能进行了优化,并且提供了一个完善的功能管理界面,是一款非常优秀的全文搜索引擎。
SpringBoot集成Solr
- 添加springboot集成solr的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
- application.yml指向solr地址
spring:
data:
solr:
host: http://192.168.0.197:8983/solr/ik_core
- 添加solr实时更新操作
@SpringBootApplication
@EnableScheduling
public class SpringbootSolrApplication {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private RestTemplateBuilder builder;
@Autowired
private RestTemplate restTemplate;
// 使用RestTemplateBuilder来实例化RestTemplate对象,spring默认已经注入了RestTemplateBuilder实例
@Bean
public RestTemplate restTemplate() {
return builder.build();
}
public static void main(String[] args) {
SpringApplication.run(SpringbootSolrApplication.class, args);
}
//每五秒执行一次
@Scheduled(cron = "0/5 * * * * *")
public void updateSolr() {
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
postParameters.add("command", "full-import");
postParameters.add("verbose", "false");
postParameters.add("clean", "true");
postParameters.add("commit", "true");
postParameters.add("core", "ik_core");
postParameters.add("name", "dataimport");
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
HttpEntity <MultiValueMap <String, Object>> r = new HttpEntity<>(postParameters, headers);
String time = String.valueOf(new Date().getTime());
String url = "http://192.168.0.197:8983/solr/ik_core/dataimport?_=" + time + "&indent=on&wt=json";
String responseMessage = restTemplate.postForObject(url, r, String.class);
logger.info("更新solr索引:返回值:{}", responseMessage);
}
}
- 测试查询(增加了高亮显示)
@Test
public void test() throws IOException, SolrServerException {
SolrQuery solrQuery = new SolrQuery();
solrQuery.set("q", "title:*");
solrQuery.set("start", 0);
solrQuery.set("rows", 20);
//======高亮设置===
//开启高亮
solrQuery.setHighlight(true);
//高亮域
solrQuery.addHighlightField("title");
//前缀
solrQuery.setHighlightSimplePre("<span style='color:red'>");
//后缀
solrQuery.setHighlightSimplePost("</span>");
QueryResponse response = solrClient.query(solrQuery);
SolrDocumentList results = response.getResults();
System.out.println("查询内容:" + solrQuery);
System.out.println("文档数量:" + results.getNumFound());
System.out.println("查询花费时间:" + response.getQTime());
//获取高亮信息
Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
for (SolrDocument solrDocument :results) {
System.out.println(solrDocument);
System.out.println(solrDocument.getFieldValue("cover"));
System.out.println(solrDocument.getFieldValue("service_area"));
//输出高亮
Map<String, List<String>> map = highlighting.get(solrDocument.get("id"));
List<String> list = map.get("title");
if(list != null && list.size() > 0){
System.out.println(list.get(0));
}
}
}
网友评论