at.fh_kufstein.InformationRetrievalUebung2.Main.java Source code

Java tutorial

Introduction

Here is the source code for at.fh_kufstein.InformationRetrievalUebung2.Main.java

Source

package at.fh_kufstein.InformationRetrievalUebung2;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
public class Main {

    private static final String INDEX_DIR = "index";
    private static final int MAX_HITS = 1000;
    private static final String SEARCH_FIELD = "contents";

    public static void main(String[] args) {
        try {
            Directory dir = getBookIndexDirectory();
            IndexSearcher searcher = new IndexSearcher(dir);
            QueryParser parser = new QueryParser(Version.LUCENE_30, SEARCH_FIELD, new SimpleAnalyzer());
            Query query = parser.parse(getUserQuery());
            TopDocs docs = searcher.search(query, MAX_HITS);
            printResults(docs);
            searcher.close();
            dir.close();
        } catch (IOException | ParseException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static void printResults(TopDocs docs) {
        System.out.println("Found " + docs.scoreDocs.length + " documents containing the query.");
        System.out.println("#\tDocId\tScore");

        for (int i = 0; i < docs.scoreDocs.length; i++) {
            System.out.println((i + 1) + "\t" + docs.scoreDocs[i].doc + "\t" + docs.scoreDocs[i].score);
        }
    }

    private static String getUserQuery() {
        System.out.println("Please type in your query:");
        Scanner userInput = new Scanner(System.in);
        String query = userInput.nextLine();
        return query;
    }

    public static Directory getBookIndexDirectory() {
        try {
            return FSDirectory.open(new File(INDEX_DIR));
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            System.exit(0);
        }
        return null; //won't happen
    }
}