Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Document {
- private String id;
- private String title;
- private String content;
- private LocalDate createdDate;
- // getters and setters
- }
- public class CMSIndexer {
- private IndexWriter writer;
- public CMSIndexer(Directory indexDirectory) throws IOException {
- Analyzer analyzer = new StandardAnalyzer();
- IndexWriterConfig config = new IndexWriterConfig(analyzer);
- writer = new IndexWriter(indexDirectory, config);
- }
- public void indexDocument(Document doc) throws IOException {
- org.apache.lucene.document.Document luceneDoc = new org.apache.lucene.document.Document();
- luceneDoc.add(new StringField("id", doc.getId(), Field.Store.YES));
- luceneDoc.add(new TextField("title", doc.getTitle(), Field.Store.YES));
- luceneDoc.add(new TextField("content", doc.getContent(), Field.Store.NO));
- luceneDoc.add(new LongPoint("created", doc.getCreatedDate().toEpochDay()));
- writer.addDocument(luceneDoc);
- }
- public void commit() throws IOException {
- writer.commit();
- }
- }
- public class CMSSearcher {
- private IndexSearcher searcher;
- public CMSSearcher(Directory indexDirectory) throws IOException {
- DirectoryReader reader = DirectoryReader.open(indexDirectory);
- searcher = new IndexSearcher(reader);
- }
- public List<Document> search(String queryString, int numResults) throws ParseException, IOException {
- QueryParser parser = new QueryParser("content", new StandardAnalyzer());
- Query query = parser.parse(queryString);
- TopDocs results = searcher.search(query, numResults);
- List<Document> documents = new ArrayList<>();
- for (ScoreDoc scoreDoc : results.scoreDocs) {
- org.apache.lucene.document.Document doc = searcher.doc(scoreDoc.doc);
- Document document = new Document();
- document.setId(doc.get("id"));
- document.setTitle(doc.get("title"));
- // ... set other fields
- documents.add(document);
- }
- return documents;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment