spring boot with solr

Keywords: Java solr Spring Apache Jetty

1. Download solr version

http://archive.apache.org/dis...

After decompression, enter the bin directory, open cmd at the current location, and start it in jetty mode:

solr start -p 8983

Stop a single specified port

solr stop -p 8983

Stop all

solr stop -all

2. Enter management interface configuration

http://localhost:8983/solr

Use the Core Admin menu to add a data table, and then configure the fields of the new core (if you do not configure the code settings directly, the corresponding field type is array type by default)

3. solr query interface

q: query condition, key=value can be used for query, value can be used for fuzzy value

fq: filter condition

Sort: sort, rule: field must be an indexed field; field cannot be multivalued

start,rows: paging query

fl: the returned result set only returns the specified field

df: default query field

3. spring boot combined with solr

  • pom configures the corresponding jar package of solr
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-solr</artifactId>
            <version>2.1.6.RELEASE</version>
        </dependency>
  • Set solr's address
spring:
  data:
    solr:
      host: http://127.0.0.1:8983/solr
  • Write corresponding solr client operation class


/**
 * 
 * 2019/11/4 14:20
 * @description
 */
@Slf4j
@RestController
@RequestMapping("solr")
public class SolrController {
    @Autowired
    private SolrClient solrClient;
    private final static String solrDataName = "disShops";

    /**
     * Add store information to solr index
     * @return
     */
    @RequestMapping("addShopToSolr")
    public ResultData addShopToSolr(){
        List<DisCitys> disCitys = disCitysService.queryAllDisCitysList();
        disCitys = disCitys.stream().filter(c->c.getAreaType()==2).collect(Collectors.toList());
        disCitys.forEach(c->{
            try {
                List<SolrInputDocument> docs = new ArrayList<>();
                List<DisShopsResp> disShops = disShopsService.queryShopsByCityNo(c.getAreaNo(), null);
                disShops.forEach(d->{
                    SolrInputDocument doc = new SolrInputDocument();
                    doc.setField("id", d.getShopId());
                    doc.setField("shopNo", d.getShopNo());
                    doc.setField("shopName", d.getShopName());
                    doc.setField("address", d.getAddress());
                    doc.setField("cityNo", d.getCityNo());
                    doc.setField("orderSeq", d.getOrderSeq());
                    docs.add(doc);
                });
                if(docs.size()>0){
                    solrClient.add(solrDataName, docs);
                    solrClient.commit(solrDataName);
                }
            } catch (Exception e) {
                log.error("Add store to solr error,cityId:{},\n Error message:{}", c.getAreaNo(), e.getMessage());
            }
        });
        return new ResultData<>();
    }

    /**
     * solr query
     * @param queryParam
     * @param cityNo
     * @param page
     * @return
     */
    @RequestMapping("searchShop")
    public ResultData searchShop(@RequestParam("queryParam") String queryParam,
                                 @RequestParam("cityNo") String cityNo,
                                 PageHelperUtil page){
        try {
            SolrQuery query = new SolrQuery();
            //Query parameter q
            query.set("q", queryParam);
            //Filter condition
            query.set("fq", "cityNo:"+cityNo);
            query.addSort("orderSeq", SolrQuery.ORDER.asc);
            query.setStart((page.getPage()-1)*page.getRows());
            query.setRows(page.getRows());
            //Default lookup domain
            query.set("df", "shopName");
            //Set prefix and suffix for highlight and related fields
            query.setHighlight(true);
            query.addHighlightField("shopName");
            query.setHighlightSimplePre("<span style='color:red'>");
            query.setHighlightSimplePost("</span>");
            QueryResponse response = solrClient.query(solrDataName, query);
            SolrDocumentList results = response.getResults();
            long sumNum = results.getNumFound();
            if(sumNum > 0){
                //Get the highlighted results. The highlighted results and query results are open
                Map<String, Map<String, List<String>>> highlight = response.getHighlighting();
                for (SolrDocument result : results) {
                    Map<String, List<String>> map = highlight.get(result.get("id"));
                    result.setField("shopName", map.get("shopName").get(0));
                }
            }
            return new ResultData(results);
        } catch (Exception e) {
            log.error("Query failed:"+e.getMessage());
            return null;
        }
    }


    /**
     * Delete all indexes
     * @return
     */
    @RequestMapping("delAllShopSolr")
    public ResultData delAllShopSolr(){
        try {
            solrClient.deleteByQuery(solrDataName, "*:*");
            solrClient.commit(solrDataName);
        } catch (Exception e) {
            log.error("Delete failed:"+e.getMessage());
        }
        return new ResultData();
    }
}
5. Configure Chinese solr word breaker

download IKAnalyzer

  • Extract the downloaded package and copy the jar to solr-6.6.0 serversolr-webappwebappweb-inflib
  • Configure solrconfig.xml of solr-6.6.0 serversolrdisshopsconf under thesaurus, find the lib related tags, and add:
 <lib dir="./lib" regex=".*\.jar"/>
  • Configure managed schema and add word segmentation related configuration
  <fieldType name="text_ik" class="solr.TextField">
    <analyzer type="index" class="org.wltea.analyzer.lucene.IKAnalyzer"/>
    <analyzer type="query" class="org.wltea.analyzer.lucene.IKAnalyzer"/>
  </fieldType>

This article is based on the platform of blog one article multiple sending OpenWrite Release!

Posted by greg_soulsby on Tue, 05 Nov 2019 06:07:37 -0800