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

简介: Spring整合solr实现文章的添加与搜索

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标签,再保存到索引中。


目录
相关文章
|
6月前
|
Java 应用服务中间件 Spring
Spring系列文章:Bean的作⽤域
Spring系列文章:Bean的作⽤域
|
6月前
|
Java Spring 容器
Spring系列文章:Bean的获取⽅式
Spring系列文章:Bean的获取⽅式
|
6月前
|
Java Spring 容器
Spring系列文章:Spring6集成MyBatis3.5
Spring系列文章:Spring6集成MyBatis3.5
|
6月前
|
XML Java 数据格式
Spring系列文章2:基于xml方式依赖注入
Spring系列文章2:基于xml方式依赖注入
|
5月前
|
XML Java 数据格式
Spring5系列学习文章分享---第一篇(概述+特点+IOC原理+IOC并操作之bean的XML管理操作)
Spring5系列学习文章分享---第一篇(概述+特点+IOC原理+IOC并操作之bean的XML管理操作)
46 1
|
5月前
|
XML druid Java
Spring5系列学习文章分享---第二篇(IOC的bean管理factory+Bean作用域与生命周期+自动装配+基于注解管理+外部属性管理之druid)
Spring5系列学习文章分享---第二篇(IOC的bean管理factory+Bean作用域与生命周期+自动装配+基于注解管理+外部属性管理之druid)
62 0
|
6月前
|
前端开发 Java 数据库连接
Spring系列文章1:Spring入门程序
Spring系列文章1:Spring入门程序
|
4月前
|
Java Apache Spring
整合Spring Boot和Apache Solr进行全文搜索
整合Spring Boot和Apache Solr进行全文搜索
|
5月前
|
Java Spring 容器
Spring5系列学习文章分享---第六篇(框架新功能系列+整合日志+ @Nullable注解 + JUnit5整合)
Spring5系列学习文章分享---第六篇(框架新功能系列+整合日志+ @Nullable注解 + JUnit5整合)
37 0
|
5月前
|
XML Java 数据库
Spring5系列学习文章分享---第五篇(事务概念+特性+案例+注解声明式事务管理+参数详解 )
Spring5系列学习文章分享---第五篇(事务概念+特性+案例+注解声明式事务管理+参数详解 )
30 0