springboot整合solr

 

整合之前 先安装好solr 请参考:solr-7.7.2部署到tomcat8中详细步骤

创建一个springboot项目。

1.导入依赖(pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>solr</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>solr</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-solr</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.solr/solr-solrj -->
        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
            <version>7.7.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.添加配置(application.yml)

server:
  port: 8222

spring:
  application:
    name: solr
  data:
    solr:
     host: http://127.0.0.1:8080/solr/core2
  datasource:
    username: tanlei
    password: root
    url: jdbc:mysql://192.168.1.15:3306/dny_shop?characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapping/*Mapper.xml
  type-aliases-package: com.example.solr.entity

3.实体类(Mobile_choiceness)

package com.example.solr.entity;

import java.io.Serializable;

/**
 * 精选案例表
 */
public class Mobile_choiceness implements Serializable {
    private Integer chs_id;   //精选案例主键ID
    private String  release_time;   //发布时间
    private Integer viewed;   //浏览次数
    private String content;   //正文
    private Integer like_number;   //点赞数量
    private String chs_title;   //标题
    private String chs_author;   //作者
    private Integer status;   //状态(1:发布;2:未发布)
     
    //get set 方法省略
}

4.工具类

package com.example.solr.util;

import com.example.solr.entity.Mobile_choiceness;

import java.util.List;

public class SearchResult {
    //总条数
    private Long recordCount;
    //数据集合
    private List<Mobile_choiceness> itemList;
    //总页数
    private Integer pageCount;
    //当前页
    private Integer curPage;

    public Long getRecordCount() {
        return recordCount;
    }

    public void setRecordCount(Long recordCount) {
        this.recordCount = recordCount;
    }

    public List<Mobile_choiceness> getItemList() {
        return itemList;
    }

    public void setItemList(List<Mobile_choiceness> itemList) {
        this.itemList = itemList;
    }

    public Integer getPageCount() {
        return pageCount;
    }

    public void setPageCount(Integer pageCount) {
        this.pageCount = pageCount;
    }

    public Integer getCurPage() {
        return curPage;
    }

    public void setCurPage(Integer curPage) {
        this.curPage = curPage;
    }
}

5.sql (MobileChsMapper.xml)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.solr.dao.ChsDao">
    <select id="ChsList" resultType="com.example.solr.entity.Mobile_choiceness" parameterType="string">
        SELECT chs_id,release_time,viewed,content,like_number,chs_title,chs_author,status
        FROM mobile_choiceness
        where  status=1
    </select>
</mapper>

6.Dao接口(ChsDao)

package com.example.solr.dao;

import com.example.solr.entity.Mobile_choiceness;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface ChsDao {
    /**
     * 查询精选案例
     * @return
     */
    public List<Mobile_choiceness> ChsList(String chs_title,String release_time);
}

7.Service接口

package com.example.solr.service;
import com.example.solr.util.SearchResult;

public interface ChsService {
    /**
     * solr 条件查询
     * @param queryString 查询条件
     * @param page 页码
     * @param rows 页长
     * @return
     * @throws Exception
     */
    SearchResult searchItem(String queryString, Integer page, Integer rows) throws Exception;

    /**
     *
     * @return
     * @throws Exception
     */
    public String importItemToIndex() throws Exception;
}

8.Service实现类

package com.example.solr.service.Impl;

import com.example.solr.dao.ChsDao;
import com.example.solr.entity.Mobile_choiceness;
import com.example.solr.service.ChsService;
import com.example.solr.util.SearchResult;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
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.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ChsServiceImpl implements ChsService {
    @Autowired
    private ChsDao chsDao;

    @Autowired
    private SolrClient solrClient;

    /**
     * solr 条件查询
     * @param queryString 查询条件
     * @param page 页码
     * @param rows 页长
     * @return
     * @throws Exception
     */
    public SearchResult searchItem(String queryString, Integer page, Integer rows) throws Exception {
        //解决乱码
        //queryString = new String(queryString.getBytes("ISO8859-1"), "UTF-8");
        //创建一个查询对象
        SolrQuery solrQuery = new SolrQuery();
        System.out.println("索引条件:"+queryString);
        //查询条件
        if(queryString == null || queryString.equals("")){
            queryString = "*:*";
        }
        solrQuery.setQuery(queryString);

        //设置默认搜索域
        solrQuery.set("df", "ik_keywords");
        //分页条件
        if (page == null) {
            page = 0;
        }
        solrQuery.setStart(page);
        solrQuery.setRows(rows);
        //高亮显示
        /*
        solrQuery.set("hl",true);
        //设置高亮域(设置的域必须在查询条件中存在)
        solrQuery.set("h1.fl","chs_title");
        //前缀
        solrQuery.set("hl.simple.pre","<em style='color:red'>");
        //后缀
        solrQuery.set("hl.simple.post","</em>");*/

        solrQuery.setHighlight(true);
        //设置高亮显示的域
        solrQuery.addHighlightField("chs_title");
        //高亮显示前缀
        solrQuery.setHighlightSimplePre("<em style=\"color:red\">");
        //后缀
        solrQuery.setHighlightSimplePost("</em>");
        System.out.println("solrQuery:"+solrQuery);
        //执行查询
        SearchResult result = searchItemDao(solrQuery);
        //计算分页
        Long recordCount = result.getRecordCount();
        int pageCount = (int) (recordCount / rows);
        if (recordCount % rows > 0) {
            pageCount++;
        }
        result.setPageCount(pageCount);
        result.setCurPage(page);

        return result;
    }
    //执行查询
    public SearchResult searchItemDao(SolrQuery solrQuery) throws Exception {

        SearchResult searchResult = new SearchResult();
        List<Mobile_choiceness> itemList = new ArrayList<Mobile_choiceness>();
        //执行查询
        QueryResponse response = solrClient.query(solrQuery);
        System.out.println(response);
        //取查询结果
        SolrDocumentList solrDocumentList = response.getResults();
        //取查询结果总数量
        searchResult.setRecordCount(solrDocumentList.getNumFound());
        System.out.println("总记录数:"+solrDocumentList.getNumFound());

        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();

        for(SolrDocument sd: solrDocumentList) {
            Mobile_choiceness oe = new Mobile_choiceness();
            oe.setChs_id(Integer.valueOf(sd.get("id").toString()));
            //oe.setChs_title(sd.get("chs_title").toString());
            //取高亮显示
            List<String> list = highlighting.get(sd.get("id")).get("chs_title");
            String title = "";
            if (null != list && list.size()>0) {
                title = list.get(0);
            } else {
                title = sd.get("chs_title").toString();
            }
            oe.setChs_title(title);

            List<String> author_list=highlighting.get(sd.get("id")).get("chs_author");
            String author="";
            if (null != author_list && author_list.size()>0) {
                author = author_list.get(0);
            } else {
                author = sd.get("chs_author").toString();
            }
            oe.setChs_author(author);

            List<String> content_list=highlighting.get(sd.get("id")).get("content");
            String content="";
            if (null != content_list && content_list.size()>0) {
                content = content_list.get(0);
            } else {
                content = sd.get("content").toString();
            }
            oe.setContent(content);
            oe.setLike_number(Integer.valueOf(sd.get("like_number").toString()));
            oe.setRelease_time(sd.get("release_time").toString());
            oe.setStatus(Integer.valueOf(sd.get("status").toString()));
            oe.setViewed(Integer.valueOf(sd.get("viewed").toString()));
            itemList.add(oe);
        }
        searchResult.setItemList(itemList);
        return searchResult;
    }

    //将所有数据导入到solr中
    public String importItemToIndex() throws Exception {
        //查询列表
        List<Mobile_choiceness> itemList = chsDao.ChsList(null,null);
        //将列表导入solr
        for (Mobile_choiceness item : itemList) {
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", item.getChs_id());
            document.addField("release_time", item.getRelease_time());
            document.addField("viewed", item.getViewed());
            document.addField("content", item.getContent());
            document.addField("like_number", item.getLike_number());
            document.addField("chs_title", item.getChs_title());
            document.addField("chs_author", item.getChs_author());
            document.addField("status", item.getStatus());
            //将文档写入索引库
            solrClient.add(document);
        }
        //提交修改
        solrClient.commit();
        return "success";
    }
}

9.Controller

package com.example.solr.controller;

import com.example.solr.service.ChsService;
import com.example.solr.util.SearchResult;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class SolrController {
    @Autowired
    ChsService chsService;
    @Autowired
    private SolrClient solrClient;

    //高亮查询 ,访问路径: localhost:8769/query?q=发
    @RequestMapping("/query")
    public SearchResult search(@RequestParam(value = "q") String queryString,
                               @RequestParam(value = "page", defaultValue = "0") Integer page, @RequestParam(value = "rows", defaultValue = "60") Integer rows) throws Exception {
        return chsService.searchItem(queryString, page, rows);
    }

    //添加数据到solr
    @RequestMapping("/add")
    public String addSolr() throws Exception {
        return chsService.importItemToIndex();
    }
    /***
     * 清空所有数据
     */
    @RequestMapping("/deleteall")
    public String DeleteAll() throws Exception {
        // 清空所有数据
        solrClient.deleteByQuery("*:*");
        solrClient.commit();
        return "solr所有数据已清除";
    }

    /**
     * 新增/修改 索引
     * 当 id 存在的时候, 此方法是修改(当然, 我这里用的 uuid, 不会存在的), 如果 id 不存在, 则是新增
     * @return
     */
    @RequestMapping("/update")
    public String update() {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        try {
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", 1);
            document.addField("release_time", "2019-09-27 17:28:10");
            document.addField("viewed", 10000);
            document.addField("content", "solr修改测试!");
            document.addField("like_number",8888);
            document.addField("chs_title", "solr修改测试!");
            document.addField("chs_author", "solr");
            document.addField("status", 1);
            /* 如果spring.data.solr.host 里面配置到 core了, 那么这里就不需要传 collection1 这个参数
             * 下面都是一样的
             */
            solrClient.add(document);
            //solrClient.commit("collection1");
            solrClient.commit();
            return "修改成功!";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }
    /**
     * 根据id删除索引
     * @param id
     * @return
     */
    @RequestMapping("/deleteID")
    public String delete(String  id)  {
        try {
            solrClient.deleteById(id);
            solrClient.commit();
            return id+"删除成功!";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }
}

源码:https://github.com/kelly921011/solr

写的小测试 代码比较凌乱  请见谅! 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值