springboot集成Lucene的詳細(xì)指南
以下是 Spring Boot 集成 Lucene 的詳細(xì)步驟:
添加依賴
在 Spring Boot 項(xiàng)目的 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)建一個(gè)配置類,對(duì) Lucene 的相關(guān)組件進(jì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"; // 索引存儲(chǔ)路徑
@Bean
public Directory directory() throws Exception {
return FSDirectory.open(Paths.get(indexPath));
}
@Bean
public Analyzer analyzer() {
return new StandardAnalyzer(); // 可替換為其他分詞器,如 IKAnalyzer
}
}創(chuàng)建實(shí)體類
根據(jù)實(shí)際需求創(chuàng)建一個(gè)實(shí)體類,用于表示要索引的文檔對(duì)象,例如:
public class Book {
private String id;
private String title;
private String author;
private String content;
// 省略getter、setter等方法
}
創(chuàng)建索引服務(wù)類
創(chuàng)建一個(gè)服務(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)建一個(gè)服務(wù)類,用于處理搜索相關(guān)的操作,如簡(jiǎ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;
// 簡(jiǎn)單搜索
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)建一個(gè)控制器類,用于處理 HTTP 請(qǐng)求,并調(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ù)實(shí)際需求對(duì)上述代碼進(jìn)行擴(kuò)展和優(yōu)化,例如添加更復(fù)雜的查詢條件、實(shí)現(xiàn)分頁(yè)功能、優(yōu)化索引的性能等。
創(chuàng)建索引 :?jiǎn)?dòng) Spring Boot 應(yīng)用后,發(fā)送一個(gè) POST 請(qǐng)求到http://localhost:8080/search/index,請(qǐng)求體中包含要索引的圖書列表,如:
[
{
"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"
}
]
簡(jiǎn)單搜索 :發(fā)送一個(gè) GET 請(qǐng)求到http://localhost:8080/search/?query=Java,即可搜索出與“Java”相關(guān)的文檔。
高亮搜索 :發(fā)送一個(gè) GET 請(qǐng)求到http://localhost:8080/search/highlight/?query=Java,即可搜索出與“Java”相關(guān)的文檔,并且搜索結(jié)果中的“Java”會(huì)以高亮顯示。
到此這篇關(guān)于springboot集成Lucene的詳細(xì)指南的文章就介紹到這了,更多相關(guān)springboot集成Lucene內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springBoot整合jwt實(shí)現(xiàn)token令牌認(rèn)證的示例代碼
實(shí)施Token驗(yàn)證的方法挺多的,還有一些標(biāo)準(zhǔn)方法,比如JWT,本文主要介紹了springBoot整合jwt實(shí)現(xiàn)token令牌認(rèn)證的示例代碼,具有一定的參考價(jià)值,感興趣的可以了解一下2024-08-08
Java并發(fā)編程中的ReentrantLock類詳解
這篇文章主要介紹了Java并發(fā)編程中的ReentrantLock類詳解,ReentrantLock是juc.locks包中的一個(gè)獨(dú)占式可重入鎖,相比synchronized,它可以創(chuàng)建多個(gè)條件等待隊(duì)列,還支持公平/非公平鎖、可中斷、超時(shí)、輪詢等特性,需要的朋友可以參考下2023-12-12
springsecurity基于token的認(rèn)證方式
本文主要介紹了springsecurity基于token的認(rèn)證方式,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08

