当前位置:首页 > 开发 > 编程语言 > 搜索 > 正文

solr demo1

发表于: 2011-06-09   作者:cpf1985   来源:转载   浏览:
摘要:    项目中用到了solr 然后自己先写了个demo 不说了 上demo 使用到的技术        struts2+spring+ibatis+solr dao import java.util.ArrayList; import java.util.HashMap; import
   项目中用到了solr 然后自己先写了个demo 不说了 上demo 使用到的技术        struts2+spring+ibatis+solr

dao
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.cpf.model.Good;
import com.ibatis.sqlmap.client.SqlMapClient;


public class GoodsDao extends SqlMapClientDaoSupport {
	public List<Good> getAllGoods() {
		List<Good> goodList = new ArrayList<Good>();
		int length=(Integer) getSqlMapClientTemplate().queryForObject("allcount");
		int time=length/10000;
		if(length%1000!=0){
			time=time+1;
		}
		
		for(int n=0;n<time;n++){
			Map<String, Integer> map= new HashMap<String, Integer>();
			map.put("begin", n*1000);
			map.put("limit", 1000);
			List<Good> list = getSqlMapClientTemplate().queryForList("getAllGoods",map);
			goodList.addAll(list);
		}
		
		return goodList;
	}
	public Good getGoodById(int good_id){
		Good good = new Good();
		good = (Good)getSqlMapClientTemplate().queryForObject("getGoodByGoodId",good_id);
		return good;
	}
	
	public void deleteCommodity(int good_id){
		getSqlMapClientTemplate().delete("deleteGoodByGood_id",good_id);
	}
	
	public Good updateCommodity(Good good){
		getSqlMapClientTemplate().update("updateGood",good);
		return (Good)getSqlMapClientTemplate().queryForObject("getGoodByGoodId",good.getGood_id());
	}
	public void setSqlMapClientBase(SqlMapClient sqlMapClient) {
		super.setSqlMapClient(sqlMapClient);
	}
}


service
package com.cpf.service;
import java.util.List;
import com.cpf.dao.GoodsDao;
import com.cpf.model.Good;
public class GoodsService {
	public 	GoodsDao goodsDao;

	public List<Good> getAllGoods() {
		List<Good> commoditys = goodsDao.getAllGoods();
		return commoditys;
	}

	public void deleteCommodity(int good_id){
		goodsDao.deleteCommodity(good_id);
	}
	
	public Good getGoodById(int good_id){
		return goodsDao.getGoodById(good_id);
	}
	
	public Good updateCommodity(Good good){
		return goodsDao.updateCommodity(good);
	}

	public GoodsDao getGoodsDao() {
		return goodsDao;
	}

	public void setGoodsDao(GoodsDao goodsDao) {
		this.goodsDao = goodsDao;
	}
	
}


   package com.cpf.service;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.faces.FactoryFinder;

import org.apache.lucene.document.Document;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;

import com.cpf.model.Good;


public class SolrService {
	 private static SolrServer solrServer;
	 public  SolrService(String solrUrl){
		 try {
			solrServer= new CommonsHttpSolrServer(solrUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	 }
	 
	 public void createIndexs(List<Good> list){
		 List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
		 for(Good good :list){
			 SolrInputDocument doc= new SolrInputDocument(); 
			 doc.addField("id", good.getGood_id());
			 doc.addField("merchant_id", good.getGood_id());
			 doc.addField("region_id", good.getRegion_id());
			 doc.addField("good_name", good.getGood_name());
			 doc.addField("good_no", good.getGood_no());
			 doc.addField("barcode", good.getBarcode());
			 doc.addField("good_desc", good.getGood_desc());
			 doc.addField("price", good.getPrice());
			 doc.addField("num", good.getNum());
			 doc.addField("typeId", good.getTypeId());
			 doc.addField("typeName", good.getTypeName());
			 docs.add(doc);
		 }
		 try {
			solrServer.add(docs);
			solrServer.optimize();
			solrServer.commit();
		} catch (Exception e) {
		
			e.printStackTrace();
		} 
		 
	 }
	 public List<Good> search(String key){
		 List<Good> goodList= new ArrayList<Good>();
		 SolrQuery query= new SolrQuery();
		 query.setQuery("good_desc:"+key);
		 query.setRows(20);
		 query.setHighlight(true);
	        // 设置高亮区域
	     query.addHighlightField("good_desc");
	        // 设置高亮区域前缀
	     query.setHighlightSimplePre("<font color=\"red\">");
	        // 设置高亮区域后缀
	     query.setHighlightSimplePost("</font>");
		// query.setFacet(true);
		 QueryResponse rsp = null;
			try {
				rsp = solrServer.query(query);
			
			} catch (SolrServerException e) {
				e.printStackTrace();
			}
			SolrDocumentList documentList=rsp.getResults();
			@SuppressWarnings("unused")
			Map<String, Map<String,List<String>>> map=rsp.getHighlighting();
			
			Iterator<SolrDocument> list=documentList.iterator();
			
			while(list.hasNext()){
				SolrDocument doucment=list.next();
				Good good= new Good();
				String goodId=String.valueOf(doucment.get("id"));
				String goodName=(String) doucment.get("good_name");
				String goodDesc=(String) doucment.get("good_desc");
				if(map.get(goodId)!=null && map.get(goodId).size()>0){
				   	if(map.get(goodId).get("good_desc")!=null){
				   		goodDesc=map.get(goodId).get("good_desc").get(0);
				   	}
				}
				good.setGood_id(Integer.parseInt(goodId));
				good.setGood_name(goodName);
				good.setGood_desc(goodDesc);
				goodList.add(good);
			}
			
		 return goodList;
	 }
	 public void delIndex(){
		 try {
			solrServer.deleteByQuery("*:*");
			solrServer.commit();//要记得提交数据
		} catch (Exception e) {
			e.printStackTrace();
		} 
	 }
	public static SolrServer getSolrServer() {
		return solrServer;
	}
	public static void setSolrServer(SolrServer solrServer) {
		SolrService.solrServer = solrServer;
	}
	 
}


model
   package com.cpf.model;

public class Good {
	int docId;
	int merchant_id;
	int good_id;
	int region_id;
	String good_name;
	String good_no;
	String barcode;
	String good_desc;
	float price;
	int num;
	int typeId;
	String typeName;
	int count;
	public int getDocId() {
		return docId;
	}
	public void setDocId(int docId) {
		this.docId = docId;
	}
	public int getMerchant_id() {
		return merchant_id;
	}
	public void setMerchant_id(int merchantId) {
		merchant_id = merchantId;
	}
	public int getGood_id() {
		return good_id;
	}
	public void setGood_id(int goodId) {
		good_id = goodId;
	}
	public int getRegion_id() {
		return region_id;
	}
	public void setRegion_id(int regionId) {
		region_id = regionId;
	}
	public String getGood_name() {
		return good_name;
	}
	public void setGood_name(String goodName) {
		good_name = goodName;
	}
	public String getGood_no() {
		return good_no;
	}
	public void setGood_no(String goodNo) {
		good_no = goodNo;
	}
	public String getBarcode() {
		return barcode;
	}
	public void setBarcode(String barcode) {
		this.barcode = barcode;
	}
	public String getGood_desc() {
		return good_desc;
	}
	public void setGood_desc(String goodDesc) {
		good_desc = goodDesc;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public int getTypeId() {
		return typeId;
	}
	public void setTypeId(int typeId) {
		this.typeId = typeId;
	}
	public String getTypeName() {
		return typeName;
	}
	public void setTypeName(String typeName) {
		this.typeName = typeName;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
}


util工具类 用在action中
package com.cpf.util;
public class BaseAction  {
	protected final static  String RELOAD = "reload";
	
	protected final static String DEFAULT = "default";
	
	protected final static String REDIRECTACTION  = "redirectAction";
	
	protected final static String REDIRECT = "redirect";
	
	protected final static String CHAIN = "chain";
	
	private String target;

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public static String getReload() {
		return RELOAD;
	}

	public static String getDefault() {
		return DEFAULT;
	}

	public static String getRedirectaction() {
		return REDIRECTACTION;
	}

	public static String getRedirect() {
		return REDIRECT;
	}

	public static String getChain() {
		return CHAIN;
	}
	
	protected String redirect(String target){
		setTarget("/WEB-INF/"+target);
		return DEFAULT;
	}
	protected String redirect(String type,String target){
		setTarget(target);
		return type;
	}

	
}


Action
   package com.cpf.action;

import java.util.ArrayList;
import java.util.List;

import com.cpf.model.Good;
import com.cpf.service.GoodsService;
import com.cpf.service.SolrService;
import com.cpf.util.BaseAction;

public class SolrAction extends BaseAction {
	private SolrService solrService;
	private GoodsService goodsService;
	private List<Good> goodList;
	private String key;
	
	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public List<Good> getGoodList() {
		return goodList;
	}

	public void setGoodList(List<Good> goodList) {
		this.goodList = goodList;
	}

	
	public SolrService getSolrService() {
		return solrService;
	}

	public void setSolrService(SolrService solrService) {
		this.solrService = solrService;
	}

	public GoodsService getGoodsService() {
		return goodsService;
	}

	public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}
    public String createIndex(){
     List<Good> list=new ArrayList<Good>(100000);
     list=	goodsService.getAllGoods();
     solrService.createIndexs(list);
     return redirect("/index.jsp");
    }
    public String search(){
    	List<Good> list= solrService.search(key);
    	goodList=list;
    	return redirect("/page/goodsList.jsp");
    }
    public String searchPage(){
    	return redirect("/page/goodsList.jsp");
    }
    
    public String delIndex(){
    	solrService.delIndex();
    	return redirect("/index.jsp");
    }
}


jsp页面-----index.jsp创建索引
   <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
	<tr>
		<td>我靠 你丫终于创建成功了 </td>
		<td><input type="button" value="搜索商品" onclick="window.location.href='${pageContext.request.contextPath}/good/searchPage.action'"/></td>
		
		
	</tr>
	
</table>


</body>
</html>

  <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
	<tr>
		<td><input type="button" value="建立索引" onclick="window.location.href='${pageContext.request.contextPath}/good/createIndex.action'"/></td>
		<td><input type="button" value="删除索引" onclick="window.location.href='${pageContext.request.contextPath}/good/delIndex.action'"/></td>
		
	</tr>
	
	
</table>


</body>
</html>

jsp页面-----goodslist.jsp搜索
   <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@taglib uri='http://java.sun.com/jstl/fmt' prefix='fmt'%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function deleteGood(obj,obj1){
		document.getElementById('docId').value=obj;
		document.getElementById('good_id').value=obj1;
		document.forms['searchForm'].action='delete.action';
		document.forms['searchForm'].submit();
	}
	function updateGood(obj,obj1){
		document.getElementById('docId').value=obj;
		document.getElementById('good_id').value=obj1;
		document.forms['searchForm'].action='updateList.action';
		document.forms['searchForm'].submit();
	}
</script>
</head>
<body>
<form name="searchForm" action="${pageContext.request.contextPath}/good/search.action" method="post">
<table>
	<tr>
		<td>关键字:<input type="text" id="key" name="key" value="${key}"></td>
		<td>
			<select id="type" name="type">
				<option value="good_name" >商品名称</option>
				<option value="good_desc">商品描述</option>
			</select>
		</td>
		<td><input type="hidden" id="docId" name="docId" value="0">
			<input type="hidden" id="good_id" name="good_id" value="0">
			<input type="submit" value="搜索">
			<input type="button" value="统计" onclick="window.location.href='count.action'">
		</td>
	</tr>
</table>
</form>
<table border="1">
	<tr>
		
		<th>商品id</th>
		<th>商品名称</th>
		<th>商品描述</th>
		<th>操作</th>
	</tr>
	<s:iterator id="good" value="goodList">
	  	 <tr>
			<td>${good.good_id }</td>
			<td>${good.good_name }</td>
			<td>${good.good_desc }</td>
			<td>测试</td>
		</tr>
	</s:iterator>

</table>
</body>
</html>

配置文件---配置文件比较多下一篇吧 哈哈

solr demo1

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号