`
cpf1985
  • 浏览: 78262 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

solr demo1

    博客分类:
  • solr
阅读更多
   项目中用到了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>

配置文件---配置文件比较多下一篇吧 哈哈
分享到:
评论
2 楼 l381336231 2014-03-03  
1 楼 zhchx0827 2012-04-24  
个人感觉在项目中好像不太适用,createIndexs方法接受一个List集合,如果Good有几千万条数据时,我总不能把数据全拿出来,传递给这个方法来创建索引吧

相关推荐

    solr demo

    1. **solrText**: 这可能是数据源文件或者测试数据集,用于演示Solr的全文搜索功能。通常,你需要对这些文本数据进行处理,将其导入到Solr中建立索引。 2. **solr服务器配置**:这包括Solr的配置文件如`solrconfig....

    solr demo文件txt版

    ### Solr Demo 文件介绍 #### 1. Paoding-dic-home.properties 配置文件解析 **paoding-dic-home.properties** 是Solr配置文件之一,主要负责配置Solr使用的外部词典路径及监控策略。 - **配置项含义解释** - `...

    全文搜索技术solr Demo

    1. 设置SOLR_HOME环境变量指向解压后的目录。 2. 运行`bin/solr start`启动Solr服务器。 3. 访问`http://localhost:8983/solr/`,如果看到Solr管理界面,说明安装成功。 四、创建和管理Solr集合(Core) 在Solr中,...

    Solr Java Demo

    1. **Apache Solr的基本概念**: - **索引**:Solr的核心功能之一是创建和管理索引,这是对原始数据进行预处理以加速查询的过程。 - **文档**:在Solr中,数据被表示为文档,每个文档由多个字段组成,如标题、内容...

    Flume+Solr演示demo.pdf

    根据给定文件信息,以下是关于Flume+Solr演示demo的知识点分析: ### Flume+Solr集成概念 #### Flume Flume是一种分布式、可靠且可用的系统,用于有效地从多个源收集、聚合和移动大量日志数据。它的主要特点包括...

    简单java实现的solr以及redis小demo

    总结来说,这个"简单java实现的solr以及redis小demo"项目将教会你如何利用Java API与Solr和Redis交互,实现基本的搜索功能和缓存策略。通过实践这个项目,你可以更深入地理解这两个强大的工具,并为未来的开发工作...

    solr-config_solrj-demo.rar_DEMO_solr_solr的j

    总之,"solr-config_solrj-demo.rar_DEMO_solr_solr的j"这个DEMO是一个全面了解和实践Solr配置及SolrJ使用的宝贵资源,它将引导你逐步掌握如何在实际项目中有效地运用Solr进行全文检索和数据分析。通过深入学习和...

    php solr client demo

    标题 "php solr client demo" 暗示我们即将探讨的是如何在PHP环境中使用Solr客户端进行操作。Solr是一个流行的、高性能的全文搜索引擎服务器,它允许开发者通过HTTP接口进行索引和搜索数据。这篇博客文章(博文链接...

    solr6 增量导入demo

    1. DataImportHandler(DIH):Solr6使用DIH进行数据导入,它是Solr内置的一个处理程序,可以连接到各种数据源(如数据库),并将数据导入到Solr索引中。DIH支持增量导入,通过跟踪数据库的LastModified时间戳或者...

    solr7.4数据库导入Demo(mysql数据库)

    本Demo将展示如何使用Solr 7.4与MySQL数据库集成,实现数据导入,并结合IK分词器提升中文搜索体验。 首先,你需要下载并安装Solr 7.4.0。解压压缩包`solr-7.4.0`,这是一个包含Solr服务器和配置文件的完整包。在`...

    全文检索(solr)实例

    1. 下载Solr:从Apache官网下载最新版本的Solr压缩包,解压到合适的位置,例如`D:\solr`。 2. 配置Solr Home:创建一个名为`solr_home`的文件夹,将示例中的`solr_data`放进去,然后将其路径设置为Solr的`SOLR_HOME`...

    使用java实现solr-7.1.0的api和solr最新支持的sql查询

    doc.addField("id", "1"); doc.addField("title", "Solr学习笔记"); client.add(doc); client.commit(); ``` 对于查询操作,你可以使用`SolrQuery`类来构造查询条件,然后调用`query()`方法执行查询: ```java ...

    solr_5.0_tomcat7_IKAnalyzer中文分词安装及demo

    在这个"solr_5.0_tomcat7_IKAnalyzer中文分词安装及demo"的压缩包中,你将找到如何在Solr 5.0中集成IKAnalyzer并进行演示的详细步骤。 首先,我们需要了解Solr与IKAnalyzer的集成过程: 1. **下载和解压**:获取...

    solr自定义评分组件demo.zip

    本示例将通过"solr自定义评分组件demo.zip"介绍如何在Solr中自定义评分策略,以优化搜索体验。 首先,让我们理解Solr的默认评分机制。Solr基于TF-IDF(词频-逆文档频率)算法来计算文档与查询的匹配度,得分越高...

    spring-data-solr 4.0.5.RELEASE 最新版本配置和小Demo

    目前在网上只能找到以前最老spring-data-solr 1.x.x 版本的配置和说明,最新版本的根本找不到,在参考spring-data-solr 官网文档后写的配置和小Demo,spring-data-solr 所使用的是目前最新版本的 spring-data-solr ...

    solr search

    "solr demo 无需分数 互相学习 拥抱开源"这部分描述可能是指提供了一个Solr的示例项目,帮助初学者快速理解和上手Solr。这个项目可能包含了配置文件、样例数据和简单的查询示例,通过运行和分析这个Demo,你可以了解...

Global site tag (gtag.js) - Google Analytics