
// require
import java.io.*;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.FilterIndexReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.*;

public class Search {

	public static void main(String[] args) throws Exception {
	
		// check for command line input
		if ( args.length == 0 ) {
		
			System.out.println( "Usage: java Search <query>" );
			System.exit(0);
		
		}
		
		// initialize
		String field       = "fulltext";
		String queries     = args[ 0 ];
		IndexReader reader = IndexReader.open( "index" );
		Searcher searcher  = new IndexSearcher( reader );
		Analyzer analyzer  = new StandardAnalyzer();
		QueryParser parser = new QueryParser( field, analyzer );
		
		// create a query, search, and display number of hits
		Query query = parser.parse( queries );
		Hits hits = searcher.search( query );
		System.out.println( "Your search (" + query.toString( field ) + ") found " + hits.length() + " documents." );    
	
		// display each hit
		for ( int i = 0; i < hits.length(); i++ ) {
		
			Document doc = hits.doc( i );
			System.out.println( "       Result: " + i );
			System.out.println( "       Author: " + doc.get( "author" ));
			System.out.println( "        Title: " + doc.get( "title" ));
			System.out.println( "  Call number: " + doc.get( "callnumber" ));
			System.out.println( "" );
			
		}
		
	}

}
