1.2 Solr安装
1:安装 Tomcat,解压缩即可。
2:解压 solr。
3:把 solr 下的dist目录solr-4.10.3.war部署到 Tomcat\webapps下(去掉版本号)。
4:启动 Tomcat解压缩 war 包
5:把solr下example/lib/ext 目录下的所有的 jar 包,添加到 solr 的工程中(\WEB-INF\lib目录下)。
6:创建一个 solrhome 。solr 下的/example/solr 目录就是一个 solrhome。复制此目录到D盘改名为solrhome
7:关联 solr 及 solrhome。需要修改 solr 工程的 web.xml 文件。
<env-entry> <env-entry-name>solr/home</env-entry-name> <env-entry-value>d:\solrhome</env-entry-value> <env-entry-type>java.lang.String</env-entry-type> </env-entry> |
8:启动 Tomcat
http://IP:8080/solr/
1.3中文分析器IK Analyzer
1.3.1 IK Analyzer简介
IK Analyzer 是一个开源的,基亍 java 语言开发的轻量级的中文分词工具包。从 2006年 12 月推出 1.0 版开始, IKAnalyzer 已经推出了 4 个大版本。最初,它是以开源项目Luence 为应用主体的,结合词典分词和文法分析算法的中文分词组件。从 3.0 版本开始,IK 发展为面向 Java 的公用分词组件,独立亍 Lucene 项目,同时提供了对 Lucene 的默认优化实现。在 2012 版本中,IK 实现了简单的分词歧义排除算法,标志着 IK 分词器从单纯的词典分词向模拟语义分词衍化。
1.3.2 IK Analyzer配置
步骤:
1、把IKAnalyzer2012FF_u1.jar 添加到 solr 工程的 lib 目录下
2、创建WEB-INF/classes文件夹 把扩展词典、停用词词典、配置文件放到 solr 工程的 WEB-INF/classes 目录下。
3、修改 Solrhome 的 schema.xml 文件,配置一个 FieldType,使用 IKAnalyzer
<fieldType name="text_ik" class="solr.TextField"> <analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/> </fieldType> |
1.4配置域
域相当于数据库的表字段,用户存放数据,因此用户根据业务需要去定义相关的Field(域),一般来说,每一种对应着一种数据,用户对同一种数据进行相同的操作。
域的常用属性:
- name:指定域的名称
- type:指定域的类型
- indexed:是否索引
- stored:是否存储
- required:是否必须
- multiValued:是否多值
1.4.1域
修改solrhome的schema.xml 文件 设置业务系统 Field
<field name="item_goodsid" type="long" indexed="true" stored="true"/> <field name="item_title" type="text_ik" indexed="true" stored="true"/> <field name="item_price" type="double" indexed="true" stored="true"/> <field name="item_image" type="string" indexed="false" stored="true" /> <field name="item_category" type="string" indexed="true" stored="true" /> <field name="item_seller" type="text_ik" indexed="true" stored="true" /> <field name="item_brand" type="string" indexed="true" stored="true" /> |
1.4.2复制域
复制域的作用在于将某一个Field中的数据复制到另一个域中
<field name="item_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/> <copyField source="item_title" dest="item_keywords"/> <copyField source="item_category" dest="item_keywords"/> <copyField source="item_seller" dest="item_keywords"/> <copyField source="item_brand" dest="item_keywords"/> |
1.4.3动态域
当我们需要动态扩充字段时,我们需要使用动态域。对于品优购,规格的值是不确定的,所以我们需要使用动态域来实现。需要实现的效果如下:
配置:
<dynamicField name="item_spec_*" type="string" indexed="true" stored="true" /> |
2.Spring Data Solr入门
2.1 Spring Data Solr简介
虽然支持任何编程语言的能力具有很大的市场价值,你可能感兴趣的问题是:我如何将Solr的应用集成到Spring中?可以,Spring Data Solr就是为了方便Solr的开发所研制的一个框架,其底层是对SolrJ(官方API)的封装。
2.2 Spring Data Solr入门小Demo
2.2.1 搭建工程
- 创建maven工程,pom.xml中引入依赖
<dependencies> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-solr</artifactId> <version>1.5.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.9</version> </dependency> </dependencies> |
(2)在src/main/resources下创建 applicationContext-solr.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:solr="http://www.springframework.org/schema/data/solr" xsi:schemaLocation="http://www.springframework.org/schema/data/solr http://www.springframework.org/schema/data/solr/spring-solr-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- solr服务器地址 --> <solr:solr-server id="solrServer" url="http://127.0.0.1:8080/solr" /> <!-- solr模板,使用solr模板可对索引库进行CRUD的操作 --> <bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate"> <constructor-arg ref="solrServer" /> </bean> </beans> |
2.2.2 @Field 注解
创建 cn.itcast.pojo 包,将品优购的TbItem实体类拷入本工程 ,属性使用@Field注解标识 。 如果属性与配置文件定义的域名称不一致,需要在注解中指定域名称。
public class TbItem implements Serializable{
@Field private Long id;
@Field("item_title") private String title;
@Field("item_price") private BigDecimal price;
@Field("item_image") private String image;
@Field("item_goodsid") private Long goodsId;
@Field("item_category") private String category;
@Field("item_brand") private String brand;
@Field("item_seller") private String seller; ....... } |
2.2.3 增加(修改)
创建测试类TestTemplate.java
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:applicationContext-solr.xml") public class TestTemplate {
@Autowired private SolrTemplate solrTemplate;
@Test public void testAdd(){ TbItem item=new TbItem(); item.setId(1L); item.setBrand("华为"); item.setCategory("手机"); item.setGoodsId(1L); item.setSeller("华为2号专卖店"); item.setTitle("华为Mate9"); item.setPrice(new BigDecimal(2000)); solrTemplate.saveBean(item); solrTemplate.commit(); } } |
2.2.4 按主键查询
@Test public void testFindOne(){ TbItem item = solrTemplate.getById(1, TbItem.class); System.out.println(item.getTitle()); } |
2.2.5 按主键删除
@Test public void testDelete(){ solrTemplate.deleteById("1"); solrTemplate.commit(); } |
2.2.6 分页查询
首先循环插入100条测试数据
@Test public void testAddList(){ List<TbItem> list=new ArrayList();
for(int i=0;i<100;i++){ TbItem item=new TbItem(); item.setId(i+1L); item.setBrand("华为"); item.setCategory("手机"); item.setGoodsId(1L); item.setSeller("华为2号专卖店"); item.setTitle("华为Mate"+i); item.setPrice(new BigDecimal(2000+i)); list.add(item); }
solrTemplate.saveBeans(list); solrTemplate.commit(); } |
编写分页查询测试代码:
@Test public void testPageQuery(){ Query query=new SimpleQuery("*:*"); query.setOffset(20);//开始索引(默认0) query.setRows(20);//每页记录数(默认10) ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class); System.out.println("总记录数:"+page.getTotalElements()); List<TbItem> list = page.getContent(); showList(list); } //显示记录数据 private void showList(List<TbItem> list){ for(TbItem item:list){ System.out.println(item.getTitle() +item.getPrice()); } } |
2.2.7 条件查询
Criteria 用于对条件的封装:
@Test public void testPageQueryMutil(){ Query query=new SimpleQuery("*:*"); Criteria criteria=new Criteria("item_title").contains("2"); criteria=criteria.and("item_title").contains("5"); query.addCriteria(criteria); //query.setOffset(20);//开始索引(默认0) //query.setRows(20);//每页记录数(默认10) ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class); System.out.println("总记录数:"+page.getTotalElements()); List<TbItem> list = page.getContent(); showList(list); } |
2.2.8 删除全部数据
@Test public void testDeleteAll(){ Query query=new SimpleQuery("*:*"); solrTemplate.delete(query); solrTemplate.commit(); } |
3.品优购-批量数据导入
3.1需求分析
编写专门的导入程序,将商品数据导入到Solr系统中
3.2查询商品数据列表
3.2.1 工程搭建
(1)创建pinyougou-solr-util(jar) ,引入pinyougou-dao 以及spring 相关依赖
(2)创建spring 配置文件
内容为:
<context:component-scan base-package="com.pinyougou.solrutil"> </context:component-scan> |
3.2.2 代码编写
创建com.pinyougou.solrutil包,创建类SolrUtil ,实现商品数据的查询(已审核商品)
@Component public class SolrUtil { @Autowired private TbItemMapper itemMapper;
/** * 导入商品数据 */ public void importItemData(){ TbItemExample example=new TbItemExample(); Criteria criteria = example.createCriteria(); criteria.andStatusEqualTo("1");//已审核 List<TbItem> itemList = itemMapper.selectByExample(example); System.out.println("===商品列表==="); for(TbItem item:itemList){ System.out.println(item.getTitle()); } System.out.println("===结束==="); }
public static void main(String[] args) { ApplicationContext context=new ClassPathXmlApplicationContext("classpath*:spring/applicationContext*.xml"); SolrUtil solrUtil= (SolrUtil) context.getBean("solrUtil"); solrUtil.importItemData(); } } |
3.3数据导入Solr索引库
3.3.1实体类
- 将demo工程中添加了@Field注解的实体类拷贝到pinyougou-pojo中
- 在pinyougou-pojo中引入依赖
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-solr</artifactId> <version>1.5.5.RELEASE</version> </dependency> |
3.3.2添加Solr配置文件
添加applicationContext-solr.xml到spring目录
<!-- solr服务器地址 --> <solr:solr-server id="solrServer" url="http://127.0.0.1:8080/solr" /> <!-- solr模板,使用solr模板可对索引库进行CRUD的操作 --> <bean id="solrTemplate" class="org.springframework.data.solr.core.SolrTemplate"> <constructor-arg ref="solrServer" /> </bean> |
3.2.3调用模板类导入solr
修改pinyougou-solr-util的SolrUtil.java
@Autowired private SolrTemplate solrTemplate;
/** * 导入商品数据 */ public void importItemData(){
TbItemExample example=new TbItemExample(); Criteria criteria = example.createCriteria(); criteria.andStatusEqualTo("1");//已审核 List<TbItem> itemList = itemMapper.selectByExample(example); System.out.println("===商品列表==="); for(TbItem item:itemList){ System.out.println(item.getTitle()); } solrTemplate.saveBeans(itemList); solrTemplate.commit(); System.out.println("===结束==="); } |
3.4规格导入动态域
3.4.1@Dynamic注解
修改TbItem.java ,添加属性
@Dynamic @Field("item_spec_*") private Map<String,String> specMap; public Map<String, String> getSpecMap() { return specMap; } public void setSpecMap(Map<String, String> specMap) { this.specMap = specMap; } |
3.4.2修改导入工具
修改pinyougou-solr-util的SolrUtil.java ,引入fastJSON依赖
/** * 导入商品数据 */ public void importItemData(){ TbItemExample example=new TbItemExample(); Criteria criteria = example.createCriteria(); criteria.andStatusEqualTo("1");//已审核 List<TbItem> itemList = itemMapper.selectByExample(example); System.out.println("===商品列表==="); for(TbItem item:itemList){ Map specMap= JSON.parseObject(item.getSpec());//将spec字段中的json字符串转换为map item.setSpecMap(specMap);//给带注解的字段赋值 System.out.println(item.getTitle()); } solrTemplate.saveBeans(itemList); solrTemplate.commit(); System.out.println("===结束==="); } |
4.品优购-关键字搜索
4.1需求分析
打开搜索页面,在搜索框输入要搜索的关键字,点击搜索按钮即可进行搜索,展示搜索结果
4.2后端代码
4.2.1服务接口层
(1)创建pinyougou-search-interface模块(搜索服务接口),依赖pinyougou-pojo
(2)创建com.pinyougou.search.service包,创建业务接口
public interface ItemSearchService { /** * 搜索 * @param keywords * @return */ public Map<String,Object> search(Map searchMap); } |
4.2.2服务实现层
(1)创建war工程pinyougou-search-service ,引入pinyougou-search-interface spring dubbox 等相关依赖(参加其它服务工程)Tomcat运行端口9004
(2)添加web.xml (参加其它服务工程)
(3)在src/main/resources/spring 下applicationContext-service.xml (参见其它服务工程)dubbo端口20884
(4)在src/main/resources/spring 下创建spring 配置文件applicationContext-solr.xml(同demo工程)
(5)编写服务实现类ItemSearchServiceImpl.java
@Service(timeout=3000) public class ItemSearchServiceImpl implements ItemSearchService{ @Autowired private SolrTemplate solrTemplate;
@Override public Map<String, Object> search(Map searchMap) { Map<String,Object> map=new HashMap<>(); Query query=new SimpleQuery(); //添加查询条件 Criteria criteria=new Criteria("item_keywords").is(searchMap.get("keywords")); query.addCriteria(criteria); ScoredPage<TbItem> page = solrTemplate.queryForPage(query, TbItem.class); map.put("rows", page.getContent()); return map; } } |
4.2.3控制层
(1)创建pinyougou-search-web 工程 ,引入依赖(参见其它web模块),tomcat运行端口9104
(2)添加web.xml (参加其它web工程)
(3)添加配置文件 (内容参加其它web工程)
(4)创建包com.pinyougou.search.controller 编写控制器类
@RestController @RequestMapping("/itemsearch") public class ItemSearchController { @Reference private ItemSearchService itemSearchService;
@RequestMapping("/search") public Map<String, Object> search(@RequestBody Map searchMap ){ return itemSearchService.search(searchMap); } } |
4.3前端代码
4.3.1拷贝资源
将下列资源拷贝至pinyougou-search-web
将angularJS拷贝到插件文件夹
拷贝base.js到js文件夹
4.3.2服务层
pinyougou-search-web工程创建searchService.js
//搜索服务层 app.service("searchService",function($http){ this.search=function(searchMap){ return $http.post('itemsearch/search.do',searchMap); } }); |
4.3.3控制层
pinyougou-search-web工程searchController.js
app.controller('searchController',function($scope,searchService){ //搜索 $scope.search=function(){ searchService.search( $scope.searchMap ).success( function(response){ $scope.resultMap=response;//搜索返回的结果 } ); } }); |
4.3.4页面
pinyougou-search-web工程search.html
引入js
<script type="text/javascript" src="plugins/angularjs/angular.min.js"> </script> <script type="text/javascript" src="js/base.js"> </script> <script type="text/javascript" src="js/service/searchService.js"> </script> <script type="text/javascript" src="js/controller/searchController.js"> </script> |
指定控制器
<body ng-app="pinyougou" ng-controller="searchController"> |
绑定搜索框
<div class="input-append"> <input type="text" id="autocomplete" ng-model="searchMap.keywords" type="text" class="input-error input-xxlarge" /> <button class="sui-btn btn-xlarge btn-danger" ng-click="search()" type="button">搜索</button> </div> |
循环显示数据
<li class="yui3-u-1-5" ng-repeat="item in resultMap.rows"> <div class="list-wrap"> <div class="p-img"> <a href="item.html" target="_blank"><img src="{{item.image}}" /></a> </div> <div class="price"> <strong> <em>¥</em> <i>{{item.price}}</i> </strong> </div> <div class="attr"> <em>{{item.title}}</em> </div> <div class="cu"> <em><span>促</span>满一件可参加超值换购</em> </div> <div class="commit"> <i class="command">已有2000人评价</i> </div> <div class="operate"> <a href="success-cart.html" target="_blank" class="sui-btn btn-bordered btn-danger">加入购物车</a> <a href="javascript:void(0);" class="sui-btn btn-bordered">对比</a> <a href="javascript:void(0);" class="sui-btn btn-bordered">关注</a> </div> </div> </li> |