zoukankan      html  css  js  c++  java
  • Solr的安装和使用

    安装

    CentOS中先安装好Java和Tomcat。准备工具IK Analyzer 2012FF

    和Solr-4.10.3.tgz

    将solr-4.10.3文件夹中dist中的solr-4.10.3.war文件复制到Tomcat的webapps,并且更名为solr.war,下开启tomcat解压后再关闭tomcat,再删除solr.war。

    将Solr-4.10.3文件中,example/lib/ext下所有jar包复制到tomcat/webapps/solr/WEB-INF/lib文件夹下。

    在你愿意的位置创建一个目录叫solrhome,把Solr-4.10.3 /example下solr复制到 solrhome中,然后在solr的WEB-INF下的web.xml中配置solrhome的位置。

        <env-entry>
           <env-entry-name>solr/home</env-entry-name>
           <env-entry-value>/usr/local/solr/solrhome</env-entry-value>
           <env-entry-type>java.lang.String</env-entry-type>
        </env-entry>

    配置业务字段

    把IK_Analyzer 2012文件夹下的IKAnalyzer2012FF_u1的jar包复制到solr 的WEB-INF下lib文件夹中。

    在WEB-INF下新建classes文件夹。复制如下三个文件到classes中

    cp IKAnalyzer.cfg.xml ext_stopword.dic mydict.dic /usr/local/solr/tomcat/webapps/solr/WEB-INF/classes

    修改solrhome/collection1/conf/schema.xml文件,在末尾添加

    <fieldType name="text_ik" class="solr.TextField">
      <analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/>
    </fieldType>
    <field name="item_title" type="text_ik" indexed="true" stored="true"/>
    <field name="item_sell_point" type="text_ik" indexed="true" stored="true"/>
    <field name="item_price"  type="long" indexed="true" stored="true"/>
    <field name="item_image" type="string" indexed="false" stored="true" />
    <field name="item_category_name" type="string" indexed="true" stored="true" />
    <field name="item_desc" type="text_ik" indexed="true" stored="false" />
    
    <field name="item_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/>
    <copyField source="item_title" dest="item_keywords"/>
    <copyField source="item_sell_point" dest="item_keywords"/>
    <copyField source="item_category_name" dest="item_keywords"/>
    <copyField source="item_desc" dest="item_keywords"/>

    重启tomcat

    简单测试

    打开solr网址,http://192.168.140.133:8080/solr/,点击左侧collection1,选择Documents

    在documents中输入

    点击Submit Document

     点击Collection1下的Query,点击Execute Query

     

    删除该测试文档,

    在Documents输入

    <delete>
    <query>*:*</query>
    </delete>
    <commit/>

    Document Type选择xml,然后Submmit Document。

    再Execute Query就没有文档了。

      },
      "response": {
        "numFound": 0,
        "start": 0,
        "docs": []
      }
    }

     使用Java代码来测试solr文档

    添加SolrJava客户端依赖

    <!-- solr客户端 -->
            <dependency>
                <groupId>org.apache.solr</groupId>
                <artifactId>solr-solrj</artifactId>
            </dependency>

    测试代码

    public class SolrJTest {
    
        @Test
        public void addDocument() throws Exception {
            //创建一连接
            SolrServer solrServer = new HttpSolrServer("http://192.168.25.154:8080/solr");
            //创建一个文档对象
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", "test001");
            document.addField("item_title", "测试商品2");
            document.addField("item_price", 54321);
            //把文档对象写入索引库
            solrServer.add(document);
            //提交
            solrServer.commit();
        }
        
        @Test
        public void deleteDocument() throws Exception {
            //创建一连接
            SolrServer solrServer = new HttpSolrServer("http://192.168.25.154:8080/solr");
            //solrServer.deleteById("test001");
            solrServer.deleteByQuery("*:*");
            solrServer.commit();
        }
    }

    使用Java代码将MySQL数据上传到Solr服务器

    使用Http方式,访问http://localhost/search/import的时候,将后台MySQL几个表的数据上传到Solr服务器。

    先看Controller

    @Controller
    public class SearchController {
        @Autowired
        private ImportItemService importItemService;
    
        @RequestMapping("/search/import")
        @ResponseBody
        public TaotaoResult importAll() {
            TaotaoResult result = importItemService.importAll();
            return result;
        }

    Service层总ImportItemService的实现类是

    @Service
    public class ImportItemServiceImpl implements ImportItemService {
        @Autowired
        private ImportItemMapper iim;
        @Autowired
        private SolrServer solrServer;
        @Override
        public TaotaoResult importAll(){
            try {
                List<ImportItem> list = iim.importItemList();
                for(ImportItem item:list) {
                    SolrInputDocument document= new SolrInputDocument();
                    document.setField("id", item.getId());
                    document.setField("item_title", item.getTitle());
                    document.setField("item_sell_point", item.getSell_point());
                    document.setField("item_price", item.getPrice());
                    document.setField("item_image", item.getImage());
                    document.setField("item_category_name", item.getCategory_name());
                    document.setField("item_desc", item.getItem_des());
                    //写入索引库
                    solrServer.add(document);
                }
                solrServer.commit();
            } catch (Exception e) {
                e.printStackTrace();
                return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
            }
            return TaotaoResult.ok();
        }
    
    }

    其中ImportItem类

    public class ImportItem {
    //getter and setter...
    ...
        private String id;
        private String title;
        private String sell_point;
        private long price;
        private String image;
        private String category_name;
        private String item_des;
    
    }

    DAO 层

    public interface ImportItemMapper {
        List<ImportItem> importItemList();
    }

    对应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.taotao.mapper.ImportItemMapper" >
        
        <select id="importItemList" resultType="com.taotao.pojo.ImportItem">
            SELECT
                a.id,
                a.title,
                a.sell_point,
                a.price,
                a.image,
                b. NAME category_name
            FROM
                tb_item a
            LEFT JOIN tb_item_cat b ON a.cid = b.id
        </select>
    
    </mapper>

     搜索服务发布

    预热:先了解SolrJ如何访问solr服务器。

    测试代码

    @Test
        public void queryDocument() throws Exception {
            SolrServer solrServer = new HttpSolrServer("http://192.168.25.154:8080/solr");
            //创建一个查询对象
            SolrQuery query = new SolrQuery();
            //设置查询条件
            query.setQuery("*:*");
            query.setStart(20);
            query.setRows(50);
            //执行查询
            QueryResponse response = solrServer.query(query);
            //取查询结果
            SolrDocumentList solrDocumentList = response.getResults();
            System.out.println("共查询到记录:" + solrDocumentList.getNumFound());
            for (SolrDocument solrDocument : solrDocumentList) {
                System.out.println(solrDocument.get("id"));
                System.out.println(solrDocument.get("item_title"));
                System.out.println(solrDocument.get("item_price"));
                System.out.println(solrDocument.get("item_image"));
                
            }
        }

    DAO层

    public interface SearchDao {
        SearchResult search(SolrQuery query)throws Exception;
    }
    @Component
    public class SearchDaoImpl implements SearchDao {
    
        @Autowired
        private SolrServer solrServer;
    
        @Override
        public SearchResult search(SolrQuery query) throws Exception {
            //返回值对象
            SearchResult result = new SearchResult();
            //根据查询条件查询索引库
            QueryResponse queryResponse = solrServer.query(query);
            //取查询结果
            SolrDocumentList solrDocumentList = queryResponse.getResults();
            //取查询结果总数量
            result.setRecordCount(solrDocumentList.getNumFound());
            //商品列表
            List<ImportItem> itemList = new ArrayList<>();
            //取高亮显示
            Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
            //取商品列表
            for (SolrDocument solrDocument : solrDocumentList) {
                //创建一商品对象
                ImportItem item = new ImportItem();
                item.setId((String) solrDocument.get("id"));
                //取高亮显示的结果
                List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
                String title = "";
                if (list != null && list.size()>0) {
                    title = list.get(0);
                } else {
                    title = (String) solrDocument.get("item_title");
                }
                item.setTitle(title);
                item.setImage((String) solrDocument.get("item_image"));
                item.setPrice((long) solrDocument.get("item_price"));
                item.setSell_point((String) solrDocument.get("item_sell_point"));
                item.setCategory_name((String) solrDocument.get("item_category_name"));
                //添加的商品列表
                itemList.add(item);
            }
            result.setItemList(itemList);
            return result;
        }

    POJO类

    public class SearchResult {
        //商品列表
        private List<ImportItem> itemList;
        //总记录数
        private long recordCount;
        //总页数
        private long pageCount;
        //当前页
        private long curPage;}

    Service层

    public interface SearchService {
        SearchResult search(String query,int page,int rows)throws Exception;
    }
    
    
    @Service
    public class SearchServiceImpl implements SearchService {
    
        @Autowired
        private SearchDao searchDao;
        @Override
        public SearchResult search(String queryString, int page, int rows) throws Exception {
            //创建查询对象
            SolrQuery query = new SolrQuery();
            //设置查询条件
            query.setQuery(queryString);
            //设置分页
            query.setStart((page - 1) * rows);
            query.setRows(rows);
            //设置默认搜素域
            query.set("df", "item_keywords");
            //设置高亮显示
            query.setHighlight(true);
            query.addHighlightField("item_title");
            query.setHighlightSimplePre("<em style="color:red">");
            query.setHighlightSimplePost("</em>");
            //执行查询
            SearchResult searchResult = searchDao.search(query);
            //计算查询结果总页数
            long recordCount = searchResult.getRecordCount();
            long pageCount = recordCount / rows;
            if (recordCount % rows > 0) {
                pageCount++;
            }
            searchResult.setPageCount(pageCount);
            searchResult.setCurPage(page);
            
            return searchResult;
        }
    
    }

    Controller层

    @Autowired
        private SearchService searchService;
        
        @RequestMapping(value="/query", method=RequestMethod.GET)
        @ResponseBody
        public TaotaoResult search(@RequestParam("q")String queryString, 
                @RequestParam(defaultValue="1")Integer page, 
                @RequestParam(defaultValue="60")Integer rows) {
            //查询条件不能为空
            if (StringUtils.isBlank(queryString)) {
                return TaotaoResult.build(400, "查询条件不能为空");
            }
            SearchResult searchResult = null;
            try {
                queryString=new String(queryString.getBytes("iso8859-1"),"utf-8");
                searchResult = searchService.search(queryString, page, rows);
            } catch (Exception e) {
                e.printStackTrace();
                return TaotaoResult.build(500, ExceptionUtil.getStackTrace(e));
            }
            return TaotaoResult.ok(searchResult);
            
        }
  • 相关阅读:
    Android开发--Layout元素
    Android开发--RelativeLayout的应用
    group by调优的一些测试
    mysql explain中key_len的计算
    mysql索引长度的一些限制
    order by调优的一些测试
    metadata lock
    JDBC连接数据库
    Java—Map.Entry
    innodb buffer pool
  • 原文地址:https://www.cnblogs.com/legion/p/9717724.html
Copyright © 2011-2022 走看看