A Simple working example of indexing and searching

   1 import java.io.IOException;
   2 
   3 import org.apache.lucene.analysis.SimpleAnalyzer;
   4 import org.apache.lucene.analysis.standard.StandardAnalyzer;
   5 import org.apache.lucene.document.Document;
   6 import org.apache.lucene.document.Field;
   7 import org.apache.lucene.index.IndexWriter;
   8 import org.apache.lucene.index.Term;
   9 import org.apache.lucene.search.IndexSearcher;
  10 import org.apache.lucene.search.Query;
  11 import org.apache.lucene.search.TermQuery;
  12 import org.apache.lucene.search.TopDocs;
  13 import org.apache.lucene.store.RAMDirectory;
  14 
  15 public class LuceneTest {
  16 
  17         public static void main(String[] args) throws IOException {
  18             RAMDirectory directory = new RAMDirectory();
  19             IndexWriter writer = 
  20               new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED);
  21                 
  22             Document doc = new Document(); 
  23             doc.add(new Field("partnum", "Q36", Field.Store.YES, Field.Index.NOT_ANALYZED));   
  24             doc.add(new Field("description", "Illidium Space Modulator", Field.Store.YES, Field.Index.ANALYZED)); 
  25             writer.addDocument(doc); 
  26             writer.close();
  27 
  28             IndexSearcher searcher = new IndexSearcher(directory);
  29             Query query = new TermQuery(new Term("partnum", "Q36"));   
  30             TopDocs rs = searcher.search(query, null, 10);
  31             System.out.println(rs.totalHits);
  32 
  33             Document firstHit = searcher.doc(rs.scoreDocs[0].doc);
  34             System.out.println(firstHit.getField("partnum").name());
  35         }
  36 }