SpringBoot--实战开发--整合Solr(十八)
2019-08-21 本文已影响0人
无剑_君
一、Solr 简介
Solr是一个独立的企业级搜索应用服务器,它对外提供类似于Web-service的API接口。用户可以通过http请求,向搜索引擎服务器提交一定格式的XML文件,生成索引;也可以通过Http Get操作提出查找请求,并得到XML格式的返回结果。
二、Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--slor依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
三、Solr 配置
# 单机版:solr服务器配置 core1 相当于数据库名,需要创建
spring.data.solr.host=http://192.168.247.128:8983/solr/core1
四、操作Solr
- 实体类
@Data
public class User implements Serializable {
// 必须实现可序列化接口,要在网络上传输
// 使用 @Field注解,里面的名字是根据你在solr数据库中配置的来决定
@Field("id")
private String id;
@Field("item_name")
private String name;
@Field("item_sex")
private String sex;
@Field("item_address")
private String address;
@Field("item_host")
private Integer host;
}
- 业务接口与实现
public interface SolrService {
List<User> addUser();
}
@Service
public class SolrServiceImpl implements SolrService {
@Override
public List<User> addUser() {
List<User> list = new ArrayList<>();
User user = new User();
for (int i = 0; i <5 ; i++) {
user.setId(UUID.randomUUID().toString().replace("-",""));
user.setName("jack"+i);
if( i % 2 ==0) {
user.setSex("男");
}else {
user.setSex("女");
}
user.setAddress("太原市迎泽区"+i);
user.setHost(73040+i);
list.add(user);
}
return list;
}
}
- 控制器
@RestController
@RequestMapping("/solr")
@Slf4j
public class SolrController {
@Autowired
private SolrService solrService;
// 获取solr客户端
@Autowired
private SolrClient solrClient;
// 批量增加
@PostMapping("/addUsers")
public void addUsers() throws IOException, SolrServerException {
List<User> users = solrService.addUser();
solrClient.addBeans(users);
// 提交数据
solrClient.commit();
}
// 单个增加
@PostMapping("/addUser")
public void addUser() throws IOException, SolrServerException {
User user = new User();
user.setId("456788");
user.setName("张慧");
user.setAddress("北京市");
user.setSex("女");
user.setHost(456752);
solrClient.addBean(user);
solrClient.commit();
}
// 根据id查询
@GetMapping("/getByIdFromSolr/{id}")
public void getByIdFromSolr(@PathVariable("id") String id) throws IOException, SolrServerException {
// 根据id查询内容
SolrDocument solrDocument = solrClient.getById(id);
// 获取filedName
Collection<String> fieldNames = solrDocument.getFieldNames();
// 获取file名和内容
Map<String, Object> fieldValueMap = solrDocument.getFieldValueMap();
List<SolrDocument> childDocuments = solrDocument.getChildDocuments();
log.info("byId==================" + solrDocument);
log.info("fieldNames==================" + fieldNames);
log.info("fieldValueMap==================" + fieldValueMap);
log.info("childDocuments==================" + childDocuments);
}
// 根据id删除
@DeleteMapping("/delById/{id}")
public void delById(@PathVariable("id") String id) throws IOException, SolrServerException {
//根据id删除信息
UpdateResponse updateResponse = solrClient.deleteById(id);
//执行的时间
long elapsedTime = updateResponse.getElapsedTime();
int qTime = updateResponse.getQTime();
//请求地址
String requestUrl = updateResponse.getRequestUrl();
//请求的结果{responseHeader={status=0,QTime=2}}
NamedList<Object> response = updateResponse.getResponse();
//请求结果的头{status=0,QTime=2}
NamedList responseHeader = updateResponse.getResponseHeader();
//请求的状态 0
int status = updateResponse.getStatus();
log.info("elapsedTime===========" + elapsedTime);
log.info("qTime===========" + qTime);
log.info("requestUrl===========" + requestUrl);
log.info("response===========" + response);
log.info("responseHeader===========" + responseHeader);
log.info("status===========" + status);
}
// 查询solr
@GetMapping("/queryFromSolr")
public Object queryFromSolr() throws IOException, SolrServerException {
//第一种方式
// Map<String, String> queryParamMap = new HashMap<String, String>();
// queryParamMap.put("q", "*:*");
// queryParamMap.put("f1","id,name");
// queryParamMap.put("sort","id asc");
// MapSolrParams mapSolrParams = new MapSolrParams(queryParamMap);
// solrClient.query(mapSolrParams);
//第二种方式
SolrQuery solrQuery = new SolrQuery();
solrQuery.setQuery("*:*");
// solrQuery.addField("*");
solrQuery.add("q", "id:4567");
solrQuery.setSort("id", SolrQuery.ORDER.asc);
//设置查询的条数
solrQuery.setRows(50);
//设置查询的开始
solrQuery.setStart(0);
//设置高亮
solrQuery.setHighlight(true);
//设置高亮的字段
solrQuery.addHighlightField("item_name");
//设置高亮的样式
solrQuery.setHighlightSimplePre("<font color='red'>");
solrQuery.setHighlightSimplePost("</font>");
log.info("{}",solrQuery);
QueryResponse response = solrClient.query(solrQuery);
//返回高亮显示结果
Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
//response.getResults();查询返回的结果
SolrDocumentList documentList = response.getResults();
for (SolrDocument solrDocument : documentList) {
log.info("solrDocument==============" + solrDocument);
}
return documentList;
}
}
-
测试
POST请求:localhost:9999/solr/addUsers
批量操作
POST请求:localhost:9999/solr/addUser
单个增加
GET请求:localhost:9999/solr/getByIdFromSolr/456788
根据id查询
GET请求:localhost:9999/solr/queryFromSolr
查询solr
DELETE请求:localhost:9999/solr/delById/456788
根据id删除
- 配置字段高亮显示
/**
* 设置结果高亮显示
*/
@Test
public void hl() throws IOException, SolrServerException {
/**
* 集群版CloudSolrClient继承自SolrClient 进行强转
* 单机版不需要直接使用solrClient
*/
CloudSolrClient cloudSolrClient =(CloudSolrClient)solrClient;
//设置默认的操作实例
cloudSolrClient.setDefaultCollection("collection1");
//设置查找的参数
SolrQuery query = new SolrQuery();
query.setQuery("item_title:手机");
//开启高亮
query.setHighlight(true);
//设置高亮字段
query.addHighlightField("item_title");
//前缀
query.setHighlightSimplePre("<font color='red'>");
//后缀
query.setHighlightSimplePost("</font>");
//执行查找
QueryResponse response = cloudSolrClient.query(query);
//打印高亮信息
log.info(response.getHighlighting());
}