datadabllp

Custom CMS Search

Jul 19th, 2024
1,912
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.14 KB | None | 0 0
  1. public class Document {
  2.     private String id;
  3.     private String title;
  4.     private String content;
  5.     private LocalDate createdDate;
  6.  
  7.     // getters and setters
  8. }
  9.  
  10. public class CMSIndexer {
  11.     private IndexWriter writer;
  12.  
  13.     public CMSIndexer(Directory indexDirectory) throws IOException {
  14.         Analyzer analyzer = new StandardAnalyzer();
  15.         IndexWriterConfig config = new IndexWriterConfig(analyzer);
  16.         writer = new IndexWriter(indexDirectory, config);
  17.     }
  18.  
  19.     public void indexDocument(Document doc) throws IOException {
  20.         org.apache.lucene.document.Document luceneDoc = new org.apache.lucene.document.Document();
  21.         luceneDoc.add(new StringField("id", doc.getId(), Field.Store.YES));
  22.         luceneDoc.add(new TextField("title", doc.getTitle(), Field.Store.YES));
  23.         luceneDoc.add(new TextField("content", doc.getContent(), Field.Store.NO));
  24.         luceneDoc.add(new LongPoint("created", doc.getCreatedDate().toEpochDay()));
  25.        
  26.         writer.addDocument(luceneDoc);
  27.     }
  28.  
  29.     public void commit() throws IOException {
  30.         writer.commit();
  31.     }
  32. }
  33.  
  34. public class CMSSearcher {
  35.     private IndexSearcher searcher;
  36.  
  37.     public CMSSearcher(Directory indexDirectory) throws IOException {
  38.         DirectoryReader reader = DirectoryReader.open(indexDirectory);
  39.         searcher = new IndexSearcher(reader);
  40.     }
  41.  
  42.     public List<Document> search(String queryString, int numResults) throws ParseException, IOException {
  43.         QueryParser parser = new QueryParser("content", new StandardAnalyzer());
  44.         Query query = parser.parse(queryString);
  45.        
  46.         TopDocs results = searcher.search(query, numResults);
  47.         List<Document> documents = new ArrayList<>();
  48.        
  49.         for (ScoreDoc scoreDoc : results.scoreDocs) {
  50.             org.apache.lucene.document.Document doc = searcher.doc(scoreDoc.doc);
  51.             Document document = new Document();
  52.             document.setId(doc.get("id"));
  53.             document.setTitle(doc.get("title"));
  54.             // ... set other fields
  55.             documents.add(document);
  56.         }
  57.        
  58.         return documents;
  59.     }
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment