springboot集成Lucene的詳細指南
以下是 Spring Boot 集成 Lucene 的詳細步驟:
添加依賴
在 Spring Boot 項目的 pom.xml 文件中添加 Lucene 的依賴,常用的核心依賴和中文分詞器依賴如下:
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>8.11.0</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>8.11.0</version>
</dependency>
<dependency>
<groupId>org.wltea</groupId>
<artifactId>ik-analyzer</artifactId>
<version>20200623</version>
</dependency>
創(chuàng)建配置類
創(chuàng)建一個配置類,對 Lucene 的相關(guān)組件進行配置,如索引目錄、分詞器等:
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.nio.file.Paths;
@Configuration
public class LuceneConfig {
private final String indexPath = "indexDir"; // 索引存儲路徑
@Bean
public Directory directory() throws Exception {
return FSDirectory.open(Paths.get(indexPath));
}
@Bean
public Analyzer analyzer() {
return new StandardAnalyzer(); // 可替換為其他分詞器,如 IKAnalyzer
}
}創(chuàng)建實體類
根據(jù)實際需求創(chuàng)建一個實體類,用于表示要索引的文檔對象,例如:
public class Book {
private String id;
private String title;
private String author;
private String content;
// 省略getter、setter等方法
}
創(chuàng)建索引服務(wù)類
創(chuàng)建一個服務(wù)類,用于處理索引相關(guān)的操作,如創(chuàng)建索引、添加文檔、刪除文檔等:
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class LuceneIndexService {
@Autowired
private Directory directory;
@Autowired
private Analyzer analyzer;
// 創(chuàng)建索引
public void createIndex(List<Book> bookList) throws IOException {
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter writer = new IndexWriter(directory, config);
for (Book book : bookList) {
Document doc = new Document();
doc.add(new TextField("id", book.getId(), Field.Store.YES));
doc.add(new TextField("title", book.getTitle(), Field.Store.YES));
doc.add(new TextField("author", book.getAuthor(), Field.Store.YES));
doc.add(new TextField("content", book.getContent(), Field.Store.YES));
writer.addDocument(doc);
}
writer.close();
}
// 添加文檔到索引
public void addDocument(Book book) throws IOException {
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter writer = new IndexWriter(directory, config);
Document doc = new Document();
doc.add(new TextField("id", book.getId(), Field.Store.YES));
doc.add(new TextField("title", book.getTitle(), Field.Store.YES));
doc.add(new TextField("author", book.getAuthor(), Field.Store.YES));
doc.add(new TextField("content", book.getContent(), Field.Store.YES));
writer.addDocument(doc);
writer.close();
}
// 刪除文檔
public void deleteDocument(String id) throws IOException {
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter writer = new IndexWriter(directory, config);
writer.deleteDocuments(new Term("id", id));
writer.forceMergeDeletes();
writer.close();
}
}創(chuàng)建搜索服務(wù)類
創(chuàng)建一個服務(wù)類,用于處理搜索相關(guān)的操作,如簡單搜索、高亮搜索等:
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.highlight.*;
import org.apache.lucene.store.Directory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class LuceneSearchService {
@Autowired
private Directory directory;
@Autowired
private Analyzer analyzer;
// 簡單搜索
public List<Document> search(String queryStr) throws Exception {
DirectoryReader reader = DirectoryReader.open(directory);
IndexSearcher searcher = new IndexSearcher(reader);
QueryParser parser = new QueryParser("content", analyzer);
Query query = parser.parse(queryStr);
TopDocs results = searcher.search(query, 10);
List<Document> docs = new ArrayList<>();
for (ScoreDoc scoreDoc : results.scoreDocs) {
docs.add(searcher.doc(scoreDoc.doc));
}
reader.close();
return docs;
}
// 高亮搜索
public List<Map<String, String>> searchWithHighlight(String queryStr) throws Exception {
DirectoryReader reader = DirectoryReader.open(directory);
IndexSearcher searcher = new IndexSearcher(reader);
QueryParser parser = new QueryParser("content", analyzer);
Query query = parser.parse(queryStr);
TopDocs results = searcher.search(query, 10);
List<Map<String, String>> docs = new ArrayList<>();
SimpleHTMLFormatter htmlFormatter = new SimpleHTMLFormatter("<span style='color:red'>", "</span>");
Highlighter highlighter = new Highlighter(htmlFormatter, new QueryScorer(query));
for (ScoreDoc scoreDoc : results.scoreDocs) {
Document doc = searcher.doc(scoreDoc.doc);
String content = doc.get("content");
TokenStream tokenStream = analyzer.tokenStream("content", new StringReader(content));
String highlightedText = highlighter.getBestFragment(tokenStream, content);
Map<String, String> docMap = new HashMap<>();
docMap.put("id", doc.get("id"));
docMap.put("title", doc.get("title"));
docMap.put("author", doc.get("author"));
docMap.put("content", highlightedText != null ? highlightedText : content);
docs.add(docMap);
}
reader.close();
return docs;
}
}創(chuàng)建控制器類
創(chuàng)建一個控制器類,用于處理 HTTP 請求,并調(diào)用相應(yīng)的服務(wù)類方法:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/search")
public class SearchController {
@Autowired
private LuceneIndexService luceneIndexService;
@Autowired
private LuceneSearchService luceneSearchService;
// 創(chuàng)建索引
@PostMapping("/index")
public String createIndex(@RequestBody List<Book> bookList) {
try {
luceneIndexService.createIndex(bookList);
return "索引創(chuàng)建成功";
} catch (IOException e) {
e.printStackTrace();
return "索引創(chuàng)建失敗";
}
}
// 搜索結(jié)果
@GetMapping
public List<Document> search(@RequestParam String query) {
try {
return luceneSearchService.search(query);
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<>();
}
}
// 高亮搜索
@GetMapping("/highlight")
public List<Map<String, String>> searchWithHighlight(@RequestParam String query) {
try {
return luceneSearchService.searchWithHighlight(query);
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<>();
}
}
}使用示例
此外,還可以根據(jù)實際需求對上述代碼進行擴展和優(yōu)化,例如添加更復(fù)雜的查詢條件、實現(xiàn)分頁功能、優(yōu)化索引的性能等。
創(chuàng)建索引 :啟動 Spring Boot 應(yīng)用后,發(fā)送一個 POST 請求到http://localhost:8080/search/index,請求體中包含要索引的圖書列表,如:
[
{
"id": "1",
"title": " Lucene in Action ",
"author": "Robert Muir",
"content": "Lucene is a search library from Apache"
},
{
"id": "2",
"title": " Java編程思想 ",
"author": "Bruce Eckel",
"content": "Java is a programming language"
}
]
簡單搜索 :發(fā)送一個 GET 請求到http://localhost:8080/search/?query=Java,即可搜索出與“Java”相關(guān)的文檔。
高亮搜索 :發(fā)送一個 GET 請求到http://localhost:8080/search/highlight/?query=Java,即可搜索出與“Java”相關(guān)的文檔,并且搜索結(jié)果中的“Java”會以高亮顯示。
到此這篇關(guān)于springboot集成Lucene的詳細指南的文章就介紹到這了,更多相關(guān)springboot集成Lucene內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文詳解Elasticsearch和MySQL之間的數(shù)據(jù)同步問題
Elasticsearch中的數(shù)據(jù)是來自于Mysql數(shù)據(jù)庫的,因此當(dāng)數(shù)據(jù)庫中的數(shù)據(jù)進行增刪改后,Elasticsearch中的數(shù)據(jù),索引也必須跟著做出改變。本文主要來和大家探討一下Elasticsearch和MySQL之間的數(shù)據(jù)同步問題,感興趣的可以了解一下2023-04-04
Java util.List如何實現(xiàn)列表分段處理
這篇文章主要介紹了Java util.List如何實現(xiàn)列表分段處理,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
Spring Boot + Kotlin整合MyBatis的方法教程
前幾天由于工作需要,便開始學(xué)習(xí)了kotlin,java基礎(chǔ)扎實學(xué)起來也還算比較快,對于kotlin這個編程語言自然是比java有趣一些,下面這篇文章主要給大家介紹了關(guān)于Spring Boot + Kotlin整合MyBatis的方法教程,需要的朋友可以參考下。2018-01-01
redis分布式鎖詳解Redisson(RedissonClient)
Redisson提供了多種鎖和實用方法,實現(xiàn)了對數(shù)據(jù)的增刪改查等操作,RedissonClient接口的實現(xiàn)類中,重點介紹了重入鎖、公平鎖和聯(lián)鎖的實現(xiàn)方式,在實際應(yīng)用中,設(shè)置定時過期的分布式鎖需要考慮服務(wù)宕機或重啟的問題,可以通過記錄鎖的Set來解決2025-11-11
Java窗體動態(tài)加載磁盤文件的實現(xiàn)方法
這篇文章主要介紹了Java窗體動態(tài)加載磁盤文件的實現(xiàn)方法,需要的朋友可以參考下2014-03-03
springboot多線程并發(fā)執(zhí)行任務(wù)
本文主要介紹了springboot多線程并發(fā)執(zhí)行任務(wù),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2026-03-03

