您的位置:首页 > 编程语言 > Java开发

[增删改查] SpringBoot 整合 Solr 之 SolrClient 实现 CRUD、分页接口、高亮显示

2018-03-31 13:27 1331 查看

一、前言

任何后端数据库,如 MySQL、Oracle、Redis、Solr、Elasticsearch、MongoDB,SpringBoot 中,先经过 SpringData 的封装,都是无比优雅简洁的。

参考文献

1、
《SpringBoot 2 精髓》
李家智

2、Solr6 快速入门教程

3、Docker+Solr+IK

4、solr(四) : springboot 整合 solr

二、代码

talk is cheap show me the code


1、代码目录

很简单的,所以把 entity、dao、Service 这三层都省略掉了




2、Controller

package com.cun.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
4000
import org.springframework.web.bind.annotation.RestController;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
* 优化:抽取 Id、text 为一个 JavaBean
* @author linhongcun
*
*/
@RestController
@RequestMapping("/test")
@EnableSwagger2
public class SolrController {

@Autowired
private SolrClient client;

/**
* 1、增
* @param message
* @return
* @throws IOException
* @throws SolrServerException
*/
@PostMapping("/insert")
public String insert(String message) throws IOException, SolrServerException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
String dateString = sdf.format(new Date());
try {
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id", dateString);
doc.setField("text", message);

/*
* 如果 spring.data.solr.host 里面配置到 core了, 那么这里就不需要传 collection1 这个参数 下面都是一样的 即
* client.commit();
*/

client.add("itaem", doc);
client.commit("itaem");
return dateString;
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}

/**
* 2、查 id
* @param id
* @return
* @throws SolrServerException
* @throws IOException
*/
@GetMapping("/get/{id}")
public String getDocumentById(@PathVariable String id) throws SolrServerException, IOException {
SolrDocument document = client.getById("itaem", id);
System.out.println(document);
return document.toString();

}

/**
* 3、删 id
* @return
*/
@DeleteMapping("/delete/{id}")
public String getAllDocuments(@PathVariable String id) {
try {
client.deleteById("itaem", id);
client.commit("itaem");
return id;
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}

/**
* 4、删 all
* @return
*/
@DeleteMapping("deleteAll")
public String deleteAll() {
try {

client.deleteByQuery("itaem", "*:*");
client.commit("itaem");
return "success";
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}

/**
* 5、改
* @param message
* @return
* @throws IOException
* @throws SolrServerException
*/
@PutMapping("/update")
public String update(String id, String message) throws IOException, SolrServerException {
try {
SolrInputDocument doc = new SolrInputDocument();
doc.setField("id", id);
doc.setField("text", message);

/*
* 如果 spring.data.solr.host 里面配置到 core了, 那么这里就不需要传 itaem 这个参数 下面都是一样的 即
* client.commit();
*/
client.add("itaem", doc);
client.commit("itaem");
return doc.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "error";
}

/**
* 6、全
* @return
* @throws SolrServerException
* @throws IOException
*/
@GetMapping("/get/all")
public Map<String, Object> getAll()
throws SolrServerException, IOException {
Map<String, Object> map = new HashMap<String, Object>();
return map;
}

/**
* 7、查  ++:关键字、高亮、分页  ✔
* @return
* @return
* @throws SolrServerException
* @throws IOException
*/
@GetMapping("/select/{q}/{page}/{size}")
public Map<String, Object> select(@PathVariable String q, @PathVariable Integer page, @PathVariable Integer size)
throws SolrServerException, IOException {
SolrQuery params = new SolrQuery();

// 查询条件
params.set("q", q);

// 排序
params.addSort("id", SolrQuery.ORDER.desc);

// 分页
params.setStart(page);
params.setRows(size);

// 默认域
params.set("df", "text");

// 只查询指定域
params.set("fl", "id,text");

// 开启高亮
params.setHighlight(true);
// 设置前缀
params.setHighlightSimplePre("<span style='color:red'>");
// 设置后缀
params.setHighlightSimplePost("</span>");

// solr数据库是 itaem
QueryResponse queryResponse = client.query("itaem", params);
SolrDocumentList results = queryResponse.getResults();

// 数量,分页用
long total = results.getNumFound();// JS 使用 size=MXA 和 data.length 即可知道长度了(但不合理)

// 获取高亮显示的结果, 高亮显示的结果和查询结果是分开放的
Map<String, Map<String, List<String>>> highlight = queryResponse.getHighlighting();
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", total);
map.put("data", highlight);
return map;

}

}


3、yml

server:
context-path: /
port: 80
spring:
data:
solr:
host: http://120.79.197.131:8983/solr[/code] 

三、效果

接口均经过 Swagger 测试,完全没有问题


1、可以打开 Solr 界面

http://120.79.197.131:8983/solr ,由于 这个 Solr 是在
阿里云服务器
上,切使用
Docker
镜像搭建的,上面的报错瑕疵不必理会



2、接口测试



3、高亮效果

①先插入如下信息进入,以备查询

近期美国以中美贸易不平衡为由,对中国先采取滥用贸易救济措施的做法,接着挥舞美国国内生锈的301调查大棒,威胁要对中国600亿美元的商品征收高额关税,引起了全球资本市场的剧烈波动,也引发了中国和其他世


②查询

输入:美利坚合众国




③JSON显示



④页面显示

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐