目录

一、solr的大概认识

(1)在互联网项目里面,绝大部分是用全文检索服务器,

lucense(基于java的全文检索api)和solr(基于lucense的全文检索服务器)都可以实现。用lucense需要自己来管理维护索引库,进行索引库的优化,缓存的添加。而solr配置一下就好了,比较方便。

(2)solr本质上是一个war包,然后部署到servlet容器中,容器你可以选择用tomcat,也可以选择更加轻量级的jetty

(3)反正solr就是:比如 好多好多商品,每个都好长名字。那我比如搜索 '漂亮手机' 的时候,solr自动划分字段(比如划分成 ‘漂亮’,‘手机’),自动去匹配数据库中对应的商品名列表,商品名列表也会被划分,完全匹配的就会展示出来

(4)solr使用的时候分两部分:把商品名列表放到solr;搜索商品

二、solr安装

(1)安装jdk(省略)

(2)下载 solr-4.10.3.tgz.tgz并解压

链接:https://pan.baidu.com/s/1G6-aLXboFKThzRiDtUV-Xg

提取码:0j9o

(3)安装tomcat(省略)

(4)拷贝solr的war包到tomcat下

  1. [root@localhost apache-tomcat-7.0.47]# cp /usr/solr/solr-4.10.3/dist/solr-4.10.3.war webapps/solr.war

(5)启动tomcat自动解压缩war包:

  1. [root@localhost apache-tomcat-7.0.47]# bin/startup.sh

(6)查看控制台,检查tomcat启动情况:

  1. [root@localhost apache-tomcat-7.0.47]# tail -f logs/catalina.out

(7)关闭tomcat

  1. [root@localhost apache-tomcat-7.0.47]# bin/shutdown.sh

(8)删除war包

  1. [root@localhost apache-tomcat-7.0.47]# rm -f webapps/solr.war

(9)把一些jar包放到solr工程下面去:

  1. [root@localhost apache-tomcat-7.0.47]# cp /usr/solr/solr-4.10.3/example/lib/ext/* webapps/solr/WEB-INF/lib/

(10)配置solrhome

  1. [root@localhost solr-4.10.3]# cp -r example/solr /usr/solr/solrhome
  2. [root@localhost apache-tomcat-7.0.47]# cd webapps/solr/WEB-INF/
  3. [root@localhost WEB-INF]# vim web.xml

修改solr/home的地址,并且去掉注释

(11)再次开启tomcat

  1. [root@localhost apache-tomcat-7.0.47]# bin/startup.sh

(12)在Windows那边访问solr

http://192.168.25.128:8080/solr/

三、solr的深度认识

用户可以通过http请求,向搜索引擎服务器提交一定格式的XML文件或数据,生成索引;也可以通过Http Get操作提出查找请求,并得到XML格式的返回结果。

四、solr的使用

(1)由于我们用到中文,所以需要中文分析器,这里我用IK Analyzer 2012FF_hf1

链接:https://pan.baidu.com/s/15TUJaTJir9d0A0FRaiBl_A

提取码:5xrw

下载好IK Analyzer 2012FF_hf1文件后,安装步骤:

<1>拷贝IKAnalyzer2012FF_u1.jar到tomcat的solr项目下的lib中:

  1. [root@localhost apache-tomcat-7.0.47]# cd webapps/solr/WEB-INF/lib
  2. [root@localhost lib]# cp /usr/solr/IK_Analyzer_2012FF_hf1/IKAnalyzer2012FF_u1.jar .

<2>拷贝三个文件到tomcat的solr项目下的classes文件中

  1. [root@localhost lib]# cd ..
  2. [root@localhost WEB-INF]# mkdir classes
  3. [root@localhost IK_Analyzer_2012FF_hf1]# cp ext_stopword.dic IKAnalyzer.cfg.xml mydict.dic /usr/tomcat/apache-tomcat-7.0.47/webapps/solr/WEB-INF/classes

<3>在solrhome里面的schema.xml定义一个fieldtype,来指定IK分析器。

  1. <fieldType name="text_ik" class="solr.TextField">
  2. <analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/>
  3. </fieldType>

(2)同时在schema.xml指定好业务域 field name......

由于solr本身就定义了id,所以我们用solr的id来保存我们要的id就可以了。

注意:string类型的是不可拆分的,而TextField类型的是可拆分的

  1. <field name="item_title" type="text_ik" indexed="true" stored="true"/>
  2. <field name="item_sell_point" type="text_ik" indexed="true" stored="true"/>
  3. <field name="item_price" type="long" indexed="true" stored="true"/>
  4. <field name="item_image" type="string" indexed="false" stored="true" />
  5. <field name="item_category_name" type="string" indexed="true" stored="true" />
  6. <field name="item_desc" type="text_ik" indexed="true" stored="false" />

(3)同时在schema.xml配置复制域

就是说你找一个商品的时候,可以在item_keywords中的四个域中找

  1. <field name="item_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/>
  2. <copyField source="item_title" dest="item_keywords"/>
  3. <copyField source="item_sell_point" dest="item_keywords"/>
  4. <copyField source="item_category_name" dest="item_keywords"/>
  5. <copyField source="item_desc" dest="item_keywords"/>

(4)启动solr看看业务域是否能用

  1. [root@localhost apache-tomcat-7.0.47]# bin/startup.sh

进入http://192.168.25.128:8080/solr/里面的collection1的Analyse ,选择一个域,比如:

五、用java代码增删data到solr中

(1)导包

  1. <!-- 添加solrJ的依赖 -->
  2. <dependency>
  3. <groupId>org.apache.solr</groupId>
  4. <artifactId>solr-solrj</artifactId>
  5. </dependency>

(2)测试一下

  1. import org.apache.solr.client.solrj.SolrServer;
  2. import org.apache.solr.client.solrj.impl.HttpSolrServer;
  3. import org.apache.solr.client.solrj.response.QueryResponse;
  4. import org.apache.solr.common.SolrDocument;
  5. import org.apache.solr.common.SolrDocumentList;
  6. import org.apache.solr.common.SolrInputDocument;
  7. import org.junit.Test;
  8. public class TestSolrJ {
  9. @Test
  10. public void testAddDocument() throws Exception {
  11. //创建一个SolrServer对象。创建一个HttpSolrServer对象
  12. //需要指定solr服务的url
  13. SolrServer solrServer = new HttpSolrServer("http://192.168.25.128:8080/solr/collection1");
  14. //创建一个文档对象SolrInputDocument
  15. SolrInputDocument document = new SolrInputDocument();
  16. //向文档中添加域,必须有id域,域的名称必须在schema.xml中定义
  17. document.addField("id", "1234");
  18. document.addField("item_title", "测试商品2");
  19. document.addField("item_price", 1000);
  20. //把文档对象写入索引库
  21. solrServer.add(document);
  22. //提交
  23. solrServer.commit();
  24. }
  25. @Test
  26. public void deleteDocumentById() throws Exception {
  27. SolrServer solrServer = new HttpSolrServer("http://192.168.25.128:8080/solr/collection1");
  28. solrServer.deleteById("123");
  29. //提交
  30. solrServer.commit();
  31. }
  32. @Test
  33. public void deleteDocumentByQuery() throws Exception {
  34. SolrServer solrServer = new HttpSolrServer("http://192.168.25.128:8080/solr/collection1");
  35. solrServer.deleteByQuery("item_title:测试商品3");
  36. solrServer.commit();
  37. }
  38. }

六、实际开发中导入数据库数据到solr的data中的步骤

<1>定义一个 (将数据库的部分数据导入到solr的data中的)接口

  1. import com.wine.common.pojo.WineResult;
  2. public interface SearchItemService {
  3. WineResult importItemsToIndex();
  4. }

<2>实现上方接口

  1. @Service
  2. public class SearchItemServiceImpl implements SearchItemService {
  3. @Autowired
  4. private SearchItemMapper searchItemMapper;
  5. @Autowired
  6. private SolrServer solrServer;
  7. @Override
  8. public WineResult importItemsToIndex() {
  9. try {
  10. //1、先查询所有商品数据
  11. List<SearchItem> itemList = searchItemMapper.getItemList();
  12. //2、遍历商品数据添加到索引库
  13. for (SearchItem searchItem : itemList) {
  14. //创建文档对象
  15. SolrInputDocument document = new SolrInputDocument();
  16. //向文档中添加域
  17. document.addField("id", searchItem.getId());
  18. document.addField("item_title", searchItem.getTitle());
  19. document.addField("item_sell_point", searchItem.getSell_point());
  20. document.addField("item_price", searchItem.getPrice());
  21. document.addField("item_image", searchItem.getImage());
  22. document.addField("item_category_name", searchItem.getCategory_name());
  23. document.addField("item_desc", searchItem.getItem_desc());
  24. //把文档写入索引库
  25. solrServer.add(document);
  26. }
  27. //3、提交
  28. solrServer.commit();
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. return WineResult.build(500, "数据导入失败");
  32. }
  33. //4、返回添加成功
  34. return WineResult.ok();
  35. }
  36. }

<3>solr连接文件applicationContext-solr.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
  8. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
  9. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
  10. <!-- 单机版solr的连接 -->
  11. <bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
  12. <constructor-arg name="baseURL" value="http://192.168.25.128:8080/solr/collection1"/>
  13. </bean>
  14. <!-- 集群版solr连接 -->
  15. <!-- <bean id="cloudSolrServer" class="org.apache.solr.client.solrj.impl.CloudSolrServer">
  16. <constructor-arg name="zkHost" value="192.168.25.128:2181,192.168.25.128:2182,192.168.25.128:2183"></constructor-arg>
  17. <property name="defaultCollection" value="collection2"/>
  18. </bean> -->
  19. </beans>

七、实际开发中实现搜索功能步骤

(1)首先测试一下,输入测试商品,看看搜索出什么东西:

  1. @Test
  2. public void searchDocumet() throws Exception {
  3. //创建一个SolrServer对象
  4. SolrServer solrServer = new HttpSolrServer("http://192.168.25.128:8080/solr/collection1");
  5. //创建一个SolrQuery对象
  6. SolrQuery query = new SolrQuery();
  7. //设置查询条件、过滤条件、分页条件、排序条件、高亮
  8. //query.set("q", "*:*");
  9. query.setQuery("测试商品");
  10. //分页条件
  11. query.setStart(0);
  12. query.setRows(10);
  13. //设置默认搜索域
  14. query.set("df", "item_keywords");
  15. //设置高亮
  16. query.setHighlight(true);
  17. //高亮显示的域
  18. query.addHighlightField("item_title");
  19. query.setHighlightSimplePre("<div>");
  20. query.setHighlightSimplePost("</div>");
  21. //执行查询,得到一个Response对象
  22. QueryResponse response = solrServer.query(query);
  23. //取查询结果
  24. SolrDocumentList solrDocumentList = response.getResults();
  25. //取查询结果总记录数
  26. System.out.println("查询结果总记录数:" + solrDocumentList.getNumFound());
  27. for (SolrDocument solrDocument : solrDocumentList) {
  28. System.out.println(solrDocument.get("id"));
  29. //取高亮显示
  30. Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
  31. List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
  32. String itemTitle = "";
  33. if (list != null && list.size() >0) {
  34. itemTitle = list.get(0);
  35. } else {
  36. itemTitle = (String) solrDocument.get("item_title");
  37. }
  38. System.out.println(itemTitle);
  39. System.out.println(solrDocument.get("item_sell_point"));
  40. System.out.println(solrDocument.get("item_price"));
  41. System.out.println(solrDocument.get("item_image"));
  42. System.out.println(solrDocument.get("item_category_name"));
  43. System.out.println("=============================================");
  44. }
  45. }

结果:(注意:sol按照匹配次数多的来排序)

我已经在solor中插入了数据(id,title,....):(123456, 测试商品2,...),(1,测试2商品,...),(2,2商品测试,...),(,7,66测试66商品,...),(5,2测试,...),(6,2商品,...)

  1. 查询结果总记录数:6
  2. 123456
  3. <div>测试</div><div>商品</div>2
  4. null
  5. 1000
  6. null
  7. null
  8. =============================================
  9. 1
  10. <div>测试</div>2<div>商品</div>
  11. null
  12. 1000
  13. null
  14. null
  15. =============================================
  16. 2
  17. 2<div>商品</div><div>测试</div>
  18. null
  19. 1000
  20. null
  21. null
  22. =============================================
  23. 7
  24. 66<div>测试</div>66<div>商品</div>
  25. null
  26. 1000
  27. null
  28. null
  29. =============================================
  30. 5
  31. 2<div>测试</div>
  32. null
  33. 1000
  34. null
  35. null
  36. =============================================
  37. 6
  38. 2<div>商品</div>
  39. null
  40. 1000
  41. null
  42. null
  43. =============================================

(2)具体代码实现

<1>添加一个访问solr的dao:

  1. /**
  2. * 查询索引库商品dao
  3. */
  4. @Repository
  5. public class SearchDao {
  6. @Autowired
  7. private SolrServer solrServer;
  8. /**
  9. SearchResult 这个pojo类里面的数据:
  10. private long totalPages;
  11. private long recordCount;
  12. private List<SearchItem> itemList;
  13. **/
  14. public SearchResult search(SolrQuery query) throws Exception{
  15. //根据query对象进行查询
  16. QueryResponse response = solrServer.query(query);
  17. //取查询结果
  18. SolrDocumentList solrDocumentList = response.getResults();
  19. //取查询结果总记录数
  20. long numFound = solrDocumentList.getNumFound();
  21. SearchResult result = new SearchResult();
  22. result.setRecordCount(numFound);
  23. List<SearchItem> itemList = new ArrayList<>();
  24. //把查询结果封装到SearchItem对象中
  25. for (SolrDocument solrDocument : solrDocumentList) {
  26. SearchItem item = new SearchItem();
  27. item.setCategory_name((String) solrDocument.get("item_category_name"));
  28. item.setId((String) solrDocument.get("id"));
  29. //取一张图片
  30. String image = (String) solrDocument.get("item_image");
  31. if (StringUtils.isNotBlank(image)) {
  32. image = image.split(",")[0];
  33. }
  34. item.setImage(image);
  35. item.setPrice((long) solrDocument.get("item_price"));
  36. item.setSell_point((String) solrDocument.get("item_sell_point"));
  37. //取高亮显示
  38. Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
  39. List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
  40. String title = "";
  41. if (list != null && list.size() > 0) {
  42. title = list.get(0);
  43. } else {
  44. title = (String) solrDocument.get("item_title");
  45. }
  46. item.setTitle(title);
  47. //添加到商品列表
  48. itemList.add(item);
  49. }
  50. //把结果添加到SearchResult中
  51. result.setItemList(itemList);
  52. //返回
  53. return result;
  54. }
  55. }

<2>添加调用dao的service类:

  1. /**
  2. * 搜索服务功能实现
  3. */
  4. @Service
  5. public class SearchServiceImpl implements SearchService {
  6. @Autowired
  7. private SearchDao searchDao;
  8. @Override
  9. public SearchResult search(String queryString, int page, int rows) throws Exception {
  10. //根据查询条件拼装查询对象
  11. //创建一个SolrQuery对象
  12. SolrQuery query = new SolrQuery();
  13. //设置查询条件
  14. query.setQuery(queryString);
  15. //设置分页条件
  16. if (page < 1) page =1;
  17. query.setStart((page - 1) * rows);
  18. if (rows < 1) rows = 10;
  19. query.setRows(rows);
  20. //设置默认搜索域
  21. query.set("df", "item_title");
  22. //设置高亮显示
  23. query.setHighlight(true);
  24. query.addHighlightField("item_title");
  25. query.setHighlightSimplePre("<font color='red'>");
  26. query.setHighlightSimplePost("</font>");
  27. //调用dao执行查询
  28. SearchResult searchResult = searchDao.search(query);
  29. //计算查询结果的总页数
  30. long recordCount = searchResult.getRecordCount();
  31. long pages = recordCount / rows;
  32. if (recordCount % rows > 0) {
  33. pages++;
  34. }
  35. searchResult.setTotalPages(pages);
  36. //返回结果
  37. return searchResult;
  38. }
  39. }

<3>控制层

  1. @Controller
  2. public class SearchController {
  3. @Autowired
  4. private SearchService searchService;
  5. @Value("${SEARCH_RESULT_ROWS}")
  6. private Integer SEARCH_RESULT_ROWS;
  7. @RequestMapping("/search")
  8. public String search(@RequestParam("q")String queryString,
  9. @RequestParam(defaultValue="1")Integer page, Model model) throws Exception {
  10. //int a = 1/0;
  11. //调用服务执行查询
  12. //把查询条件进行转码,解决get乱码问题
  13. queryString = new String(queryString.getBytes("iso8859-1"), "utf-8");
  14. SearchResult searchResult = searchService.search(queryString, page, SEARCH_RESULT_ROWS);
  15. //把结果传递给页面
  16. model.addAttribute("query", queryString);
  17. model.addAttribute("totalPages", searchResult.getTotalPages());
  18. model.addAttribute("itemList", searchResult.getItemList());
  19. model.addAttribute("page", page);
  20. //返回逻辑视图
  21. return "search";
  22. }
  23. }

solr的认识、linux下安装、java下使用(含下载资源)的更多相关文章

  1. Linux下安装Java环境配置

    1.下载安装文件 下载地址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 2. ...

  2. Kali下安装Java环境

    <-----教你在Kali下安装Java环境-----> 1. 下载1.8u121的JAVA JDK 下载地址:http://java.sun.com/javase/downloads/i ...

  3. 求助下 Ubuntu 15.10(64 位)下安装 pyspider 下的问题 - V2EX

    https://www.v2ex.com/t/279405 求助下 Ubuntu 15.10(64 位)下安装 pyspider 下的问题 - V2EX pip 更新到最新 sudo apt inst ...

  4. Linux中安装java JDK

    Linux中安装java JDK 1.下载jdk 下载地址:https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads. ...

  5. Linux下安装Java环境配置步骤详述

    0.下载jdk8 登录网址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html选择对 ...

  6. linux下安装java

    搞了一年IT了,作为IT人没怎么玩过linux挺丢脸的,要好好整整. 先从熟悉的来,在linux下开发java,首先要搭建环境. linux有一个工具yum,非常好用. 1.yum install j ...

  7. Linux SSH下安装Java并设置环境

    我是用Xshell进行远程连接阿里云服务器的,所以jdk不好下载. 我使用的是Winscp远程软件,在window上下载了jdk然后再上传到Linux服务器上 下面是安装的步骤 1.下载jdk8 登录 ...

  8. Linux下安装java的jdk和配置环境变量

    每次感觉配这个超级简单 但是每次都要查下 记一下好了 Linux下安装jdk,步骤如下 1:下载jdk包:本章使用的为后缀为tar.gz的文件(不需要安装),如jdk-8u111-linux-x64. ...

  9. [转]Linux下安装Java环境配置步骤详述

    1.下载jdk8 登录网址:http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 选择 ...

  10. Linux环境下安装java的方法

    linux安装java步骤 方式一:yum方式下载安装 1.查找java相关的列表 yum -y list java* 或者 yum search jdk 2.安装jdk yum install ja ...

随机推荐

  1. 软件性能测试技术树(二)----Linux服务器性能

    全图: 测试目的: 测试范围&性能指标: 测试与生产环境服务器配置不同的处理方法: 实时CPU监控: 实时内存监控: 实时网络监控: 实时磁盘监控: 万能命令:  Linux下的进程追踪命令: ...

  2. 原生javascript写自己的运动库(匀速运动篇)

    网上有很多JavaScript的运动库,这里和大家分享一下用原生JavaScript一步一步写一个运动函数的过程,如读者有更好的建议欢迎联系作者帮助优化完善代码.这个运动函数完成后,就可以用这个运动函 ...

  3. .NET开发微信小程序(基础配置)

    1.微信小程序的必备Model public class WxConfig { /// <summary> /// 小程序的appId /// 登录小程序可以直接看到 /// </s ...

  4. 利用JavaScriptSerializer转json实用方法

    项目中经常碰到需要输出的是json数据,使用JavaScriptSerializer转换,以前老的方法如下. JavaScriptSerializer jss = new JavaScriptSeri ...

  5. 微信小程序函数调用监控

    微信小程序之无埋点函数调用监控 有时候,面对一个bug,左思右想就是无法理解为什么. 我就有过这样的经历,耗时整个一个晚上,后来还是放弃了.不得不在所有可能的点都加上日志,部署等待再次报错,真的很让人 ...

  6. Mac命令行

    参考:http://www.cnblogs.com/-ios/p/4949923.html 必读 涵盖范围: 这篇文章对刚接触命令行的新手以及具有命令行使用经验的人都有用处.本文致力于做到覆盖面广(尽 ...

  7. Spring Boot Hikari

    Guys, I got the following properties to work, kind of. The following creates 2 pools. One connection ...

  8. 1.用互联网的产品思维打造一本app后端的书

    刚刚接触app后端,是做完adidas中国的官方商城的时候,那时不清楚app后端应该怎么架构,只能摸着石头过河,网络上只有一些零散的资料,遇到问题,只能不断地搜索,思考,务必找到解决问题的方法. 在从 ...

  9. nodejs中处理回调函数的异常

    如果是使用nodejs+express3这个经典的组合,那么有一种很方面的处理回调函数异常的方法: 1. 安装模块:express-domain-middleware 2. 加入如下的代码: app. ...

  10. python 写日志

    简单配置 日志级别 级别 何时使用 DEBUG 详细信息,典型地调试问题时会感兴趣. INFO 证明事情按预期工作. WARNING 表明发生了一些意外,或者不久的将来会发生问题(如'磁盘满了').软 ...