1.solr简介
solr是以lucene为内核开发的企业级搜索应用 应用程序可以通过http请求方式来提交索引,查询索引,提供了比lucene更丰富的查询语言,是一个高性能,高可用环境全文搜索引擎
2.倒排索引的原理
- 实例文章表
文章id | 文章标题 | 文章内容 |
---|---|---|
1 | 我爱中国 | 中国地大物博 |
2 | 香港是中国一部分 | 香港的英文是hongkong |
- 到排索引原理
索引 文章id
我 1
爱 1
中国 1,2
香港 2
是 2
一部分 2
3.分词器
- 将中文拆分成有意义的词 常用的IK分词器,庖丁解牛分词器。
4.lucene
-
lucene是一个将text数据类型,分词建立索引的一个库,不适合企业级使用,企业级考虑高可用问题。
-
solr是一个企业级应用的搜索引擎,支持使用json格式提交数据。
-
json格式:
-
[] 代表数组
-
{} 对象(文档 document)
-
键值对 属性
-
模拟json
[
{
id:1,
title:'我爱中国',
content:'中国地大物博'
},
{
id:2,
title:'香港是中国一部分',
content:'香港的英文是hongkong'
}
]
5.solr安装(docker)
核(core):是用于存储json格式的数据,等价于mysql中数据库的概念。
文档:一个json对象就是一个文档 相同属性的json数组集合就是一个表。
检测端口命令: netstat -aon | grep 8983 下载netstat :yum -y install net-tools telnet
- docker pull solr:5.5.5 下载镜像
- docker run --name my_solr -id --net host -t solr:5.5.5 开启容器
- docker exec -it --user=solr my_solr bin/solr create_core -c mycore 创建core
- 创建成功后提示:
[root@localhost ~]# docker exec -it --user=solr my_solr bin/solr create_core -c mycore
Copying configuration to new core instance directory:
/opt/solr/server/solr/mycore
Creating new core 'mycore' using command:
http://localhost:8983/solr/admin/cores?action=CREATE&name=mycore&instanceDir=mycore
{
"responseHeader":{
"status":0,
"QTime":2137},
"core":"mycore"}
6.solr搜索
- q表示按照什么字段来搜索
- 字段名:值 (where 列名=值)
- 支持or 和and语法
- 比如 i:1 and j:2
- 模拟数据
7.solr中文分词器配置
- 默认solr 没有使用中文分词器 所有搜索的词 都是整个句子就是一个词 搜索时 将单词全部写入才能搜索或者使用* 需要配置中文分词器
- 目前比较好用的分词器 是IK 2012年停更 只支持到 Lucene4.7 所有 solr5.5 需要lucene5支持 需要修改部分源码来支持solr5.5
- 创建一个maven项目
- pom.xml添加依赖
- 下载ikanalyzer后默认是4.7版本,要替换成5.5.5版本
<dependencies>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>5.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>5.5.5</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>5.5.5</version>
</dependency>
<dependency>
<groupId>com.janeluo</groupId>
<artifactId>ikanalyzer</artifactId>
<version>2012_u6</version>
</dependency>
</dependencies>
- 重写IKAnalyzer类和IKTokenizer类
注意这里建包必须是:org.wltea.analyzer.lucene
IKAnalyzer类(类名必须要一样)
//修改后的类
package org.wltea.analyzer.lucene;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.Tokenizer;
/**
* IK分词器,Lucene Analyzer接口实现
* 兼容Lucene 4.0版本
*/
public final class IKAnalyzer extends Analyzer {
private boolean useSmart;
public boolean useSmart() {
return useSmart;
}
public void setUseSmart(boolean useSmart