美文网首页
第六课 Spring整合solr实现文章的添加与搜索

第六课 Spring整合solr实现文章的添加与搜索

作者: Arroganter | 来源:发表于2018-08-27 08:38 被阅读40次

    maven里添加依赖
    <dependency>
    <groupId>org.apache.solr</groupId>
    <artifactId>solr-solrj</artifactId>
    <version>4.10.2</version>
    </dependency>
    <dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
    </dependency>
    spring配置文件里添加
    <bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
    <constructor-arg index="0" value="http://192.168.25.128:8080/solr/collection1"/>
    </bean>
    添加文章
    Contoller或service里添加

    @Autowired
    private SolrServer solrServer;
    

    public int addArticle(Article article) {
    int result = articleMapper.addArticle(article);

        SolrInputDocument inputDocument = new SolrInputDocument();
        //向文档中添加域以及对应的值,注意:所有的域必须在schema.xml中定义过,前面已经给出过我定义的域。
        UUID uuid = UUID.randomUUID();
        inputDocument.addField("id", uuid);
        inputDocument.addField("article_title", article.getTitle());
        inputDocument.addField("article_content", article.getContent());
        inputDocument.addField("article_id", article.getAid());
        try {
            solrServer.add(inputDocument);
            solrServer.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    

    检索文章
    public List<Article> queryArticles(String keyword,SolrQueryPageInfo solrQueryPageInfo) {

        List<Article> articleList = new ArrayList<>();
    
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.set("q",keyword);
        solrQuery.set("df","article_keywords");//df=>default field
        solrQuery.setSort("id", SolrQuery.ORDER.asc);
    
        solrQuery.setStart(solrQueryPageInfo.getPageIndex()*solrQueryPageInfo.getPageSize());
        solrQuery.setRows(solrQueryPageInfo.getPageSize());
    
        //开启高亮显示
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("article_title");
        solrQuery.addHighlightField("article_content");
        solrQuery.setHighlightSimplePre("<em>");
        solrQuery.setHighlightSimplePost("</em>");
    
        QueryResponse queryResponse = null;
        try {
            queryResponse = solrServer.query(solrQuery);
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        SolrDocumentList solrDocumentList = queryResponse.getResults();
        int total = (int) solrDocumentList.getNumFound();
        solrQueryPageInfo.setTotal(total);
        Map<String, Map<String, List<String>>> mapMapHighlighting = queryResponse.getHighlighting();
    
        for(SolrDocument solrDocument : solrDocumentList)
        {
            Article article = new Article();
            String id = (String)solrDocument.get("id");
            String article_title = (String)solrDocument.get("article_title");
            String article_content = (String)solrDocument.get("article_content");
            Long article_id = (Long)solrDocument.get("article_id");
            article.setTitle(article_title);
            article.setContent(article_content);
            article.setAid(article_id.intValue());
            Map<String, List<String>> map = mapMapHighlighting.get(id);//一个商品,一个json对象
    
            for(Map.Entry<String, List<String>> entry : map.entrySet())
            {
                if(entry.getKey().equals("article_title"))
                {
                    article.setTitle(entry.getValue().get(0));
                }
                if(entry.getKey().equals("article_content"))
                {
                    article.setContent(entry.getValue().get(0));
                }
    
            }
    
            articleList.add(article);
    
        }
    
        return articleList;
    }
    

    Controller里调用

    @RequestMapping("query")
    public void queryArticles(String keyword, Model model, SolrQueryPageInfo solrQueryPageInfo, HttpServletResponse response) throws IOException {
    response.setContentType("text/html;charset=utf-8");

        ArticlePageInfo articlePageInfo = new ArticlePageInfo();
        List<Article> articleList = articleService.queryArticles(keyword,solrQueryPageInfo);
        articlePageInfo.setTotal(solrQueryPageInfo.getTotal());
        articlePageInfo.setArticles(articleList);
    
        String jsonString = JSON.toJSONString(articlePageInfo);
        response.getWriter().println(jsonString);
    }
    

    ArticlePageInfo
    public class ArticlePageInfo {
    int total;
    List<Article> articles;

    public int getTotal() {
        return total;
    }
    
    public void setTotal(int total) {
        this.total = total;
    }
    
    public List<Article> getArticles() {
        return articles;
    }
    
    public void setArticles(List<Article> articles) {
        this.articles = articles;
    }
    

    }
    SolrQueryPageInfo
    public class SolrQueryPageInfo {
    int pageIndex;
    int pageSize;
    int total;

    public int getPageIndex() {
        return pageIndex;
    }
    
    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }
    
    public int getPageSize() {
        return pageSize;
    }
    
    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }
    
    public int getTotal() {
        return total;
    }
    
    public void setTotal(int total) {
        this.total = total;
    }
    

    }
    index_query.jsp
    <%--
    Created by IntelliJ IDEA.
    User: ttc
    Date: 2018/7/6
    Time: 14:06
    To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <head>
    <title>Title</title>
    <style>

      ul{
        list-style: none;
      }
    
      em{
        color:red;
        font-style: normal;
      }
    
    </style>
    <link href="${pageContext.request.contextPath}/thirdpart/page/mricode.pagination.css" rel="stylesheet">
    <script src="${pageContext.request.contextPath}/thirdpart/page/jquery2.1.4.min.js"></script>
    <script src="${pageContext.request.contextPath}/thirdpart/page/mricode.pagination.js"></script>
    <script src="${pageContext.request.contextPath}/thirdpart/page/arttemplate.min.js"></script>
    
    <script>
        window.onload = function () {
    
            $('#btn').click(function () {
                var page = $("#page");
                page.pagination({
                    pageIndex: 0,
                    pageSize: 2,
                    showInfo: true,
                    showJump: true,
                    showPageSizes: true,
                    remote:{
                        url:' ${pageContext.request.contextPath}/article/query',
                        params: $('form').serializeArray(),
                        success:function (data) {
    
                            var html = template('test',data);
                            document.getElementById('content').innerHTML = html;
                        }
                    }
                });//json 对象
            })
    
        }
    </script>
    

    </head>
    <body>

    <form action="#">
      <input type="text" name="keyword">
      <input type="button" value="搜索" id="btn">
    </form>
    
    <div id="content">
    
    </div>
    <div id="page" class="m-pagination"></div>
    

    </body>

    <script id="test" type="text/html">
    <ul class="artilce-list">

        {{each articles as article}}
        <li>
          <div><a href="${pageContext.request.contextPath}/article/view_article/{{article.aid}}">{{#article.title}}</a></div>
          <div>{{#article.content}}</div>
        </li>
      {{/each}}
    </ul>
    

    </script>
    </html>

    可能的问题
    如果想向solr添加带html标签的文本,可以使用jsoup选中元素,调用text()方法脱去全部的html标签,再保存到索引中。

    谢谢

    相关文章

      网友评论

          本文标题:第六课 Spring整合solr实现文章的添加与搜索

          本文链接:https://www.haomeiwen.com/subject/pdqliftx.html