1 Solr簡介
1.1 Solr是什么
Solr是一個基於全文檢索的企業級應用服務器。可以輸入一段文字,通過分詞檢索數據。它是單獨的服務,部署在 tomcat。
1.2 為什么需要Solr
問題:我們已經學過Lucene,為什么還要學習solr?
Lucene是一個工具包,不能單獨運行,需要導入到java代碼中。Solr可以獨立運行在tomcat容器中,通過http協議,以接口的方式對外提供服務,java代碼只需要專注於業務的處理就可以。
1.3 Solr目錄結構說明
- bin:solr的運行腳本
- contrib:solr的一些擴展jar包,用於增強solr的功能
- dist:該目錄包含build過程中產生的jar文件,以及相關的依賴文件
- example:solr工程的例子目錄
- licenses:solr相關的一些許可信息
2 入門示例
2.1 需求
將數據庫的數據導入 solr 中,實現查詢功能
2.2 配置步驟
2.2.1 啟動 solr
進入 solr 解壓路徑下的 bin 目錄,按 shift + 鼠標右鍵,選擇在此次打開命令行工具
輸入命令: .\solr start
啟動 solr 服務
使用瀏覽器訪問 localhost:8983 即可進入后台控制頁面。
2.2.2 配置 solr core
繼續使用命令工具創建一個 core,core 就相當於一個 solr 的項目實例。
命令:solr create -c <core_name>
成功創建后,可以在 solr-8.2.0/server/solr/<core_name>
目錄下看到自動生成的默認配置文件
創建完成后,重新進入后台控制頁面,可以查看到新建的 core
2.2.3 創建java程序訪問solr服務器
步驟說明:
- 采集數據
- 將數據轉換成Solr文檔
- 連接solr服務器,將文檔寫入索引庫
2.2.3.1 創建項目,導入 jar 包
需要導入的包有:
- Solrj 核心包:
solr-8.2.0\dist\solr-core-8.2.0.jar
- Solrj 依賴包:
solr-8.2.0\dist\solrj-lib\
目錄下的所有包 - JDBC 驅動包:根據數據庫版本而定,我這里拷的是 mysql 8 的驅動包
項目結構:
2.2.3.2 采集數據
需求采集的字段說明:
- 參與搜索的字段:名稱、價格、商品類別、描述信息
- 參與結果展示的字段:商品id、圖片
(1)創建 pojo
public class Product {
private Integer pid;
private String name;
private String categoryName;
private Double price;
private String description;
private String picture;
//省略 getter、setter、constructor、toString
}
(2)創建 dao
public class ProductDao {
public List<Product> listAll() {
List<Product> products = new ArrayList<>();
//獲取數據庫連接
Connection conn = JdbcUtils.getConnection();
String sql = "select * from `products`";
Statement statement = null;
ResultSet resultSet = null;
try {
//創建 statement
statement = conn.createStatement();
//執行 sql 語句
resultSet = statement.executeQuery(sql);
//循環操作結果集
while (resultSet.next()) {
products.add(new Product(resultSet.getInt("pid"),
resultSet.getString("name"),
resultSet.getString("category_name"),
resultSet.getDouble("price"),
resultSet.getString("description"),
resultSet.getString("picture")));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//關閉資源
if (null != resultSet) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (null != statement) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}
}
return products;
}
}
(3)將數據轉換成 solr 文檔, SolrInputDocument 對象
Solr是通過一個配置文件managed-schema,事先定義域的信息的,需要先定義再使用。
配置文件里面事先定義好了各種 <dynamicField>
,能夠根據命名動態的指定域的類型,也就是 type 屬性。
而域的類型也在此做了定義,用的是 <fieldType>
標簽。(可對比 lucene 理解)
其中,text-general 指定了分詞器,以及一些拓展配置文件
我們可以根據需要,按照上述例子,手動的聲明幾個域,並使用中文分詞。先將 lucene 中的 SmartChineseAnalyzer 的 jar 包拷入文件夾中
再修改 managed-schema 配置文件,添加以下內容
重啟服務器后,可以看到效果
為 dao 添加 getDocuments 方法
public List<SolrInputDocument> getDocuments(List<Product> products) {
List<SolrInputDocument> documents = new ArrayList<>();
products.forEach(product -> {
SolrInputDocument document = new SolrInputDocument();
document.addField("id", product.getPid());//對應solr的uniqueKey
document.addField("product_name", product.getName());
document.addField("product_price", product.getPrice());
document.addField("product_category_name", product.getCategoryName());
document.addField("product_picture", product.getPicture());
document.addField("product_description", product.getDescription());
documents.add(document);
});
return documents;
}
創建索引庫
@Test
public void createIndex() {
//1.創建 HttpSolrClient.Builder 對象,通過它創建客戶端通信
HttpSolrClient.Builder builder = new HttpSolrClient.Builder("http://localhost:8983/solr");
HttpSolrClient solrClient = builder.build();
//2.通過 client 將 document 加入索引庫
ProductDao dao = new ProductDao();
try {
//參數1是 solr core 的名字
solrClient.add("product", dao.getDocuments(dao.listAll()));
solrClient.commit("product");
System.out.println("創建索引庫完成");
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
導入成功后可以在后天控制頁面看到結果
2.2.3.3 搜索索引
@Test
public void queryTest() {
//1.創建 HttpSolrClient.Builder 對象,通過它創建客戶端通信
HttpSolrClient.Builder builder = new HttpSolrClient.Builder("http://localhost:8983/solr");
HttpSolrClient solrClient = builder.build();
//2.創建一個map封裝搜索條件
Map<String, String> queryMap = new HashMap<>();
queryMap.put("q","音樂盒");//關鍵字
queryMap.put("df", "product_name");//默認搜索域
//queryMap.put("sort","id asc");//結果以 id 升序排列,默認以關聯度排序
queryMap.put("rows","20");//默認只有十條
//3.使用map創建 MapSolrParams 對象
SolrParams solrParams = new MapSolrParams(queryMap);
try {
//4.使用客戶端進行查詢
QueryResponse response = solrClient.query("product", solrParams);
//5.提取結果
SolrDocumentList documents = response.getResults();
System.out.println("一共查詢到:" + documents.getNumFound() + "條結果");
//6.循環輸出
documents.forEach(document ->{
System.out.println("編號" + document.get("id") + ":" + document.get("product_name"));
});
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
3 solr管理控制台
3.1 查詢界面說明
可以根據查詢界面各個關鍵字,設置上述代碼 queryMap,實現復雜的查詢功能。key 對應的就是關鍵字,value 就是輸入框內的值。
3.2 安裝DataImport插件
3.2.1 Dataimport插件說明
使用該插件后,可以在管理界面直接從數據庫導入數據到索引庫。(即:一個插件解決入門示例中,創建索引的全部操作)
3.2.2 安裝步驟
(1)拷貝相關 jar 包到文件夾
(2)修改 \solr-8.2.0\server\solr\product\conf\solrconfig.xml
文件,增加以下代碼
(3)在 \solr-8.2.0\server\solr\product\conf\
目錄下新建 DIHconfig.xml 文件,並編寫以下內容
<dataConfig>
<dataSource type="JdbcDataSource"
driver="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/solr?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false"
user="root"
password="password"
/>
<document>
<entity name="product"
query="SELECT * FROM products">
<field column="pid" name="id"/>
<field column="name" name="product_name"/>
<field column="price" name="product_price"/>
<field column="category_name" name="product_category_name"/>
<field column="description" name="product_description"/>
<field column="picture" name="product_picture"/>
</entity>
</document>
</dataConfig>
(4)重啟 solr 服務
3.2.3 測試
(1) 清空索引庫
(2)導入索引庫
我的博客即將同步至騰訊雲+社區,邀請大家一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=9fsyys67r6lo