Solr is introduced

Solr is highly reliable, scalable and fault-tolerant, providing distributed indexing, replication and load-balancing queries, automatic failover and recovery, centralized configuration, and more. Solr provides search and navigation capabilities for many of the world’s largest Internet sites.

Solr is a standalone enterprise search server with restful apis. You can put documents into it via JSON, XML, CSV, or HTTP binaries (called “indexing”). You query it via HTTP GET and receive JSON, XML, CSV, or binary results.

Advanced full-text search function

With Lucene ™ support, Solr implements powerful matching capabilities, including phrases, wildcards, joins, grouping, and more, across any data type

Optimized for heavy flow

Solr has been widely proven worldwide

Standards-based open interfaces -XML, JSON and HTTP

Solr uses the tools you use to make your applications build quickly

Comprehensive management interface

Solr comes with a built-in responsive management user interface that makes it easy to control your Solr instances

Easy to monitor

Need a deeper look at your example? Solr publishes load metric data through JMX

Highly extensible and fault tolerant

Solr is built on the battle-tested Apache Zookeeper and can be easily scaled up and down. Solr copies, distributes, rebalances and tolerates faults right out of the box.

Flexible and adaptable, simple configuration

Solr’s is designed to meet all your needs while simplifying configuration

Near real time index

Want to see your updates now? Solr takes advantage of Lucene’s near-real-time indexing capabilities to ensure that you see content as you see it

Extensible plug-in architecture

Solr has released a number of well-defined extension points that make it easy to insert index and query time plug-ins. Of course, since it’s apache-licensed open source, you can change whatever code you need!

The installation

Official website to download address: lucene.apache.org/solr/downlo…

Download speed can be a lot faster: download.csdn.net/download/ta…

Download for Windows

Mine is solr-7.7.2.zip, unzip

Bin: solr command file contrib: solr plug-in dist: Solr JAR package Docs: Solr document example: Solr example licenses: Solr certificate server: Solr server core file

Setting environment variables to facilitate startup: solr’s bin directory

Start the

solr start
Copy the code

Do not want to configure environment traversal

// Go to the solr bin directory solr.cmd startCopy the code

Other commands solr start -p port number Single-server edition Starting the Solr service (default port number 8983) solr restart -p port number Restarting the solr service solr stop -p port number Disabling the Solr serviceCopy the code

The installation is complete when the solr page is displayed.

Used in Spring Boot

Create core on the Solr page

solr create -c demo
Copy the code

 

A demo file will be generated in the solr directory:

Go to conf directory:

XML and schema. XML. In Solr releases (before Solr5), when core is created, Solr automatically creates schema. XML. In later releases, Solr automatically creates schema. XML. The generated managed-schema is schema. XML. Rename the managed-schema file directly to schema.xml

Basic configuration complete

Add, delete, change and check data in spring Boot project

Add a solr dependency to Spring Boot

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-solr</artifactId>
</dependency>
Copy the code

Yml Configures solR port information

spring:
  data:
    solr:
      host: http://localhost:8983/solr/demo
Copy the code

Add the entity class UserSolr

import lombok.Data;
import org.apache.solr.client.solrj.beans.Field;

import java.io.Serializable;

/ * * *@authorAbstract scholar *@date: Created in 2020/1/6 9:34 *@Time: neither have *@description: Search engine entity class *@modified By:
 * @version: 1.0 $* /
@Data
public class UserSolr implements Serializable {

    // The serializable interface must be implemented and transmitted over the network
    @Field("id")// Using this annotation, the name in the annotation is determined according to the configuration in the solr database
    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;

}
Copy the code

SolrService

public interface SolrService {

    List<UserSolr> addUser(a);
}
Copy the code

SolrServiceImpl

@Service
public class SolrServiceImpl implements SolrService {

    @Override
    public List<UserSolr> addUser(a) {
        List<UserSolr> list = new ArrayList<>();
        UserSolr user = new UserSolr();
        for (int i = 0; i <5 ; i++) {
            user.setId(UUID.randomUUID().toString().replace("-".""));
            user.setName("jack"+i);
            if( i % 2= =0) {
                user.setSex("Male");
            }else {
                user.setSex("Female");
            }
            user.setAddress("666 anning District, Lanzhou city"+i);
            user.setHost(73040+i);
            list.add(user);
        }
        returnlist; }}Copy the code

SolrController


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.aop.log.Log;
import me.zhengjie.domain.UserSolr;
import me.zhengjie.service.SolrService;
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.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.NamedList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;


@Slf4j
@Controller
@RequestMapping("/api/solr")
@API (tags = "Tools: Search engine ")
@Component
public class SolrController {

    @Autowired
    private SolrService solrService;

    @Autowired
    private SolrClient solrClient;

    // Batch increment
    @GetMapping("/addUsers")
    @log (" batch increment ")
    @apiOperation (" Batch add ")
    @ResponseBody
    public void addUsers(a) throws IOException, SolrServerException {
        List<UserSolr> users = solrService.addUser();

        solrClient.addBeans(users);
        solrClient.commit();
    }
    // Single increment
    @GetMapping("/addUser")
    @Log(" single increment ")
    @apiOperation (" Single increment ")
    @ResponseBody
    public void addUser(a) throws IOException, SolrServerException {
        UserSolr user = new UserSolr();
        user.setId("456788");
        user.setName("Wang qiang");
        user.setAddress("Beijing");
        user.setSex("Female");
        user.setHost(456752);
        solrClient.addBean(user);
        solrClient.commit();
    }

    // Query according to di
    @GetMapping("/getByIdFromSolr/{id}")
    @log (" query by DI ")
    @apiOperation (" query according to di ")
    @ResponseBody
    public  void getByIdFromSolr(@PathVariable("id") String id) throws IOException, SolrServerException {

        // Query content by id
        SolrDocument solrDocument = solrClient.getById(id);
        / / get filedName
        Collection<String> fieldNames = solrDocument.getFieldNames();
        // Get the file name and contents
        Map<String, Object> fieldValueMap = solrDocument.getFieldValueMap();

// int childDocumentCount = solrDocument.getChildDocumentCount();

        List<SolrDocument> childDocuments = solrDocument.getChildDocuments();

        System.out.println("byId=================="+solrDocument);
        System.out.println("fieldNames=================="+fieldNames);
        System.out.println("fieldValueMap=================="+fieldValueMap);
// System.out.println("childDocumentCount=================="+childDocumentCount);
        System.out.println("childDocuments=================="+childDocuments);

    }
    // Delete according to di
    @DeleteMapping("/delById/{id}")
    @log (" delete according to di ")
    @apiOperation (" Delete according to di ")
    @ResponseBody
    public  void  delById(@PathVariable("id") String id) throws IOException, SolrServerException {
        // Delete information by id
        UpdateResponse updateResponse = solrClient.deleteById(id);
        // The execution time
        long elapsedTime = updateResponse.getElapsedTime();

        int qTime = updateResponse.getQTime();
        // Request an address
        String requestUrl = updateResponse.getRequestUrl();
        {responseHeader={status=0,QTime=2}}
        NamedList<Object> response = updateResponse.getResponse();
        {status=0,QTime=2}
        NamedList responseHeader = updateResponse.getResponseHeader();
        // Request status 0
        int status = updateResponse.getStatus();

        System.out.println("elapsedTime==========="+elapsedTime);
        System.out.println("qTime==========="+qTime);
        System.out.println("requestUrl==========="+requestUrl);
        System.out.println("response==========="+response);
        System.out.println("responseHeader==========="+responseHeader);
        System.out.println("status==========="+status);
    }

    @GetMapping("/queryFromSolr")
    @Log("queryFromSolr")
    @ApiOperation("queryFromSolr")
    public  Object  queryFromSolr(a) throws IOException, SolrServerException {
        // The first way
// Map
      
        queryParamMap = new HashMap
       
        ();
       ,>
      ,>
// queryParamMap.put("q", "*:*");
// queryParamMap.put("f1","id,name");
// queryParamMap.put("sort","id asc");
// MapSolrParams mapSolrParams = new MapSolrParams(queryParamMap);
// solrClient.query(mapSolrParams);

        // The second way
        SolrQuery solrQuery  = new SolrQuery();
        solrQuery.setQuery(: "* *");
// solrQuery.addField("*");
        solrQuery.add("q"."id:4567");

        solrQuery.setSort("id", SolrQuery.ORDER.asc);
        // Set the number of queries
        solrQuery.setRows(50);
        // Set the start of the query
        solrQuery.setStart(0);
        // Set the highlight
        solrQuery.setHighlight(true);
        // Set the highlighted fields
        solrQuery.addHighlightField("item_name");
        // Set the highlighted style
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        System.out.println(solrQuery);
        QueryResponse response = solrClient.query(solrQuery);
        // Returns the result highlighted
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        //response.getResults(); The result returned by the query
        SolrDocumentList documentList = response.getResults();
        for (SolrDocument solrDocument : documentList) {
            System.out.println("solrDocument==============" +solrDocument);
        }
        returndocumentList; }}Copy the code

Start testing:

Single increment:

successful

 

Volume increase

Delete by DI

Query by DI

 

 

Reference: lucene.apache.org/solr/

Reference for this article: blog.csdn.net/weixin_4212…