1.Solr簡介
1.1.Solr是什么
Solr是一個基于全文檢索的企業(yè)級應(yīng)用服務(wù)器。
全文檢索:可以輸入一段文字,通過分詞檢索數(shù)據(jù)!!(復(fù)習(xí))
應(yīng)用服務(wù)器:它是單獨的服務(wù)。
1.2.Solr能做什么
它就是用于做全文搜索。
1.3.為什么需要Solr
問題:我們已經(jīng)學(xué)過Lucene,為什么還要學(xué)習(xí)solr?
答:Lucene是一個工具包,不能單獨運行,需要導(dǎo)入到j(luò)ava代碼中。
Solr可以獨立運行在tomcat容器中,通過http協(xié)議,以接口的方式對外提供服務(wù),java代碼只需要專注于業(yè)務(wù)的處理就可以。

1.4.Solr下載路徑
http://archive.apache.org/dist/lucene/solr/
solr是基于lucene實現(xiàn)的,和Lucene同步更新。
1.5.Solr目錄結(jié)構(gòu)說明
下載solr-4.10.3.zip并解壓:

bin:solr的運行腳本
contrib:solr的一些擴展jar包,用于增強solr的功能。
dist:該目錄包含build過程中產(chǎn)生的war和jar文件,以及相關(guān)的依賴文件。
docs:solr的API文檔
example:solr工程的例子目錄:
licenses:solr相關(guān)的一些許可信息
2.入門示例
2.1.需求
使用Solr實現(xiàn)電商網(wǎng)站的商品搜索功能。
2.2.配置步驟說明
(1)配置Solr服務(wù)器。
(2)配置SolrHome。(Solr服務(wù)的主目錄,磁盤)
(3)在Solr服務(wù)器中加載SolrHome。
(4)java程序訪問Solr服務(wù)器,實現(xiàn)全文搜索。
2.3.配置步驟
2.4.第一部分:配置Solr服務(wù)器
--說明:Solr可以獨立運行,需要servlet容器加載它。本文使用tomcat。
2.4.1.第一步:解壓一個Tomcat
解壓一個新的Tomcat,專門用來加載Solr。

2.4.2.第二步:部署Solr服務(wù)到Tomcat中
--在Solr的下載包中,提供了Solr的war包程序。(空的war包程序)

--拷貝solr.war到Tomcat的webapp目錄下。并解壓
[圖片上傳失敗...(image-a9623d-1563540122837)]

2.4.3.第三步:添加Solr運行依賴的jar包
--在Solr的下載包中,提供Solr服務(wù)器運行所依賴的jar包。

(1)拷貝/example/lib/ext下的所有包,到solr應(yīng)用的lib目錄中

(2)拷貝/example/resource/log4j.properties,到solr應(yīng)用的classes目錄下。
--前提:先在/WEB-INF/目錄下,創(chuàng)建classes目錄。

2.5.第二部分:配置SolrHome
--說明:Solr的下載包中,提供了標準的SolrHome配置。

2.5.1.第一步:拷貝到本地,修改名稱為SolrHome。(見名知意)

2.5.1.1.SolrHome說明
--SolrHome目錄結(jié)構(gòu):

(1)SolrHome是Solr配置搜索服務(wù)的主目錄。
(2)collection1稱為Solr服務(wù)的一個實例(solrCore)。
(3)一個solr實例對應(yīng)一個索引庫。
(4)Solr可以同時配置多個實例。以便為不同的java程序提供搜索服務(wù)。
配置solr服務(wù),就是在配置solr實例。
2.5.2.第二步:配置SolrCore
2.5.2.1.Step1:配置SolrCore實例的名稱
--說明:每一個實例都有自己的名稱。在core.properties文件中配置

--在這里,我們將其修改為:soreCore0719

2.5.2.2.Step2:配置SolrCore所需的jar依賴
--說明:Solr下載包中,提供SolrCore所需要的所有jar依賴。

(1)在SolrHome同級目錄下,創(chuàng)建depJar文件夾。(目的:方便管理jar依賴)

(2)拷貝contrib、dist兩個目錄到depJar目錄下。

(3)修改/collection1/conf目錄下的solrconfig.xml,加載jar包
--說明:solr是通過<lib>標簽,來加載運行所需要的jar包的。

(4)配置索引庫目錄
--說明:solr是通過<dataDir>標簽,來指定索引庫的目錄的。

--默認路徑是在SolrCore目錄下,跟conf目錄同級。首次加載時,將自動創(chuàng)建。
[圖片上傳失敗...(image-d60bc7-1563540122837)]

本課程就使用該默認路徑。
2.6.第三部分:在Solr服務(wù)器中加載SolrHome
2.6.1.第一步:修改web.xml加載SolrHome
--在solr的應(yīng)用中,是通過web.xml來加載SolrHome的。

--說明:在這里是通過修改<env-entry>標簽,來加載SolrHome的。

2.6.2.第二步:啟動Tomcat測試
--訪問地址 http://localhost:8080/solr

--solr服務(wù)器配置成功!!!
2.7.第四部分:創(chuàng)建java程序訪問solr服務(wù)器
--前提:創(chuàng)建好了數(shù)據(jù)庫。(導(dǎo)入products-solr.sql文件即可)

--配置步驟說明:
(1)創(chuàng)建項目。
(2)創(chuàng)建索引
(3)搜索索引
2.7.1.第一步:創(chuàng)建項目,導(dǎo)入jar包
--導(dǎo)包說明:
SolrJ核心包 /solr-4.10.3/dist/solr-solrj-4.10.3.jar
SolrJ依賴包 /solr-4.10.3/dist/solrj-lib下的所有包
日志依賴包 /solr-4.10.3/example/lib/ext目錄下的所有jar包
JDBC驅(qū)動包 mysql-connector-java-5.1.10-bin.jar
--拷貝log4j.properties到src目錄下。(或者創(chuàng)建一個Source Folder)
--項目結(jié)構(gòu):

2.7.2.第二步:創(chuàng)建索引
--步驟說明。(復(fù)習(xí)回顧)
(1)采集數(shù)據(jù)。
(2)將數(shù)據(jù)轉(zhuǎn)換成Solr文檔。
(3)連接solr服務(wù)器,將文檔寫入索引庫。
2.7.2.1.Step1:采集數(shù)據(jù)
--需求采集的字段說明:
參與搜索的字段:名稱、價格、商品類別、描述信息
參與結(jié)果展示的字段:商品id、圖片、
(1)創(chuàng)建Product類
public class Product {
private Integer pid;
private String name;
private String catalog_name;
private double price;
private String description;
private String picture;
// 補全get、set方法
}
(2)創(chuàng)建ProductDao類
package cn.gzsxt.solr.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import cn.gzsxt.solr.pojo.Product;
public class ProductDao {
private Connection connection;
private PreparedStatement pst;
private ResultSet rs;
/**
* 采集數(shù)據(jù),查詢所有商品
* @return
*/
public List<Product> getAllProducts() {
List<Product> products = new ArrayList<>();
try {
//1、加載驅(qū)動
Class.forName("com.mysql.jdbc.Driver");
//2、獲取Connection連接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/solr", "root", "gzsxt");
//3、獲取PreparedStatement,執(zhí)行預(yù)編譯
pst = connection.prepareStatement("select pid,name, catalog_name,price,description,picture from products");
//4、執(zhí)行sql搜索
rs = pst.executeQuery();
Product p = null;
while(rs.next()){
p = new Product();
p.setPid(rs.getInt("pid"));
p.setName(rs.getString("name"));
p.setPrice(rs.getFloat("price"));
p.setPicture(rs.getString("picture"));
p.setDescription(rs.getString("description"));
p.setCatalog_name(rs.getString("catalog_name"));
products.add(p);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(null!=rs){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=pst){
try {
pst.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(null!=connection){
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return products;
}
}
(3)創(chuàng)建一個測試類ProductDaoTest
--導(dǎo)入junit類庫。(快捷鍵ctrl+1)
package cn.gzsxt.solr.test;
import org.junit.Test;
import cn.gzsxt.solr.dao.ProductDao;
public class ProductDaoTest {
@Test
public void getAllProducts(){
ProductDao dao = new ProductDao();
System.out.println(dao.getAllProducts());
}
}
--測試結(jié)果,采集數(shù)據(jù)成功!!!

2.7.2.2.Step2:將數(shù)據(jù)轉(zhuǎn)換成Solr文檔SolrInputDocument
--說明:solr是通過SolrInputDocument來封裝數(shù)據(jù)的。部分源碼如下:
public SolrInputDocument(Map fields){
_documentBoost = 1.0F;
_fields = fields;
}
public void addField(String name, Object value){
addField(name, value, 1.0F);
}
問題:我們在Lucene中知道,域有三大屬性,在創(chuàng)建文檔的時候指定。而Solr的源碼中,只是用一個Map集合來封裝域的信息。那域的三大屬性怎么定義呢?
答:Solr是通過一個配置文件schema.xml,事先定義域的信息的。
2.7.2.2.1.Solr域的說明
--通過<field>標簽定義域的名稱等信息

name屬性:域的名稱
type屬性: 域的類型(<FieldType>標簽,加載了分詞器,指定了分詞屬性)
indexed屬性:是否索引
stored屬性:是否存儲
multiValued屬性:是否支持多個值
--通過<fieldType>標簽,定義域的類型信息

name屬性:域類型的名稱
class屬性:指定域類型的solr類型。
<analyzer>:指定分詞器。
<analyzer type=”index”>:表示在創(chuàng)建索引時,對域做分詞處理。
<analyzer type=”query”>:表示在檢索索引時,對域做分詞處理。
<tokenizer>標簽:指定分詞器
<filter>標簽:指定過濾器
2.7.2.2.2.Solr域的特點
(1)、Solr的域必須先定義,后使用。(否則報錯:unknown fieldName)
(2)、定義solr域的時候,必須指定是否索引、是否存儲這兩個屬性。<field>
(3)、定義solr域的時候,必須指定域的類型<fieldType>:
因為域的類型確定了這個域在索引、搜索兩個階段的分詞屬性。
<field>標簽: 來指定索引、存儲兩個屬性
<fieldType>標簽:來指定分詞屬性
(4)、每一個文檔中,必須包含id這個域,它的值標記文檔的唯一性。

2.7.2.2.3.配置Solr業(yè)務(wù)域
--商品各字段屬性說明

--修改schema.xml,添加如下配置。(id域不用配置,直接使用solr的id域)
<!--product-->
<field name="id" type="string" indexed="true" stored="true" required="true"
multiValued="false" />
<field name="product_name" type="text_general" indexed="true" stored="true"/>
<field name="product_catalog_name" type="string" indexed="true" stored="true" />
<field name="product_price" type="double" indexed="true" stored="true"/>
<field name="product_description" type="text_general" indexed="true" stored="false" />
<field name="product_picture" type="string" indexed="false" stored="true" />
2.7.2.2.4.修改ProductDao,新增getDocuments方法
/**
* 將采集到的商品數(shù)據(jù),轉(zhuǎn)換成solr文檔類型
* @param products
* @return
*/
public List<SolrInputDocument> getDocuments(List<Product> products){
List<SolrInputDocument> docs = new ArrayList<>();
SolrInputDocument doc = null;
for (Product product : products) {
doc = new SolrInputDocument();
doc.addField("id", product.getPid());
doc.addField("product_name", product.getName());
doc.addField("product_price", product.getPrice());
doc.addField("product_catalog_name", product.getCatalog_name());
doc.addField("product_description", product.getDescription());
doc.addField("product_picture", product.getPicture());
docs.add(doc);
}
return docs;
}
2.7.2.3.Step3:連接Solr服務(wù)器,創(chuàng)建索引
--前提:已經(jīng)啟動了Tomcat,加載了Solr服務(wù)器。(前面給過schema.xml,需要重寫啟動Tomcat)
--修改ProductDaoTest類,新增createIndex方法
@Test
public void createIndex(){
// 1、 創(chuàng)建HttpSolrServer對象,通過它和Solr服務(wù)器建立連接。
// 參數(shù):solr服務(wù)器的訪問地址
HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr/solrCore0719");
// 2、 通過HttpSolrServer對象將SolrInputDocument添加到索引庫。
ProductDao dao = new ProductDao();
try {
server.add(dao.getDocuments(dao.getAllProducts()));
// 3、 提交。
server.commit();
System.out.println("創(chuàng)建索引庫成功!!!");
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
2.7.2.4.Step4:訪問Solr主界面,在Query選項下測試
--創(chuàng)建索引庫成功?。?!
2.7.3.第三步:搜索索引
--修改ProductDaoTest類型,新增一個查詢方法
@Test
public void queryIndex() throws Exception {
// 創(chuàng)建HttpSolrServer對象,通過它和Solr服務(wù)器建立連接。
// 參數(shù):solr服務(wù)器的訪問地址
HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr/solrCore0719");
// 創(chuàng)建SolrQuery對象
SolrQuery query = new SolrQuery();
// 設(shè)置查詢條件,參考主界面
query.set("q", "*:*");
// 調(diào)用server的查詢方法,查詢索引庫
QueryResponse response = server.query(query);
// 查詢結(jié)果
SolrDocumentList results = response.getResults();
// 查詢結(jié)果總數(shù)
long cnt = results.getNumFound();
System.out.println("查詢結(jié)果總數(shù):" + cnt);
System.out.println("--------------------分隔符-------------------");
for (SolrDocument solrDocument : results) {
System.out.println("商品id:"+solrDocument.get("id"));
System.out.println("商品名稱:"+solrDocument.get("product_name"));
System.out.println("商品價格:"+solrDocument.get("product_price"));
System.out.println("商品類別:"+solrDocument.get("product_catalog_name"));
System.out.println("商品圖片:"+solrDocument.get("product_picture"));
System.out.println("----------------------------------------");
}
}
--查詢結(jié)果,非常成功?。。?/p>

3.solr管理控制臺
3.1.查詢界面說明

(1) q - 查詢關(guān)鍵字,必須,如果查詢所有文檔時,使用:。

(2) fq - (filter query)過慮查詢,可以有多個。如:價格10到50的記錄。

(3) sort - 排序,格式:sort=<field name>+<desc|asc>。如:按價格升序

(4) start - 分頁顯示使用,開始記錄下標,從0開始

(5) rows - 指定返回結(jié)果最多有多少條記錄,配合start來實現(xiàn)分頁。

(6) fl - 指定返回那些字段內(nèi)容,用逗號或空格分隔多個。

(7) df-指定一個默認搜索的Field

(8) wt - (writer type)指定輸出格式,默認json格式。

3.1.1.對照界面,實現(xiàn)復(fù)雜查詢
--修改ProductDaoTest類型,新增動態(tài)查詢方法
@Test
public void queryDynamic(){
//1、連接solr服務(wù)器
HttpSolrServer server = new HttpSolrServer("http://localhost:8080/solr/solrCore0719");
//2、創(chuàng)建查詢對象,封裝查詢條件
SolrQuery query = new SolrQuery();
//設(shè)置默認搜索的域
query.set("df", "product_name");
//參考管理界面中的 "q"標簽,封裝查詢的關(guān)鍵詞
query.set("q", "音樂盒");
//添加價格過濾
query.addFilterQuery("product_price:[10 TO 50]");
//添加類別過濾
query.addFilterQuery("product_catalog_name:幽默雜貨");
//設(shè)置排序 價格升序
query.set("sort","product_price asc");
//設(shè)置分頁信息 第二頁 每頁10條 start=(page-1)*pageSize
query.set("start", 10);
query.set("rows",10);
//設(shè)置要查詢字段
query.set("fl", "id,product_name,product_price");
//3、執(zhí)行查詢
try {
QueryResponse response = server.query(query);
//獲取查詢的響應(yīng)碼
int status = response.getStatus();
System.out.println("響應(yīng)碼:"+status);
if(0==status){
SolrDocumentList solrDocumentList = response.getResults();
long numFound = solrDocumentList.getNumFound();
System.out.println("共查詢到"+numFound+"條滿足條件的數(shù)據(jù)!");
System.out.println("--------------");
for (SolrDocument s : solrDocumentList) {
System.out.println("商品的id:"+s.get("id"));
System.out.println("商品的名稱:"+s.get("product_name"));
System.out.println("商品的價格:"+s.get("product_price"));
System.out.println("商品的圖片:"+s.get("product_picture"));
System.out.println("商品的類別名稱:"+s.get("product_catalog_name"));
System.out.println("商品的描述:"+s.get("product_decsription"));
System.out.println("-----------分隔符---------------");
}
}
} catch (SolrServerException e) {
e.printStackTrace();
}
}
--測試結(jié)果:非常成功!?。。▽Ρ裙芾斫缑娌樵兘Y(jié)果)

3.2.安裝DataImport插件
3.2.1.Dataimport插件說明
--好處:可以在管理界面直接從數(shù)據(jù)庫導(dǎo)入數(shù)據(jù)到索引庫。(即:一個插件解決入門示例中,創(chuàng)建索引的全部操作)

3.2.2.安裝步驟
3.2.2.1.第一步:添加jar依賴
(1)將/solr-4.10.3/dist/solr-dataimporthandler-4.10.3.jar拷貝到
/depJar/contrib/dataimporthandler/lib目錄下

(2)、將jdbc驅(qū)動包拷貝到 /depJar/contrib/db/lib 目錄下

(3)、在solrconfig.xml文件中,加載這兩個jar依賴
<lib dir="F:/depJar/contrib/dataimporthandler/lib/" regex=".*\.jar" />
<lib dir="F:/depJar/contrib/db/lib/" regex=".*\.jar" />
3.2.2.2.第二步:配置數(shù)據(jù)庫表和solr域的映射關(guān)系
--在solr實例的conf目錄下,配置數(shù)據(jù)庫映射文件data-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<dataConfig>
<dataSource type="JdbcDataSource"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/solr"
user="root"
password="gzsxt"/>
<document>
<entity name="product" query="SELECT pid,name,catalog,catalog_name,price,description,picture FROM products ">
<field column="pid" name="id"/>
<field column="name" name="product_name"/>
<field column="catalog_name" name="product_catalog_name"/>
<field column="price" name="product_price"/>
<field column="description" name="product_description"/>
<field column="picture" name="product_picture"/>
</entity>
</document>
</dataConfig>
3.2.2.3.第三步:創(chuàng)建dataimport處理器
--說明:Solr是在solrconfig.xml文件中,通過<requestHandler>標簽定義各類請求處理器
--修改solrconfig.xml,添加如下配置。(加載data-config.xml映射文件)
<requestHandler name="/dataimport"
class="org.apache.solr.handler.dataimport.DataImportHandler">
<lst name="defaults">
<str name="config">data-config.xml</str>
</lst>
</requestHandler>
3.2.2.4.第四步:重啟tomcat,在管理界面測試
--測試清空索引庫,成功?。?!

--測試重新導(dǎo)入數(shù)據(jù),成功?。?!

3.3.Analyzer分析器,配置中文分詞器
3.3.1.Solr自帶分詞器的缺陷
--solr跟Lucene一樣,提供了很多分析器。可以在Analyzer選型下測試分詞效果。

--測試發(fā)現(xiàn):所以的分詞器,對中文支持都不友好。
解決辦法:配置中文分詞器。
3.3.2.Solr配置中文分析器
3.3.2.1.中文分析器選擇
選擇IK中文分詞器。
3.3.2.2.配置步驟
3.3.2.2.1.第一步:添加IkAnalyze的jar依賴
--把IKAnalyzer2012FF_u1.jar添加到solr/WEB-INF/lib目錄下。
3.3.2.2.2.第二步:加載IkAnalyzer的核心配置文件
--拷貝IkAnalyzer的配置文件到solr/WEB-INF/classes目錄

3.3.2.2.3.第三步:創(chuàng)建中文分詞器
--在schema.xml中自定義一個FieldType,指定中文分詞器IKAnalyzer。
<!-- IKAnalyzer-->
<fieldType name="text_ik" class="solr.TextField">
<analyzer class="org.wltea.analyzer.lucene.IKAnalyzer"/>
</fieldType>
3.3.2.3.測試中文分詞器
3.3.2.3.1.第一步:重啟tomcat
3.3.2.3.2.第二步:在analysis選項卡下,測試分詞效果。成功?。?!

3.3.3.改造業(yè)務(wù)域,使用IK做分詞器
--修改schem.xml文件,修改需要分詞的域的fieldType類型
我們只需要修改product_name、product_description兩個業(yè)務(wù)域即可。
<field name="id" type="string" indexed="true" stored="true" required="true" multiValued="false" />
<field name="product_name" type="text_ik" indexed="true" stored="true"/>
<field name="product_catalog_name" type="string" indexed="true" stored="true" />
<field name="product_price" type="double" indexed="true" stored="true"/>
<field name="product_description" type="text_ik" indexed="true" stored="false" />
<field name="product_picture" type="string" indexed="false" stored="true" />
--重啟tomcat即可。