1.Solr是什么?

Solr 是Apache下的一个顶级开源项目,采用Java开发,它是基于Lucene的全文搜索服务器。Solr提供了比Lucene更为丰富的查询语言,同时实现了可配置、可扩展,并对索引、搜索性能进行了优化。 Solr可以独立运行,运行在Jetty、Tomcat等这些Servlet容器中,Solr 索引的实现方法很简单,用 POST 方法向 Solr 服务器发送一个描述 Field 及其内容的 XML 文档,Solr根据xml文档添加、删除、更新索引 。Solr 搜索只需要发送 HTTP GET 请求,然后对 Solr 返回Xml、json等格式的查询结果进行解析,组织页面布局。Solr不提供构建UI的功能,Solr提供了一个管理界面,通过管理界面可以查询Solr的配置和运行情况。

2.Solr的安装及配置

从Solr官方网站(http://lucene.apache.org/solr/ )下载Solr4.10.3,根据Solr的运行环境,Linux下需要下载lucene-4.10.3.tgz,windows下需要下载lucene-4.10.3.zip。
Solr使用指南可参考:https://wiki.apache.org/solr/FrontPage。

3.文件说明

bin:solr的运行脚本
contrib:solr的一些贡献软件/插件,用于增强solr的功能。
dist:该目录包含build过程中产生的war和jar文件,以及相关的依赖文件。
docs:solr的API文档
example:solr工程的例子目录:
example/solr:该目录是一个包含了默认配置信息的Solr的Core目录。
example/multicore:该目录包含了在Solr的multicore中设置的多个Core目录。
example/webapps: 该目录中包括一个solr.war,该war可作为solr的运行实例工程。
licenses:solr相关的一些许可信息

4.安装环境

solr 需要运行在一个Servlet容器中,Solr4.10.3要求jdk使用1.7以上,Solr默认提供Jetty(java写的Servlet容器),本教程使用Tocmat作为Servlet容器,环境如下:

Solr:Solr4.10.3
Jdk:jdk1.7.0_72
Tomcat:apache-tomcat-7.0.53

5.安装步骤

1.创建文件夹

[root@localhost /]# mkdir /usr/local/solr/

2.将Tomcat解压后的文件放进solr文件夹

[root@localhost /]# cp apache-tomcat-7.0.85 /usr/local/solr/tomcat -r

3.将solr压缩包上传服务器并解压
4.把/solr-4.10.3/dist/solr-4.10.3.war包部署到tomcat下。并改名为solr.war

[root@localhost dist]# cp solr-4.10.3.war /usr/local/solr/tomcat/webapps/solr.war
[root@localhost dist]# cd /usr/local/solr/tomcat/webapps/

5.解压war包。启动tomcat自动解压。关闭tomcat。删除solr.war.

[root@localhost bin]# ./startup.sh
[root@localhost bin]# ./shutdown.sh
[root@localhost bin]# cd ..
[root@localhost tomcat]# cd webapps/

6.把/solr-4.10.3/example/lib/ext 目录下所有的jar包复制到solr工程中。

[root@localhost /]# cd solr-4.10.3/example/lib/ext/
[root@localhost ext]# cp * /usr/local/solr/tomcat/webapps/solr/WEB-INF/lib/

7.创建solrhome。Solrhome是存放solr服务器所有配置文件的目录。example文件夹solr就是一个标准的Solrhome

[root@localhost /]# cd solr-4.10.3/example/
[root@localhost example]# cp -r solr /usr/local/solr/solrhome

8.告诉solr服务器solrhome的位置。需要修改solr工程的web.xml文件

[root@localhost solr]# cd tomcat/webapps/solr/WEB-INF/
[root@localhost WEB-INF]# vim web.xml

将注释去掉,并将Solrhome路径写进去

9.启动Tomcat,浏览器访问IP:8080/solr

10.使用IK-Analyzer。把分析器的文件夹上传到服务器。
链接:https://download.csdn.net/download/weixin_40263776/10274623
11.需要把分析器的jar包添加到solr工程中。

[root@localhost IKAnalyzer2012FF_hf1]# cp IKAnalyzer2012FF_u1.jar /usr/local/solr/tomcat/webapps/solr/WEB-INF/lib/

12.需要把IKAnalyzer需要的扩展词典及停用词词典、配置文件复制到solr工程的classpath。

[root@localhost IKAnalyzer2012FF_hf1]# mkdir /usr/local/solr/tomcat/webapps/solr/WEB-INF/classes
[root@localhost IKAnalyzer2012FF_hf1]# cp IKAnalyzer.cfg.xml ext_stopword.dic mydict.dic /usr/local/solr/tomcat/webapps/solr/WEB-INF/classes

注意:扩展词典及停用词词典的字符集必须是utf-8。不能使用windows记事本编辑。

13.配置fieldType。需要在solrhome/collection1/conf/schema.xml中配置。
技巧:使用vi、vim跳转到文档开头gg。跳转到文档末尾:G

[root@localhost solr]# vim solrhome/collection1/conf/schema.xml

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

6.业务字段配置

业务字段判断标准(这个是根据自己的业务分析):
1、在搜索时是否需要在此字段上进行搜索。例如:商品名称、商品的卖点、商品的描述
2、后续的业务是否需要用到此字段。例如:商品id。

需要用到的字段:
1、商品id
2、商品title
3、卖点
4、价格
5、商品图片
6、商品分类名称
7、商品描述

Solr中的业务字段:
1、id → 商品id
其他的对应字段创建solr的字段。

<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

测试一下

后边括号汉字是说明用的,实际操作时候没有这些汉字

删除刚测试的内容

删除两种方法:
1、根据id删除:

<delete>
<id>test001</id>
</delete>
<commit/>

2、根据查询删除:

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

7.java实际使用

1.添加solr客户端

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

2.测试Test

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;public class SolrJTest {@Testpublic void addDocument() throws Exception {//创建一连接SolrServer solrServer = new HttpSolrServer("http://192.168.184.129: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();}@Testpublic void deleteDocument() throws Exception {//创建一连接SolrServer solrServer = new HttpSolrServer("http://192.168.184.129:8080/solr");//solrServer.deleteById("test001");solrServer.deleteByQuery("*:*");solrServer.commit();}
}

效果图

3.将所有商品导入数据库

把商品信息导入到索引库
使用java程序读取mysql数据库中的商品信息,然后创建solr文档对象,把商品信息写入索引库。
需要发布一个服务

1.创建一个Maven文件
2.数据库查询语句(就是要将自己查询时要显示的数据关联显示出来存进Solr文档)

SELECTa.id,a.title,a.sell_point,a.price,a.image,b.`name` category_name,c.item_desc
FROMtb_item a
LEFT JOIN tb_item_cat b ON a.cid = b.id
LEFT JOIN tb_item_desc c ON a.id = c.item_id

3.要创建一个mapper接口+mapper映射文件。名称相同且在同一目录下。
Pojo

public class Item {private String id;private String title;private String sell_point;private long price;private String image;private String category_name;private String item_des;
}

Interface

public interface ItemMapper {/*** 获取solr查询数据* @return*/public List<Item> getItemList();
}

Mapper

<?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.search.mapper.ItemMapper" ><select id="getItemList" resultType="com.taotao.search.pojo.Item">SELECTa.id,a.title,a.sell_point,a.price,a.image,b. NAME category_nameFROMtb_item aLEFT JOIN tb_item_cat b ON a.cid = b.id</select></mapper>

Service

@Service
public class ItemServiceImpl implements ItemService {@Autowiredprivate ItemMapper itemMapper;@Autowiredprivate SolrServer solrServer;@Overridepublic TaotaoResult importAllItems() {try {//查询商品列表List<Item> list = itemMapper.getItemList();//把商品信息写入索引库for (Item item : list) {//创建一个SolrInputDocument对象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();}}

Controller

@Controller
@RequestMapping("/manager")
public class ItemController {@Autowiredprivate ItemService itemService;/*** 导入商品数据到索引库*/@RequestMapping("/importall")@ResponseBodypublic TaotaoResult importAllItems() {TaotaoResult result = itemService.importAllItems();return result;}
}

resource.properties

#solr服务地址
SOLR.SERVER.URL=http://192.168.184.129:8080/solr

applicationContext-solr.xml

<!-- 配置SolrServer对象 -->
<!-- 单机版 -->
<bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer"><constructor-arg name="baseURL" value="${SOLR.SERVER.URL}"></constructor-arg>
</bean>

修改pom文件,添加如下配置:

<build> <resources><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources></build>

搜索服务发布

需求分析
http形式的服务。对外提供搜索服务是一个get形式的服务。调用此服务时需要查询条件,分页条件可以使用page(要显示第几页)、rows(每页显示的记录数)。返回一个json格式的数据
请求的url: /search/query?q={查询条件}&page={page}&rows={rows}
查询测试:

@Testpublic 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"));}}

返回结果pojo:

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

Dao

public interface SearchDao {/*** 商品搜索* @param query* @return* @throws Exception*/SearchResult search(SolrQuery query) throws Exception;
}
@Repository
public class SearchDaoImpl implements SearchDao {@Autowiredprivate SolrServer solrServer;@Overridepublic SearchResult search(SolrQuery query) throws Exception {//返回值对象SearchResult result = new SearchResult();//根据查询条件查询索引库QueryResponse queryResponse = solrServer.query(query);//取查询结果SolrDocumentList solrDocumentList = queryResponse.getResults();//取查询结果总数量result.setRecordCount(solrDocumentList.getNumFound());//商品列表List<Item> itemList = new ArrayList<>();//取高亮显示Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();//取商品列表for (SolrDocument solrDocument : solrDocumentList) {//创建一商品对象Item item = new Item();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;}}

Service层
功能:接收查询条件。查询条件及分页条件(page、rows),创建一个SolrQuery对象。指定查询条件、分页条件、默认搜索域、高亮显示。调用dao层执行查询。得到查询结果计算总页数。返回SearchResult对象。

@Service
public class SearchServiceImpl implements SearchService {@Autowiredprivate SearchDao searchDao;@Overridepublic 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层
接收查询参数:查询条件、page、rows
调用Service执行查询返回一个查询结果对象。
把查询结果包装到TaotaoResult中返回,结果是json格式的数据。
如果查询条件为空,返回状态码:400,消息:查询条件不能为空。
Page为空:默认为1
Rows 为空:默认为60

@Controller
public class SearchController {@Autowiredprivate SearchService searchService;@RequestMapping(value="/query", method=RequestMethod.GET)@ResponseBodypublic 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 {//get出现乱码解决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);}}

applicationContext-solr.xml

  <!-- 扫描包加载Service实现类 --><context:component-scan base-package="com.taotao.search"><!-- 不要扫描controller包 --><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan>

Solr实现全文检索相关推荐

  1. [摘]全文检索引擎Solr系列—–全文检索基本原理

    原文链接--http://www.importnew.com/12707.html 全文检索引擎Solr系列-–全文检索基本原理 2014/08/18 | 分类: 基础技术, 教程 | 2 条评论 | ...

  2. 【solr】——全文检索实现原理

    Solr是一个独立的企业级搜索应用服务器,它对外提供类似于Web-service的API接口.用户可以通过http请求,向搜索引擎服务器提交一定格式的XML文件,生成索引:也可以通过Http Get操 ...

  3. 利用solr实现商品的搜索功能

    为什么要用solr服务,为什么要用luncence?问题提出:当我们访问购物网站的时候,我们可以根据我们随意所想的内容输入关键字就可以查询出相关的 内容,这是怎么做到呢?这些随意的数据不可能是根据数据 ...

  4. 什么是Lucene和Solr和Elasticsearch,它们的区别是什么?

    说道es我们往往会听到Solr和Lucene,那么Lucene和Solr和Elasticsearch的区别? Lucene Lucene是apache下的一个子项目,是一个开放源代码的全文检索引擎工具 ...

  5. Kettle, Solr

    http://antkillerfarm.github.io/ Kettle ETL,是英文Extract-Transform-Load的缩写,用来描述将数据从来源端经过抽取(extract).转换( ...

  6. 面试题:Lucene、Solr、ElasticSearch

    1.Lucene和Solr和Elasticsearch的区别 Lucene Lucene是apache下的一个子项目,是一个开放源代码的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文 ...

  7. solr搜索服务的使用

    1. 了解搜索技术 1.1 搜索引擎 所谓搜索引擎,就是根据用户需求与一定算法,运用特定策略从互联网检索出制定信息反馈给用户的一门检索技术.搜索引擎依托于多种技术,如网络爬虫技术.检索排序技术.网页处 ...

  8. 使用solr 检索word文档

    版权声明:本文为博主原创文章,转载注明出处即可. https://blog.csdn.net/bskfnvjtlyzmv867/article/details/80940089 I. Solr Sol ...

  9. Elasticsearch全文检索:根据关键词对全文查询检索,关键词也分词处理

    之前看过了solr的全文检索工具,原理比较简单,理解起来也快:这次我们项目上要求用Elasticsearch实现全文检索,据说这个插件功能更厉害,但是也没有具体研究过:这里就省略了es的部署过程和集成 ...

  10. Lucene全文检索_索引创建

      因项目原因接触到了solr,感觉全文检索满神奇的,计算机的搜索文件功能应该都用过,非常慢.lucene建立一个索引库,而索引检索是非常快的.   假设文件系统,某个目录下有n个文件,每个文件有不同 ...

最新文章

  1. Vue2.0使用vue-cli脚手架搭建
  2. 阿里飞猪个性化搜索排序探索实践
  3. layer.open 模态弹窗, 隐藏关闭按钮, 隐藏按钮组
  4. Java断言(assert)
  5. 1.3(java学习笔记)构造方法及重载
  6. 开心一刻,你和导师之间有什么有趣的事情?
  7. android 显示单位 像素
  8. postgres中分组后拼接多行
  9. centos7安装详细图解_CentOS7编译安装PHP7的详细教程(图文)
  10. 4999元起!三星在中国正式发布Galaxy S22系列
  11. AjaxPro.Dll运用
  12. 360安全浏览器安装adblock plus
  13. 基于STM32的智能小区安保管理系统设计
  14. LTE网络架构 学习整理
  15. 华为手机USB测试灰色
  16. 反函数法生成服从特定概率密度函数的随机数
  17. 戴尔刀片服务器型号在哪里,戴尔 PowerEdge M640 刀片式服务器:服务器 | Dell 中国大陆...
  18. 如何解决失眠有效方法,五个助眠小妙招
  19. Java中Number转为百分比
  20. Qt键盘事件(二)——长按按键反复触发event事件问题解决

热门文章

  1. vue中设置外部链接
  2. 房屋租赁合同可不可以用笔修改
  3. 凭什么国内造不出高端示波器?一起扒一扒示波器的发展史!
  4. 十问数据库:问来路,问现在,问未来
  5. 三十一、利用微信搜索抓取公众号文章
  6. 千万级 PV是什么意思?
  7. JAVA数据聚合服务_Spring Cloud 跨服务数据聚合小框架
  8. 最新Handsome主题V6.0免授权版+Typecho内核
  9. 绝对受用的求职经验分享
  10. 10个方法教你提升表达能力