[Add/Remove Check] SpringBoot integrates SolrClient of Solr to implement CRUD, paging interface, highlighting

1. Preface


Any back-end database, such as MySQL, Oracle, Redis, Solr, Elasticsearch, MongoDB, encapsulated in SpringBoot first by SpringData, is extremely elegant and concise

Attached are search engine actual cases using solr to simulate Baidu once:
Use LayUI+SpringBoot+Solr to mimic Baidu's search engine

2. Code

Update 2018.7.14: Code is already on github: https://github.com/larger5/SpringBoot_solr_base.git

1. Code directory

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;

/**
 * Optimize: Extract Id, text as a JavaBean
 * @author linhongcun
 *
 */
@RestController
@RequestMapping("/test")
@EnableSwagger2
public class SolrController {

    @Autowired
    private SolrClient client;

    /**
     * 1,increase
     * @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);

            /*
             * If core is configured in spring.data.solr.host, then there is no need to pass collection1. The following parameters are the same:
             * client.commit();
             */

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

    /**
     * 2,Check 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,Delete 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,Delete all
     * @return
     */
    @DeleteMapping("deleteAll")
    public String deleteAll() {
        try {

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

    /**
     * 5,change
     * @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);

            /*
             * If core is configured in spring.data.solr.host, then there is no need to pass itaem here. The following parameters are the same:
             * client.commit();
             */
            client.add("itaem", doc);
            client.commit("itaem");
            return doc.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 6,All: Not yet, I don't feel necessary
     * @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,Check++: Keyword, Highlight, Paging_
     * @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();

        // query criteria
        params.set("q", q);

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

        // paging
        params.setStart(page);
        params.setRows(size);

        // Default Domain
        params.set("df", "text");

        // Query only specified fields
        params.set("fl", "id,text");

        // Turn on highlighting
        params.setHighlight(true);
        // Set prefix
        params.setHighlightSimplePre("<span style='color:red'>");
        // Set Suffix
        params.setHighlightSimplePost("</span>");

        // The solr database is itaem
        QueryResponse queryResponse = client.query("itaem", params);
        SolrDocumentList results = queryResponse.getResults();

        // Quantity, Paging
        long total = results.getNumFound();// JS uses size=MXA and data.length to know the length (but not reasonable)

        // Get highlighted results, highlighted results are separated from query results
        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

3. Effect

The interfaces have been tested by Swagger and are completely OK

1. Solr interface can be opened

http://120.79.197.131:8983/solr Since this Solr was built on an Ali Cloud server using a Docker mirror, the above error flaws need not be ignored

2. Interface Testing

3. Highlighting effect

First insert the following information to enter for query
Recently, the United States took the abuse of trade relief measures against China due to the trade imbalance between China and the United States, followed by a 301-year rust investigation stick in the United States, threatening to impose high tariffs on China's $60 billion commodities, causing sharp fluctuations in the global capital market and triggering China and the rest of the world
  • 1

(2) Query

Input: United States of America
  • 1

(3) JSON display

(4) Page display

4. Summary

Reference
1. Li Jiazhi, Essence of SpringBoot 2
2,Solr6 Quick Start Tutorial
3,Docker+Solr+IK
4,solr(4): springboot integrated solr

                        <li class="tool-item tool-active is-like "><a href="javascript:;"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#csdnc-thumbsup"></use>
                        </svg><span class="name">compliment</span>
                        <span class="count">3</span>
                        </a></li>
                        <li class="tool-item tool-active is-collection "><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;popu_824&quot;}"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-csdnc-Collection-G"></use>
                        </svg><span class="name">collection</span></a></li>
                        <li class="tool-item tool-active is-share"><a href="javascript:;" data-report-click="{&quot;mod&quot;:&quot;1582594662_002&quot;}"><svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-csdnc-fenxiang"></use>
                        </svg>Share</a></li>
                        <!--Start rewarding-->
                                                <!--End of reward-->
                                                <li class="tool-item tool-more">
                            <a>
                            <svg t="1575545411852" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5717" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><defs><style type="text/css"></style></defs><path d="M179.176 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5718"></path><path d="M509.684 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5719"></path><path d="M846.175 499.222m-113.245 0a113.245 113.245 0 1 0 226.49 0 113.245 113.245 0 1 0-226.49 0Z" p-id="5720"></path></svg>
                            </a>
                            <ul class="more-box">
                                <li class="item"><a class="article-report">article report</a></li>
                            </ul>
                        </li>
                                            </ul>
                </div>
                            </div>
            <div class="person-messagebox">
                <div class="left-message"><a href="https://blog.csdn.net/larger5">
                    <img src="https://profile.csdnimg.cn/3/D/3/3_larger5" class="avatar_pic" username="larger5">
                                            <img src="https://g.csdnimg.cn/static/user-reg-year/2x/3.png" class="user-years">
                                    </a></div>
                <div class="middle-message">
                                        <div class="title"><span class="tit"><a href="https://blog.csdn.net/larger5" data-report-click="{&quot;mod&quot;:&quot;popu_379&quot;}" target="_blank">larger5</a></span>
                                            </div>
                    <div class="text"><span>104 original articles were published</span> <span>459</span> <span>870,000 visits+</span> </div>
                </div>
                                <div class="right-message">
                                            <a href="https://bbs.csdn.net/topics/395525761" target="_blank" class="btn-sm btn-red-hollow bt-button personal-messageboard">his message board
                        </a>
                                                            <a class="btn btn-sm attented bt-button personal-watch" data-report-click="{" mod":" popu_379"}">Attentioned</a>
                                    </div>
                            </div>
                    </div>
    
    Published 30 original articles, won approval 2, visited 1173
    Private letter follow

    Keywords: solr Apache Java SpringBoot

    Added by delphi123 on Wed, 04 Mar 2020 03:42:39 +0200