Solr與Spring Boot整合 - Viithiisys
在本教程中,我將向您展示如何通過將Solr與Spring Boot整合來改進搜尋。Spring-data-solr 是Spring Data的擴充套件,用於將Solr與Spring Boot starter整合。
什麼是Solr
Apache Solr既是搜尋引擎又是支援SQL的分散式文件資料庫。Solr核心是個搜尋引擎,但遠不止於此。它是一個具有事務支援的NoSQL資料庫。
步驟:
- 配置Solr
- 建立Solr文件
- 建立Solr儲存庫
注意:github專案中 提供了Solr REST API的完整示例。
配置Solr
你可以在這裡 下載Solr
基本Solr命令:
Directory solr/solr-5.3.1 Start Solr: ./bin/solr start Stop Solr: ./bin/solr stop Check Logs: tail -f server/logs/solr.log Start Solr on a different port: ./bin/solr start -p 2000
執行Solr:
cd solr/solr-5.3.1 ./bin/solr start
建立Core:
./bin/solr create -c user_core
與Spring Boot Project整合
新增依賴項Maven:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-solr</artifactId> </dependency>
Gradle:
implementation('org.springframework.boot:spring-boot-starter-data-solr')
建立Solr文件:
Solr文件是使用@SolrDocument註釋建立的,其核心是在其中定義的。
@Indexed註釋用於欄位以使其可搜尋。
<b>import</b> org.springframework.data.annotation.Id; <b>import</b> org.springframework.data.solr.core.mapping.Indexed; <b>import</b> org.springframework.data.solr.core.mapping.SolrDocument; <font><i>/** * @author anuragdhunna */</i></font><font> @SolrDocument(solrCoreName = </font><font>"user_core"</font><font>) <b>public</b> <b>class</b> UserDoc { @Id @Indexed <b>private</b> String id; @Indexed(name = </font><font>"username"</font><font>, type = </font><font>"string"</font><font>) <b>private</b> String username; @Indexed(name = </font><font>"email"</font><font>, type = </font><font>"string"</font><font>) <b>private</b> String email; @Indexed(name = </font><font>"phone_number"</font><font>, type = </font><font>"string"</font><font>) <b>private</b> String phoneNumber; </font><font><i>// Getter Setters </i></font><font> } </font>
建立Solr倉儲:
<b>import</b> com.anuragdhunna.solrIntegration.documents.UserDoc; <b>import</b> org.springframework.beans.factory.annotation.Qualifier; <b>import</b> org.springframework.data.solr.repository.Query; <b>import</b> org.springframework.data.solr.repository.SolrCrudRepository; <b>import</b> org.springframework.stereotype.Repository; <b>import</b> java.util.List; <font><i>/** * @author anuragdhunna */</i></font><font> @Repository @Qualifier(</font><font>"userSolrRepo"</font><font>) <b>public</b> <b>interface</b> UserSolrRepo <b>extends</b> SolrCrudRepository<UserDoc, String> { @Query(value = </font><font>"*:*"</font><font>) List<UserDoc> getUsers(); } </font>
注意:如果Solr在不同的埠上執行(8983),請在application.properties檔案中新增一個屬性:
spring.data.solr.host = http:<font><i>//127.0.0.1:3000/solr</i></font><font> </font>
對於完整的API參考,您可以在Github上檢查專案。