您的位置:首页 > 其它

solr搜索引擎安装配置及项目中的使用方法

2017-12-27 11:12 323 查看

Solr服务搭建:

Solr的环境:

Solr是java开发。

需要安装jdk。
安装环境Linux。
需要安装Tomcat。

搭建步骤:

第一步:把solr 的压缩包上传到Linux系统
solr-4.10.3.tgz.tgz (自行下载)



第二步:解压solr。
[root@localhost ~]# tar zxf solr-4.10.3.tgz.tgz

第三步:安装Tomcat,解压缩即可。
[root@localhost ~]# tar zxf apache-tomcat-7.0.47.tar.gz

第四步:把solr部署到Tomcat下。
[root@localhost ~]# mkdir /usr/local/solr
[root@localhost ~]# cp apache-tomcat-7.0.47 /usr/local/solr/tomcat -r

[root@localhost ~]# cd solr-4.10.3

[root@localhost solr-4.10.3]# cd dist/
[root@localhost dist]# cp solr-4.10.3.war /usr/local/solr/tomcat/webapps/solr.war
第五步:解压缩war包。启动Tomcat解压。

[root@localhost dist]# cd /usr/local/solr/tomcat/
[root@localhost tomcat]# bin/startup.sh
[root@localhost tomcat]# tal -f logs/catalina.out (查看日志起动完毕后关闭)
[root@localhost tomcat]# bin/shutdown.sh
[root@localhost tomcat]# cd /webapps/
[root@localhost webappst]# rm -f solr.war (删除war包)

第六步:把/root/solr-4.10.3/example/lib/ext目录下的所有的jar包,添加到solr工程中。

[root@localhost ~]# cd solr-4.10.3/example/lib/ext/
[root@localhost ext]# cp * /usr/local/solr/tomcat/wabapps/solr/WEB-INF/lib/(日志相关的jia包)
第七步:创建一个solrhome。/example/solr目录就是一个solrhome。复制此目录到/usr/local/solr/solrhome[root@localhost ~]# cd solr-4.10.3/example/
[root@localhost example]# cp -r solr /usr/local/solr/solrhome
第八步:关联solr及solrhome。需要修改solr工程的web.xml文件。
[root@localhost example]# vim /usr/local/solr/tomcat/webapps/solr/WEB-INF/web.xml



第九步:启动Tomcat

[root@localhost ~]# cd /usr/local/solr/tomcat/

[root@localhost tomcat]# bin/startup.sh

第十步:访问http://192.123.12.123:8080/solr/
访问成功进行下一步,没有访问到关闭防火墙试试。

配置业务域:

schema.xml中定义
1、Id

这里的数据库唯一id配置到solr中的id作为唯一标识 方便维护数据。

2、title 3、image  4、price  5.name等等

这些是你业务逻辑,页面展示,数据库存在的字段等等(下面会具体用到)。
创建对应的业务域。需要制定中文分析器:这里使用的是IKAnalyzer2012FF_u1.jar
创建步骤:
第一步:把中文分析器添加到工程中。需要下载IK Analyzer 2012FF_hf1文件
1、把IKAnalyzer2012FF_u1.jar添加到solr工程的lib目录下
[root@localhost ~]# cd IK\ Analyzer\ 2012FF_hf1

[root@localhost IK Analyzer 2012FF_hf1]# cp IKAnalyzer2012FF_u1.jar /usr/local/solr/tomcat/webapps/solr/WEB-INF/lib/
2、把扩展词典、配置文件放到solr工程的WEB-INF/classes目录下。
[root@localhost IK Analyzer 2012FF_hf1]# mkdir /usr/local/solr/tomcat/webapps/solr/WEB-INF/classes
[root@localhost IK Analyzer 2012FF_hf1]# cp ext_stopword.dic IkAnalyzer.cfg.xml mydict.dic /usr/local/solr/tomcat/webapps/solr/WEB-INF/classes/

第二步:配置一个FieldType,制定使用IKAnalyzer
修改schema.xml文件
[root@localhost IK Analyzer 2012FF_hf1]# vim /usr/local/solr/solrhome/collection1/conf/schema.xml
修改Solr的schema.xml文件,添加FieldType:最后一行</schema>前添加

<fieldType name="text_ik" class="solr.TextField">
<analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/>
</fieldType>
</schema>

第三步:配置业务域field,type制定使用自定义的FieldType。
设置业务系统Field还是在schema.xml文件接着添加
<field name="demo_title" type="text_ik" indexed="true" stored="true"/>
<field name="demo_point" type="text_ik" indexed="true" stored="true"/>
<field name="demo_price" type="long" indexed="true" stored="true"/>
<field name="demo_image" type="string" indexed="false" stored="true" />
<field name="demo_name" type="string" indexed="true" stored="true" />

<field name="demo_keywords" type="text_ik" indexed="true" stored="false" multiValued="true"/>
<copyField source="demo_title" dest="demo_keywords"/>
<copyField source="demo_point" dest="demo_keywords"/>
<copyField source="demo_name" dest="demo_keywords"/>
这里说明一下:type="text_ik"是使用中文分词器。copyField 是复制域,是对搜索的优化,dest="demo_keywords指定搜索域,意思是或者在point里包含,或者在name里包含等等,(像sql里的or like模糊匹配,或者在title里面包含)在项目中使用要指定搜索域,不指定默认搜索text,或者可以修改solrconfig.xml的默认搜索域。

第四步:重启tomcat
[root@localhost tomcat]# bin/shutdown.sh

[root@localhost tomcat]# bin/startup.sh

第五步:测试
刷新192.168.00.000:8080/solr/# 页面



测试没问题继续下一步

下面是在项目中使用:

使用solrJ管理索引库:使用SolrJ可以实现索引库的增删改查操作。

1.添加文档:
第一步:把solrJ的jar包添加到工程中。
<!-- solr客户端 -->
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
</dependency>
第二步:创建一个SolrServer,使用HttpSolrServer创建对象。
第三步:创建一个文档对象SolrInputDocument对象。
第四步:向文档中添加域。必须有id域,域的名称必须在schema.xml中定义。
第五步:把文档添加到索引库中。
第六步:提交。
代码演示:
@Test
public void addDocument() throws Exception {
// 第一步:把solrJ的jar包添加到工程中。
// 第二步:创建一个SolrServer,使用HttpSolrServer创建对象。
SolrServ
4000
er solrServer = new HttpSolrServer("http://192.168.00.000:8080/solr");
// 第三步:创建一个文档对象SolrInputDocument对象。
SolrInputDocument document = new SolrInputDocument();
// 第四步:向文档中添加域。必须有id域,域的名称必须在schema.xml中定义。
document.addField("id", "i1");
document.addField("demo_title", "测试");
document.addField("demo_price", "199");
// 第五步:把文档添加到索引库中。
solrServer.add(document);
// 第六步:提交。
solrServer.commit();
}测试通过查看solr里是否存在该内容。
2.删除文档:

根据id删除:
第一步:创建一个SolrServer对象。
第二步:调用SolrServer对象的根据id删除的方法。
第三步:提交。
@Test
public void deleteDocumentById() throws Exception {
// 第一步:创建一个SolrServer对象。
SolrServer solrServer = new HttpSolrServer("http://192.168.00.000:8080/solr");
// 第二步:调用SolrServer对象的根据id删除的方法。
solrServer.deleteById("i1");
// 第三步:提交。
solrServer.commit();
}根据查询删除:
@Test
public void deleteDocumentByQuery() throws Exception {
SolrServer solrServer = new HttpSolrServer("http://192.168.00.000:8080/solr");
solrServer.deleteByQuery("title:suibian");
solrServer.commit();
}
3.查询索引库:
查询步骤:
第一步:创建一个SolrServer对象
第二步:创建一个SolrQuery对象。
第三步:向SolrQuery中添加查询条件、过滤条件。。。
第四步:执行查询。得到一个Response对象。
第五步:取查询结果。
第六步:遍历结果并打印。
简单查询:

@Test
public void queryDocument() throws Exception {
// 第一步:创建一个SolrServer对象
SolrServer solrServer = new HttpSolrServer("http://192.168.00.000:8080/solr");
// 第二步:创建一个SolrQuery对象。
SolrQuery query = new SolrQuery();
// 第三步:向SolrQuery中添加查询条件、过滤条件。。。
query.setQuery("*:*");
// 第四步:执行查询。得到一个Response对象。
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("demo_title"));
System.out.println(solrDocument.get("demo_price"));
}
}带高亮显示:这里就要指定搜索域了(默认分页是10条)
@Test
public void queryDocumentWithHighLighting() throws Exception {
// 第一步:创建一个SolrServer对象
SolrServer solrServer = new HttpSolrServer("http://192.168.00.000:8080/solr");
// 第二步:创建一个SolrQuery对象。
SolrQuery query = new SolrQuery();
// 第三步:向SolrQuery中添加查询条件、过滤条件。。。
query.setQuery("测试");
//指定默认搜索域
query.set("df", "demo_keywords");
//开启高亮显示
query.setHighlight(true);
//高亮显示的域
query.addHighlightField("demo_title");
query.setHighlightSimplePre("<em>");
query.setHighlightSimplePost("</em>");
// 第四步:执行查询。得到一个Response对象。
QueryResponse response = solrServer.query(query);
// 第五步:取查询结果。
SolrDocumentList solrDocumentList = response.getResults();
System.out.println("查询结果的总记录数:" + solrDocumentList.getNumFound());
// 第六步:遍历结果并打印。
for (SolrDocument solrDocument : solrDocumentList) {
System.out.println(solrDocument.get("id"));
//取高亮显示
Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
List<String> list = highlighting.get(solrDocument.get("id")).get("demo_title");
String demoTitle = null;
if (list != null && list.size() > 0) {
demoTitle = list.get(0);
} else {
demoTitle = (String) solrDocument.get("demo_title");
}
System.out.println(demoTitle);
System.out.println(solrDocument.get("demo_price"));
}
}

基于ssm使用方法其他框架也可使用:

说明:查询数据库,根据数据库内容添加到solr中,进行增删改查业务。

导入数据到solr:

1.添加依赖:
2.SolrServer的配置:
这里配置了一个solrj的一个子类交由spring管理,业务需要直接注入,其他框架可以直接new,或者........。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
<bean id="httpSolrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
<constructor-arg index="0" value="http://192.168.00.000:8080/solr"/>
</bean>

</beans>3.service层:
把数据库的所有demo信息添加到solr中返回是否成功信息。
@Service
public class DemoServiceImpl implements DemoService {

@Autowired
private DemoMapper demoMapper;
@Autowired
private SolrServer solrServer;

@Override
public Result importAllDemo() {
try {
//查询demo列表
List<Demo> demoList = demoMapper.getDemoList();
//遍历demo列表
for (Demo demo: demoList) {
//创建文档对象
SolrInputDocument document = new SolrInputDocument();
//向文档对象中添加域
document.addField("id", demoItem.getId());
document.addField("demo_title", demo.getTitle());
document.addField("demo_point", demo.getSell_point());
document.addField("demo_price", demo.getPrice());
document.addField("demo_image", demo.getImage());
document.addField("demo_name", demo.getName());
//把文档对象写入索引库
solrServer.add(document);
}
//提交
solrServer.commit();
//返回导入成功
return Result.ok();
} catch (Exception e) {
e.printStackTrace();
return Result.build(500, "数据导入时发生异常");

}
}

}
4.controller:
直接调用service服务
@Controller
public class DemoController {

@Autowired
private DemoService demoService;

@RequestMapping("/index/demo/import")
@ResponseBody
public Result impotItemIndex() {
Result result = demoService.importAllDemo();
return result;
}

}
根据查询条件查询数据:带分页

dao层:
接收service封装好的查询条件SolrQuery ,返回demo总记录数和搜索的demo集合Result。
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 org.springframework.web.bind.annotation.ResponseBody;

@Repository
public class DemoDao {

@Autowired
private SolrServer solrServer;

/**
*根据查询条件查询索引库
* <p>Title: search</p>
* <p>Description: </p>
* @param query
* @return 查询内容 带分页信息
*/
public Result search(SolrQuery query) throws Exception {
//根据query查询索引库
QueryResponse queryResponse = solrServer.query(query);
//取查询结果。
SolrDocumentList solrDocumentList = queryResponse.getResults();
//取查询结果总记录数
long numFound = solrDocumentList.getNumFound();
Result result = new Result();
result.setRecordCount(numFound);
//取demo列表,需要取高亮显示
Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
List<Demo> demoList = new ArrayList<>();
for (SolrDocument solrDocument : solrDocumentList) {
Demo demo= new Demo();
demo.setId((String) solrDocument.get("id"));
demo.setCategory_name((String) solrDocument.get("demo_name"));
demo.setImage((String) solrDocument.get("demo_image"));
demo.setPrice((long) solrDocument.get("demo_price"));
demo.setPoint((String) solrDocument.get("demo_point"));
//取高亮显示
List<String> list = highlighting.get(solrDocument.get("id")).get("demo_title");
String title = "";
if (list != null && list.size() > 0) {
title = list.get(0);
} else {
title = (String) solrDocument.get("demo_title");
}
demo.setTitle(title);
//添加到demo列表
demoList.add(demo);
}
result.setDemoList(demoList);
//返回结果
return result;
}

}service层:
接收contoller中的分页信息page rows,及查询内容的字段keyword,补全SolrQuery 查询条件及Result返回内容,调用dao,返回查询结果及分页信息。
import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.e3mall.common.pojo.SearchResult;
import cn.e3mall.search.dao.SearchDao;
import cn.e3mall.search.service.SearchService;

@Service
public class DemoServiceImpl implements DemoService {

@Autowired
private DemoDao demoDao;

@Override
public Result search(String keyword, int page, int rows) throws Exception {
//创建一个SolrQuery对象
SolrQuery query = new SolrQuery();
//设置查询条件
query.setQuery(keyword);
//设置分页条件
if (page <=0 ) page =1;
query.setStart((page - 1) * rows);
query.setRows(rows);
//设置默认搜索域
query.set("df", "demo_title");
//开启高亮显示
query.setHighlight(true);
query.addHighlightField("demo_title");
query.setHighlightSimplePre("<em style=\"color:red\">");
query.setHighlightSimplePost("</em>");
//调用dao执行查询
Result result = demoDao.search(query);
//计算总页数
long recordCount = result.getRecordCount();
int totalPage = (int) (recordCount / rows);
if (recordCount % rows > 0)
totalPage ++;
//添加到返回结果
result.setTotalPages(totalPage);
//返回结果
return result;
}

}
controller层:
接收页面传过来的搜索关键词keyword, 第几页 page,调用service返回json数据,配置页数。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DemoController {

@Autowired
private DemoService demoService;

@Value("${DEMO_ROWS}")
private Integer DEMO_ROWS;

@RequestMapping("/search")
public String searchDemoList(String keyword,
@RequestParam(defaultValue="1") Integer page, Model model) throws Exception {
keyword = new String(keyword.getBytes("iso-8859-1"), "utf-8");
//查询商品列表
Result result = demoService.search(keyword, page, DEMO_ROWS);
//把结果传递给页面
model.addAttribute("query", keyword);
model.addAttribute("totalPages", result.getTotalPages());
model.addAttribute("page", page);
model.addAttribute("recourdCount", result.getRecordCount());
model.addAttribute("demoList", result.getDemoList());

//返回逻辑视图
return "demo";
}
}
到这里结束了,有什么问题回复,下一篇介绍solr集群。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐