Here are the detailed steps to integrate Lucene with Spring Boot:
Add dependencies
Add Lucene's dependencies to the Spring Boot project file. The commonly used core dependencies and Chinese word segmenter dependencies are as follows:
<dependency> <groupId></groupId> <artifactId>lucene-core</artifactId> <version>8.11.0</version> </dependency> <dependency> <groupId></groupId> <artifactId>lucene-analyzers-common</artifactId> <version>8.11.0</version> </dependency> <dependency> <groupId></groupId> <artifactId>ik-analyzer</artifactId> <version>20200623</version> </dependency>
Create a configuration class
Create a configuration class to configure Lucene's related components, such as index directories, word segmenters, etc.:
import ; import ; import ; import ; import ; import ; import ; @Configuration public class LuceneConfig { private final String indexPath = "indexDir"; // Index storage path @Bean public Directory directory() throws Exception { return ((indexPath)); } @Bean public Analyzer analyzer() { return new StandardAnalyzer(); // Can be replaced with other word participles, such as IKAnalyzer } }
Create entity class
Create an entity class based on actual needs to represent the document object to be indexed, for example:
public class Book { private String id; private String title; private String author; private String content; // Omit getter, setter and other methods}
Create index service class
Create a service class to handle index-related operations, such as creating indexes, adding documents, deleting documents, etc.:
import ; import ; import ; import .*; import .*; import ; import ; import ; import ; import ; import ; @Service public class LuceneIndexService { @Autowired private Directory directory; @Autowired private Analyzer analyzer; // Create an index 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(); (new TextField("id", (), )); (new TextField("title", (), )); (new TextField("author", (), )); (new TextField("content", (), )); (doc); } (); } // Add document to index public void addDocument(Book book) throws IOException { IndexWriterConfig config = new IndexWriterConfig(analyzer); IndexWriter writer = new IndexWriter(directory, config); Document doc = new Document(); (new TextField("id", (), )); (new TextField("title", (), )); (new TextField("author", (), )); (new TextField("content", (), )); (doc); (); } // Delete the document public void deleteDocument(String id) throws IOException { IndexWriterConfig config = new IndexWriterConfig(analyzer); IndexWriter writer = new IndexWriter(directory, config); (new Term("id", id)); (); (); } }
Create a search service class
Create a service class to handle search-related operations, such as simple search, highlight search, etc.:
import ; import ; import ; import ; import .*; import .*; import ; import ; import ; import ; import ; import ; import ; @Service public class LuceneSearchService { @Autowired private Directory directory; @Autowired private Analyzer analyzer; // Simple search public List<Document> search(String queryStr) throws Exception { DirectoryReader reader = (directory); IndexSearcher searcher = new IndexSearcher(reader); QueryParser parser = new QueryParser("content", analyzer); Query query = (queryStr); TopDocs results = (query, 10); List<Document> docs = new ArrayList<>(); for (ScoreDoc scoreDoc : ) { (()); } (); return docs; } // Highlight search public List<Map<String, String>> searchWithHighlight(String queryStr) throws Exception { DirectoryReader reader = (directory); IndexSearcher searcher = new IndexSearcher(reader); QueryParser parser = new QueryParser("content", analyzer); Query query = (queryStr); TopDocs results = (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 : ) { Document doc = (); String content = ("content"); TokenStream tokenStream = ("content", new StringReader(content)); String highlightedText = (tokenStream, content); Map<String, String> docMap = new HashMap<>(); ("id", ("id")); ("title", ("title")); ("author", ("author")); ("content", highlightedText != null ? highlightedText : content); (docMap); } (); return docs; } }
Create a controller class
Create a controller class that handles HTTP requests and calls the corresponding service class method:
import ; import .*; import ; import ; import ; @RestController @RequestMapping("/search") public class SearchController { @Autowired private LuceneIndexService luceneIndexService; @Autowired private LuceneSearchService luceneSearchService; // Create an index @PostMapping("/index") public String createIndex(@RequestBody List<Book> bookList) { try { (bookList); return "Index creation successfully"; } catch (IOException e) { (); return "Index creation failed"; } } // Search results @GetMapping public List<Document> search(@RequestParam String query) { try { return (query); } catch (Exception e) { (); return new ArrayList<>(); } } // Highlight search @GetMapping("/highlight") public List<Map<String, String>> searchWithHighlight(@RequestParam String query) { try { return (query); } catch (Exception e) { (); return new ArrayList<>(); } } }
Example of usage
In addition, the above code can be extended and optimized according to actual needs, such as adding more complex query conditions, implementing paging functions, optimizing index performance, etc.
Create an index: After starting the Spring Boot application, send a POST request to http://localhost:8080/search/index, and the request body contains the list of books to be indexed, such as:
[ { "id": "1", "title": " Lucene in Action ", "author": "Robert Muir", "content": "Lucene is a search library from Apache" }, { "id": "2", "title": "Java Programming Thoughts", "author": "Bruce Eckel", "content": "Java is a programming language" } ]
Simple search: Send a GET request to http://localhost:8080/search/?query=Java to search for documents related to "Java".
Highlight search: Send a GET request to http://localhost:8080/search/highlight/?query=Java, and you can search for documents related to "Java", and the "Java" in the search results will be highlighted.
This is the article about this detailed guide on springboot integration Lucene. For more related springboot integration Lucene content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!