solr学习笔记 -- day06 模拟京东实现站内搜索

来源:互联网 发布:mysql select unique 编辑:程序博客网 时间:2024/06/07 06:38

一:功能分析

1、输入条件

(1)、主条件查询

(2)、根据商品分类名称过滤

(3)、价格期间过滤

(4)、价格排序

(5)、分页

2、返回结果

(1)、总记录数

(2)、总页数

(3)、商品列表,包括:商品图片、商品标题、商品价格、关键词高亮显示

二:工程搭建

1、创建一个web工程

2、导入jar包

        solrJ的jar包

        solrJ依赖的jar包

        日志相关jar包

        springmvc相关jar包


3、框架整合

        只需要将springmvc整合如项目即可

(1)、项目整体


(2)、web.xml配置

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <display-name>jdsearch</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>    <!-- POST提交过滤器 UTF-8 --><filter><filter-name>encoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>encoding</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 前端控制器 --><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>springmvc</servlet-name><url-pattern>*.action</url-pattern></servlet-mapping></web-app>
(3)、springmvc.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:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd 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"><!-- 配置扫描 器 --><context:component-scan base-package="com.itheima.jd"/><!-- 配置处理器映射器  适配器 --><mvc:annotation-driven/><!-- 配置视图解释器 jsp --><bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/"/><property name="suffix" value=".jsp"/></bean><!-- 初始化sqlServer对象 --><bean id="solrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer"><constructor-arg index="0" value="http://localhost:8080/solr/collection1"/></bean></beans>

三:pojo层

1、对应商品信息创建一个Product对象

package com.itheima.jd.pojo;public class Product {// 商品编号private String pid;// 商品名称private String name;// 商品分类名称private String catalog_name;// 价格private float price;// 图片名称private String picture;public String getPid() {return pid;}public void setPid(String pid) {this.pid = pid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getCatalog_name() {return catalog_name;}public void setCatalog_name(String catalog_name) {this.catalog_name = catalog_name;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}public String getPicture() {return picture;}public void setPicture(String picture) {this.picture = picture;}}

2、创建查询结果对象SearchResult

package com.itheima.jd.pojo;import java.util.List;public class SearchResult {private List<Product> productList;//结果集列表private long recordCount;//总记录数private long pageCount;//总页数public List<Product> getProductList() {return productList;}public void setProductList(List<Product> productList) {this.productList = productList;}public long getRecordCount() {return recordCount;}public void setRecordCount(long recordCount) {this.recordCount = recordCount;}public long getPageCount() {return pageCount;}public void setPageCount(long pageCount) {this.pageCount = pageCount;}}

四:dao层

1、逻辑分析

(1)、执行查询,得到查询结果

(2)、取查询结果的总记录数

(3)、取商品列表,封装到ProductList中

(4)、取高亮显示的结果

(5)、返回SearchResult对象

2、代码实现

package com.itheima.jd.dao;import java.util.ArrayList;import java.util.List;import java.util.Map;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServer;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.SolrDocument;import org.apache.solr.common.SolrDocumentList;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import com.itheima.jd.pojo.Product;import com.itheima.jd.pojo.SearchResult;@Repositorypublic class SearchDao {@Autowiredprivate SolrServer solrServer;public SearchResult search(SolrQuery query) throws Exception{//1.执行查询,得到查询结果QueryResponse queryResponse = solrServer.query(query);SolrDocumentList docList = queryResponse.getResults();//2.取查询结果的总记录数long count = docList.getNumFound();//3.取商品列表,封装到productList中List<Product> list = new ArrayList<Product>();//4.取高亮显示的结果Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();for (SolrDocument doc : docList) {Product product = new Product();product.setCatalog_name((String) doc.get("product_catalog_name"));//取高亮结果List<String> list2 = highlighting.get(doc.get("id")).get("product_name");String name = "";if(list2 != null && list2.size() > 0){name = list2.get(0);}else{name = (String) doc.get("product_name");}product.setName(name);product.setPicture((String) doc.get("product_picture"));product.setPid((String) doc.get("id"));product.setPrice((float) doc.get("product_price"));list.add(product);}//5.返回SearchResult对象SearchResult result = new SearchResult();result.setProductList(list);result.setRecordCount(count);return result;}}

3、在springmvc中配置初始化solrServer

<!-- 初始化sqlServer对象 --><bean id="solrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer"><constructor-arg index="0" value="http://localhost:8080/solr/collection1"/></bean>

五:Servie层

1、参数分析:

a、主查询条件                          String   queryString

b、根据商品分类名称过滤       String   catalog_name

c、价格区间过滤                      String   price 

d、价格排序                              int   sort                          0:升序           1:降序

e、分页                                     int    page                        页码从1开始,需要计算start,rows

2、返回值:

SearchResult

3、逻辑分析:

a、根据参数创建SolrQuery对象

b、调用dao执行查询,可以得到SearchResult对象

c、取总记录数

d、计算总页数

e、返回SearchResult对象

4、代码实现

package com.itheima.jd.service;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrQuery.ORDER;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.itheima.jd.dao.SearchDao;import com.itheima.jd.pojo.SearchResult;@Servicepublic class SearchService {//设置分页中每页显示常量数private static Integer ROWS = 10;//注入dao@Autowiredprivate SearchDao searchDao;/** * 查询业务逻辑 */public SearchResult search(String queryString, String catalog_name, String price,int sort, int page) throws Exception{//1.根据参数创建solrQuery对象SolrQuery query = new SolrQuery();//设置查询条件if(queryString != null && !"".equals(queryString)){query.setQuery(queryString);}else{query.setQuery("*:*");}//根据商品分类名称过滤查询if(catalog_name != null && !"".equals(catalog_name)){query.addFilterQuery("product_catalog_name:" + catalog_name);}//根据价格区间过滤if(price != null && !"".equals(price)){String[] strs = price.split("-");query.addFilterQuery("product_price:[" + strs[0] + " TO " + strs[1] + "]");}//排序条件if(sort == 0){query.setSort("product_price",ORDER.asc);}else{query.setSort("product_price",ORDER.desc);}//分页组件query.setStart((page - 1) * ROWS);query.setRows(ROWS);//设置默认搜索域query.set("df","product_keywords");//开启高亮显示query.setHighlight(true);query.addHighlightField("product_name");//设置高亮字段query.setHighlightSimplePre("<em style='color:red'>");//设置高亮前缀query.setHighlightSimplePost("</em>");//设置高亮后缀 //2.调用dao查询,获取SearchResult对象SearchResult result = searchDao.search(query);//3.获取总记录数long recordCount = result.getRecordCount();//4.计算总页数long pageCount = recordCount / ROWS;if(recordCount % ROWS > 0){pageCount ++;}result.setPageCount(pageCount);//5.返回SearchResult对象return result;}}

六:controller层

package com.itheima.jd.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import com.itheima.jd.pojo.SearchResult;import com.itheima.jd.service.SearchService;@Controllerpublic class SearchController {@Autowiredprivate SearchService searchService;@RequestMapping("list")public String search(String queryString, String catalog_name, String price,@RequestParam(defaultValue="1") Integer page,@RequestParam(defaultValue="1") Integer sort, Model model) throws Exception{//调用service进行查询SearchResult result = searchService.search(queryString, catalog_name, price, sort, page);//回显结果model.addAttribute("result",result);model.addAttribute("queryString",queryString);model.addAttribute("catalog_name",catalog_name);model.addAttribute("price",price);model.addAttribute("page",page);model.addAttribute("sort",sort);//返回逻辑视图return "product_list";}}

七:完成后的工程代码

url:http://pan.baidu.com/s/1gfgPIyn