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

1 篇文章 0 订阅

一、前言

这里写图片描述
任何后端数据库,如 MySQL、Oracle、Redis、Solr、Elasticsearch、MongoDB,在 SpringBoot 中,先经过 SpringData 的封装,都是无比优雅简洁的

附上使用 solr 模拟百度一下的搜索引擎实战案例:
使用 LayUI+SpringBoot+Solr 模仿百度一下搜索引擎

二、代码

2018.7.14更新:代码已经放在 github 上了:https://github.com/larger5/SpringBoot_solr_base.git

1、代码目录

这里写图片描述

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;
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
  
  

三、效果

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

 
 

1、可以打开 Solr 界面

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

这里写图片描述

2、接口测试

这里写图片描述

3、高亮效果

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

 
 
  • 1
②查询
输入:美利坚合众国

 
 
  • 1

这里写图片描述

③JSON显示

这里写图片描述

④页面显示

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值