Solr的安装和使用

安装

CentOS中先安装好Java和Tomcat。准备工具IK Analyzer 2012FF

和Solr-4.10.3.tgz

将solr-4.10.3文件夹中dist中的solr-4.10.3.war文件复制到Tomcat的webapps,并且更名为solr.war,下开启tomcat解压后再关闭tomcat,再删除solr.war。

将Solr-4.10.3文件中,example/lib/ext下所有jar包复制到tomcat/webapps/solr/WEB-INF/lib文件夹下。

在你愿意的位置创建一个目录叫solrhome,把Solr-4.10.3 /example下solr复制到 solrhome中,然后在solr的WEB-INF下的web.xml中配置solrhome的位置。

    <env-entry><env-entry-name>solr/home</env-entry-name><env-entry-value>/usr/local/solr/solrhome</env-entry-value><env-entry-type>java.lang.String</env-entry-type></env-entry>

 

配置业务字段

 

把IK_Analyzer 2012文件夹下的IKAnalyzer2012FF_u1的jar包复制到solr 的WEB-INF下lib文件夹中。

在WEB-INF下新建classes文件夹。复制如下三个文件到classes中

cp IKAnalyzer.cfg.xml ext_stopword.dic mydict.dic /usr/local/solr/tomcat/webapps/solr/WEB-INF/classes

 

修改solrhome/collection1/conf/schema.xml文件,在末尾添加

<fieldType name="text_ik" class="solr.TextField"><analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/>
</fieldType>
<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

简单测试

打开solr网址,http://192.168.140.133:8080/solr/,点击左侧collection1,选择Documents

在documents中输入

点击Submit Document

 点击Collection1下的Query,点击Execute Query

 

删除该测试文档,

在Documents输入

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

Document Type选择xml,然后Submmit Document。

再Execute Query就没有文档了。

  },"response": {"numFound": 0,"start": 0,"docs": []}
}

 使用Java代码来测试solr文档

添加SolrJava客户端依赖

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

测试代码

public class SolrJTest {@Testpublic void addDocument() throws Exception {//创建一连接SolrServer solrServer = new HttpSolrServer("http://192.168.25.154: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.25.154:8080/solr");//solrServer.deleteById("test001");solrServer.deleteByQuery("*:*");solrServer.commit();}
}

使用Java代码将MySQL数据上传到Solr服务器

使用Http方式,访问http://localhost/search/import的时候,将后台MySQL几个表的数据上传到Solr服务器。

先看Controller

@Controller
public class SearchController {@Autowiredprivate ImportItemService importItemService;@RequestMapping("/search/import")@ResponseBodypublic TaotaoResult importAll() {TaotaoResult result = importItemService.importAll();return result;}

Service层总ImportItemService的实现类是

@Service
public class ImportItemServiceImpl implements ImportItemService {@Autowiredprivate ImportItemMapper iim;@Autowiredprivate SolrServer solrServer;@Overridepublic TaotaoResult importAll(){try {List<ImportItem> list = iim.importItemList();for(ImportItem item:list) {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();}}

其中ImportItem类

public class ImportItem {
//getter and setter...
...private String id;private String title;private String sell_point;private long price;private String image;private String category_name;private String item_des;}

 

DAO 层

public interface ImportItemMapper {List<ImportItem> importItemList();
}

对应XML文件

<?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.mapper.ImportItemMapper" ><select id="importItemList" resultType="com.taotao.pojo.ImportItem">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>

 搜索服务发布

预热:先了解SolrJ如何访问solr服务器。

测试代码

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

DAO层

public interface SearchDao {SearchResult search(SolrQuery query)throws Exception;
}
@Component
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<ImportItem> itemList = new ArrayList<>();//取高亮显示Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();//取商品列表for (SolrDocument solrDocument : solrDocumentList) {//创建一商品对象ImportItem item = new ImportItem();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;}

POJO类

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

Service层

public interface SearchService {SearchResult search(String query,int page,int rows)throws Exception;
}@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层

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

 

转载于:https://www.cnblogs.com/legion/p/9717724.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/249408.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

springboot工程打包时将application.properties放在jar包外

https://blog.csdn.net/luckyzsion/article/details/83743604

史上最详细的js日期正则表达式分享

最简单的正则 如 : /d{4}-/d{2}-/d{2} 但是实际情况却不是那么简单,,要考虑,有效性和闰年等问题..... 对于日期的有效范围&#xff0c;不同的应用场景会有所不同。MSDN中定义的DateTime对象的有效范围是&#xff1a;0001-01-01 00:00:00到9999-12-31 23:59:59。 UNIX时间戳的0按…

laravel的validator验证

1.引入对应的类 use Illuminate\Support\Facades\Validator;2.自定义规则&#xff0c;写在模型&#xff0c;控制器&#xff0c;中间件都可以 $rules [password > required|between;6,20|confirmed, name > required|between;3,8, ];3.自定义提示&#xff0c;laravel自…

HTML,CSS,JaveScript

一、HTML 1、标记语言 标记语言为非编程语言&#xff0c;不具备编程语言具备的程序逻辑 2、html为前端页面的主体&#xff0c;由标签、指令与转义字符&#xff08;实体&#xff09;等组成 标签&#xff1a;被尖括号包裹&#xff0c;由字母开头包含合法字符的&#xff0c;可以被…

python用户交互、基本数据类型、运算符

用户交互 在实际应用中&#xff0c;我们经常需要用户输入相应信息&#xff0c;根据用户输入信息进行反馈&#xff0c;此时我们需要input/output信息 python中提供了便捷的输入方法input&#xff08;&#xff09;和print&#xff08;&#xff09; 在python3中 name input("…

pom.xml详细说明

<project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd "><!-- 父项目的坐标。…

maven如何修改本地仓库与中央仓库

什么是Maven仓库 在不用Maven的时候&#xff0c;比如说以前我们用Ant构建项目&#xff0c;在项目目录下&#xff0c;往往会看到一个名为/lib的子目录&#xff0c;那里存放着各类第三方依赖jar文件&#xff0c;如 log4j.jar&#xff0c;junit.jar等等。每建立一个项目&#xff0…

Maven项目 之eclipse操作篇

使用eclipse创建maven项目大家应该都很熟悉&#xff0c;这里主要说明如何将已创建的非maven项目修改为maven项目。 1.创建测试项目 创建一个Dynamic Web Project &#xff0c;项目结构如图。 2.配置工程类型 右击项目--> Properties --> Project Facets&#xff0c;勾选…

前端jQuery基本语法

jQuery基础语法 #不管找什么标签&#xff0c;用什么选择器&#xff0c;都必须要写$("")&#xff0c;引号里面再写选择器&#xff0c;通过jQuery找到的标签对象就是一个jQuery对象&#xff0c;用原生JS找到的标签对象叫做DOM对象。二者可以相互转换。$()[0]:就是jQuer…

网络工程:3.1 RIP(Routing Information Protocol)协议

遵循协议&#xff1a; 1、特网rip1标准文件&#xff1a;rfc1058 网站 &#xff1a; https://tools.ietf.org/html/rfc1058 2、因特网rip2标准文件&#xff1a;rfc1723 网站 &#xff1a;https://tools.ietf.org/html/rfc1723 使用工具&#xff1a; GNS3 使用路由器文件&a…

为什么要有 hash 和 history

https://www.cnblogs.com/zhaobao1830/p/9269042.html

2:word定制工作界面

1.2&#xff0c;定制工作界面 一、功能区的折叠和展开 设计选项----右上方的向上的箭头 功能区的选项&#xff1a;三个&#xff1a;自动隐藏功能区&#xff0c;显示选项卡&#xff0c;显示选项卡和命令 二、定制快速访问工具栏 如何将一些常用的命令放到一个能便捷找到的地方 第…

JBPM中 使用JobExecutor执行timer定义的job

Job executor在jbpm.cfg.xml中是被缺省注释的&#xff0c;所以只要去掉此行即可通过JobExecutor来定时触发timer中的event-handler了 Xml代码 <jbpm-configuration><import resource"jbpm.default.cfg.xml" /><import resource"jbpm.businessca…

二维码生成

从vs Nugets搜索ThoughtWorks.QRCode下载ThoughtWorks.QRCode.dll private byte[] CreateQrcode(string code){ string enCodeString code;QRCodeEncoder qrCodeEncoder new QRCodeEncoder();qrCodeEncoder.QRCodeEncodeMode QRCodeEncoder.ENCODE_MODE.BYTE;qrCodeEncod…

vue created

https://blog.csdn.net/xdnloveme/article/details/78035065

Qt打开文件对话框同时选中多个文件或单个文件

Qt中打开单个文件 //str_path为文件路径 QString str_path QFileDialog::getOpenFileName(this, tr("选择转码文件"), tr("/home"), tr("视频文件(*.mp4 *.m3u8);;所有文件&#xff08;*.*);;")); 打开多个文件 QString strs; QStringList file…

Activiti Explorer安装

Activiti Explorer安装 分类&#xff1a; activiti 2014-05-06 19:11 349人阅读 评论(0) 收藏 举报 一、Activiti Explorer介绍 流程引擎的用户控制台。使用它来启动新流程&#xff0c;分配任务&#xff0c;查看并认领任务&#xff0c;等等。这个工具也可以用来管理Activ…

一招明白URL和URI的区别

URL和URI的区别(示例)&#xff1a; URL[统一资源定位器]&#xff1a; http://localhost:8080/api/account/queryAccountInfoURI[统一资源定位符]&#xff1a; /api/account/queryAccountInfo解释&#xff1a;说白了&#xff0c;可以认为url是绝对路径&#xff0c;uri是相对路径…

JS ES6中export和import详解

1.Export 模块是独立的文件&#xff0c;该文件内部的所有的变量外部都无法获取。如果希望获取某个变量&#xff0c;必须通过export输出&#xff0c; // profile.js export var firstName Michael; export var lastName Jackson; export var year 1958;或者用更好的方式&am…

巧用地图

L1-1 天梯赛座位分配&#xff08;20 分&#xff09; 天梯赛每年有大量参赛队员&#xff0c;要保证同一所学校的所有队员都不能相邻&#xff0c;分配座位就成为一件比较麻烦的事情。为此我们制定如下策略&#xff1a;假设某赛场有 N 所学校参赛&#xff0c;第 i 所学校有 M[i] 支…