import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

import java.io.IOException;

public class HelloLucene {
  public static void main(String[] args) throws IOException, ParseException {
    // 1. create the index
    Directory index = new RAMDirectory();
    IndexWriter w = new IndexWriter(index, new StandardAnalyzer(), true);
    addDoc(w, "Lucene in Action");
    addDoc(w, "Lucene for Dummies");
    addDoc(w, "Managing Gigabytes");
    addDoc(w, "The Art of Computer Science");
    w.close();

    // 2. query
    String querystr = args.length > 0 ? args[0] : "lucene";
    Query q = new QueryParser("title", new StandardAnalyzer()).parse(querystr);

    // 3. search
    IndexSearcher s = new IndexSearcher(index);
    Hits hits = s.search(q);

    // 4. display results
    System.out.println("Found " + hits.length() + " hits.");
    for(int i=0;i<hits.length();++i) {
      System.out.println((i + 1) + ". " + hits.doc(i).get("title"));
    }
    s.close();
  }

  private static void addDoc(IndexWriter w, String value) throws IOException {
    Document doc = new Document();
    doc.add(new Field("title", value, Field.Store.YES, Field.Index.TOKENIZED));
    w.addDocument(doc);
  }
}
