|
| 1 | +package com.baeldung.lucene; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +import org.apache.lucene.analysis.standard.StandardAnalyzer; |
| 8 | +import org.apache.lucene.document.Document; |
| 9 | +import org.apache.lucene.document.Field; |
| 10 | +import org.apache.lucene.document.TextField; |
| 11 | +import org.apache.lucene.index.DirectoryReader; |
| 12 | +import org.apache.lucene.index.IndexReader; |
| 13 | +import org.apache.lucene.index.IndexWriter; |
| 14 | +import org.apache.lucene.index.IndexWriterConfig; |
| 15 | +import org.apache.lucene.queryparser.classic.ParseException; |
| 16 | +import org.apache.lucene.queryparser.classic.QueryParser; |
| 17 | +import org.apache.lucene.search.IndexSearcher; |
| 18 | +import org.apache.lucene.search.Query; |
| 19 | +import org.apache.lucene.search.ScoreDoc; |
| 20 | +import org.apache.lucene.search.TopDocs; |
| 21 | +import org.apache.lucene.store.Directory; |
| 22 | + |
| 23 | +public class InMemoryLuceneIndex { |
| 24 | + |
| 25 | + private Directory memoryIndex; |
| 26 | + private StandardAnalyzer analyzer; |
| 27 | + |
| 28 | + public InMemoryLuceneIndex(Directory memoryIndex, StandardAnalyzer analyzer) { |
| 29 | + super(); |
| 30 | + this.memoryIndex = memoryIndex; |
| 31 | + this.analyzer = analyzer; |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * |
| 36 | + * @param title |
| 37 | + * @param body |
| 38 | + */ |
| 39 | + public void indexDocument(String title, String body) { |
| 40 | + |
| 41 | + IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer); |
| 42 | + try { |
| 43 | + IndexWriter writter = new IndexWriter(memoryIndex, indexWriterConfig); |
| 44 | + Document document = new Document(); |
| 45 | + |
| 46 | + document.add(new TextField("title", title, Field.Store.YES)); |
| 47 | + document.add(new TextField("body", body, Field.Store.YES)); |
| 48 | + |
| 49 | + writter.addDocument(document); |
| 50 | + writter.close(); |
| 51 | + } catch (IOException e) { |
| 52 | + e.printStackTrace(); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + public List<Document> searchIndex(String inField, String queryString) { |
| 57 | + try { |
| 58 | + Query query = new QueryParser(inField, analyzer).parse(queryString); |
| 59 | + |
| 60 | + IndexReader indexReader = DirectoryReader.open(memoryIndex); |
| 61 | + IndexSearcher searcher = new IndexSearcher(indexReader); |
| 62 | + TopDocs topDocs = searcher.search(query, 10); |
| 63 | + List<Document> documents = new ArrayList<>(); |
| 64 | + for (ScoreDoc scoreDoc : topDocs.scoreDocs) { |
| 65 | + documents.add(searcher.doc(scoreDoc.doc)); |
| 66 | + } |
| 67 | + |
| 68 | + return documents; |
| 69 | + } catch (IOException | ParseException e) { |
| 70 | + e.printStackTrace(); |
| 71 | + } |
| 72 | + return null; |
| 73 | + |
| 74 | + } |
| 75 | + |
| 76 | +} |
| 77 | + |
| 78 | + |
0 commit comments