Example usage for org.apache.lucene.index IndexReader close

List of usage examples for org.apache.lucene.index IndexReader close

Introduction

In this page you can find the example usage for org.apache.lucene.index IndexReader close.

Prototype

@Override
public final synchronized void close() throws IOException 

Source Link

Document

Closes files associated with this index.

Usage

From source file:it.unibz.instasearch.indexing.SearchResultDoc.java

License:Open Source License

private TermFreqVector getTermFreqVector() throws IOException {
    if (termFreqVector == null) {
        IndexReader reader = IndexReader.open(indexDir, true);
        createFreqVect(reader);//from w w  w .j ava2s  . co  m
        reader.close();
    }

    return termFreqVector;
}

From source file:it.unibz.instasearch.indexing.StorageIndexer.java

License:Open Source License

/**
 * Check if the index can be read//w  w w . ja  v a 2  s.co m
 * 
 * @return whether the index is readable
 */
public boolean isReadable() {

    try {
        IndexReader reader = IndexReader.open(getIndexDir(), true);
        reader.close();

    } catch (IOException readingException) {
        return false;
    }

    return true;
}

From source file:it.unibz.instasearch.indexing.StorageIndexer.java

License:Open Source License

public void deleteStorage(IStorage storage) throws Exception {
    IndexReader reader = IndexReader.open(getIndexDir(), false);

    String filePath = storage.getFullPath().toString();

    Term term = Field.FILE.createTerm(filePath);
    reader.deleteDocuments(term);/*from w w w .jav  a 2  s.c om*/

    reader.close();
}

From source file:it.unibz.instasearch.indexing.WorkspaceIndexer.java

License:Open Source License

/**
 * Deletes and re-indexes files in a folder
 * /*ww  w .  j  ava  2s  .  co m*/
 * @param folder
 * @param monitor 
 * @throws Exception 
 */
public void updateFolder(IFolder folder, IProgressMonitor monitor) throws Exception {

    if (!isIndexed())
        return;

    IndexReader reader = IndexReader.open(getIndexDir(), false);
    deleteFolder(reader, folder);
    reader.close();

    if (!folder.isAccessible())
        return;

    resourceCollector.clear();
    resourceCollector.setExcludedDirRegExes(excludedDirRegExes);
    folder.accept(resourceCollector); // get also subfolders

    IndexWriter w = createIndexWriter(false);

    for (IContainer container : resourceCollector.getContainers()) {
        if (isExcluded(container))
            continue;
        indexContainer(w, container, monitor);
    }

    w.close();
}

From source file:it.unibz.instasearch.indexing.WorkspaceIndexer.java

License:Open Source License

/**
 * @param project//from   ww w  .  ja va2 s  . co m
 * @return deletedCount
 * @throws Exception
 */
public int deleteProject(IProject project) throws Exception {
    IndexReader reader = IndexReader.open(getIndexDir(), false);
    String filePath = project.getFullPath().toString();

    Term term = Field.PROJ.createTerm(filePath);
    int deletedCount = reader.deleteDocuments(term);

    reader.close();

    return deletedCount;
}

From source file:it.unipd.dei.ims.lucene.clef.applications.BatchRetrieval.java

License:Apache License

public static void main(String[] args) {

    Properties properties = new Properties();
    InputStream input = null;/*w w  w  .  ja  v a  2 s. c  o m*/
    try {
        if (System.getProperty("properties.path") != null) {
            input = new FileInputStream(System.getProperty("properties.path"));
            properties.load(input);
        } else {
            logger.info("Loading default property file [resources/lucene-clef.properties]");
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            input = loader.getResourceAsStream("lucene-clef.properties");
            properties.load(input);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    properties.putAll(System.getProperties());

    Path indexPath = new File(properties.getProperty("index.path")).toPath();

    Path runPath = new File(properties.getProperty("run.path")).toPath();

    String runTag = properties.getProperty("run.tag");

    String language = properties.getProperty("language");

    String stemmer = properties.getProperty("stemmer");

    String stopsetType = properties.getProperty("stopset.type");

    String stopsetPath = properties.getProperty("stopset.path");

    try {

        Directory directory = new SimpleFSDirectory(indexPath);
        IndexReader reader = DirectoryReader.open(directory);
        IndexSearcher searcher = new IndexSearcher(reader);

        String model = properties.getProperty("run.model").toUpperCase();

        Similarity similarity;

        switch (model) {
        case "BM25":
            similarity = new BM25Similarity(Float.parseFloat(properties.getProperty("bm25.k1", "1.2f")),
                    Float.parseFloat(properties.getProperty("bm25.b", "0.75f")));
            break;
        default:
            throw new UnsupportedOperationException("Model " + model + " not supported yet");

        }

        searcher.setSimilarity(similarity);

        int maxResults = Integer.parseInt(properties.getProperty("maxresults", "1000"));

        SubmissionReport runfile = new SubmissionReport(
                new PrintWriter(Files.newBufferedWriter(runPath, StandardCharsets.UTF_8)), model);

        String topicPath = properties.getProperty("topics.path");

        String[] topicFields = properties.getProperty("topics.fields").split(";");

        CharArraySet stopset = AnalyzerFactory.createStopset(language, stopsetType, stopsetPath);

        QualityQuery qqs[] = getQualityQueries(topicPath, topicFields);

        QualityQueryParser qqParser = new ClefQQParser(topicFields, BuildIndex.BODY_FIELD_NAME, language,
                stemmer, stopset);

        // run the benchmark
        QualityBenchmark qrun = new QualityBenchmark(qqs, qqParser, searcher, BuildIndex.ID_FIELD_NAME);

        qrun.setMaxResults(maxResults);

        QualityStats stats[] = qrun.execute(null, runfile, null);

        reader.close();
        directory.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:jfix.search.FullTextIndex.java

License:Open Source License

public List<E> search(String search) throws Exception {
    try {//from w w w.j  ava  2  s. c om
        ObjectCollector<E> collector = new ObjectCollector<>(objects);
        String query = buildQueryString(search);
        IndexReader indexReader = DirectoryReader.open(indexDirectory);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        indexSearcher.search(queryParser.parse(query), collector);
        indexReader.close();
        return collector.getOutput();
    } catch (Exception e) {
        throw new Exception("Query Syntax Error: " + search);
    }
}

From source file:kde.KDEImplementation.java

public static void main(String[] args) throws IOException, ParseException {
    KDEImplementation kde = new KDEImplementation();
    IndexReader reader = DirectoryReader
            .open(FSDirectory.open(new File("/media/procheta/3CE80E12E80DCADA/newIndex2")));
    reader.close();

}

From source file:l3.SearchFiles.java

License:Apache License

/** Simple command-line based search demo. */
public static void main(String[] args) throws Exception {
    String usage = "Usage:\tjava org.apache.lucene.demo.SearchFiles [-index dir] [-field f] [-repeat n] [-queries file] [-query string] [-raw] [-paging hitsPerPage]\n\nSee http://lucene.apache.org/core/4_1_0/demo/ for details.";
    if (args.length > 0 && ("-h".equals(args[0]) || "-help".equals(args[0]))) {
        System.out.println(usage);
        System.exit(0);//from   ww w . ja  v  a2s . c om
    }

    String index = "index";
    String field = "contents";
    String queries = null;
    int repeat = 0;
    boolean raw = false;
    String queryString = null;
    int hitsPerPage = 10;

    for (int i = 0; i < args.length; i++) {
        if ("-index".equals(args[i])) {
            index = args[i + 1];
            i++;
        } else if ("-field".equals(args[i])) {
            field = args[i + 1];
            i++;
        } else if ("-queries".equals(args[i])) {
            queries = args[i + 1];
            i++;
        } else if ("-query".equals(args[i])) {
            queryString = args[i + 1];
            i++;
        } else if ("-repeat".equals(args[i])) {
            repeat = Integer.parseInt(args[i + 1]);
            i++;
        } else if ("-raw".equals(args[i])) {
            raw = true;
        } else if ("-paging".equals(args[i])) {
            hitsPerPage = Integer.parseInt(args[i + 1]);
            if (hitsPerPage <= 0) {
                System.err.println("There must be at least 1 hit per page.");
                System.exit(1);
            }
            i++;
        }
    }

    IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(index)));
    IndexSearcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_43);

    BufferedReader in = null;
    if (queries != null) {
        in = new BufferedReader(new InputStreamReader(new FileInputStream(queries), "UTF-8"));
    } else {
        in = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
    }
    QueryParser parser = new QueryParser(Version.LUCENE_43, field, analyzer);
    while (true) {
        if (queries == null && queryString == null) { // prompt the user
            System.out.println("Enter query: ");
        }

        String line = queryString != null ? queryString : in.readLine();

        if (line == null || line.length() == -1) {
            break;
        }

        line = line.trim();
        if (line.length() == 0) {
            break;
        }

        Query query = parser.parse(line);
        System.out.println("Searching for: " + query.toString(field));

        if (repeat > 0) { // repeat & time as benchmark
            Date start = new Date();
            for (int i = 0; i < repeat; i++) {
                searcher.search(query, null, 100);
            }
            Date end = new Date();
            System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms");
        }

        doPagingSearch(in, searcher, query, hitsPerPage, raw, queries == null && queryString == null);

        if (queryString != null) {
            break;
        }
    }
    reader.close();
}

From source file:Lab6.LuceneTest.java

public static void main(String[] args) {

    try {// w ww  . ja  v  a2  s .  com
        //   Specify the analyzer for tokenizing text.
        //   The same analyzer should be used for indexing and searching
        StandardAnalyzer analyzer = new StandardAnalyzer();

        //   Code to create the index
        Directory index = new RAMDirectory();

        IndexWriterConfig config = new IndexWriterConfig(analyzer);

        IndexWriter w = new IndexWriter(index, config);
        addDoc(w, " Software Engineering 2", "133");
        addDoc(w, " Software Engineering 1", "CMPE 131:");
        addDoc(w, " Object Oriented Design", "CS 151:");
        addDoc(w, " Advance Data Structures with Java ", "CS 146:");
        addDoc(w, " System Security with Java", "CS 166:");
        addDoc(w, "Lucene demo by teja", "23k43413");
        w.close();

        //   Text to search
        String querystr = args.length > 0 ? args[0] : "Object";

        //   The \"title\" arg specifies the default field to use when no field is explicitly specified in the query
        Query q = new QueryParser("Classes", analyzer).parse(querystr);

        // Searching code
        int hitsPerPage = 10;
        IndexReader reader = DirectoryReader.open(index);
        IndexSearcher searcher = new IndexSearcher(reader);
        TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage);
        searcher.search(q, collector);
        ScoreDoc[] hits = collector.topDocs().scoreDocs;

        //   Code to display the results of search
        System.out.println("Found " + hits.length + " Classes Matching your Requirement");
        for (int i = 0; i < hits.length; ++i) {
            int docId = hits[i].doc;
            Document d = searcher.doc(docId);
            System.out.println((i + 1) + ". " + d.get("Number") + d.get("Classes"));
        }

        // reader can only be closed when there is no need to access the documents any more
        reader.close();
    }

    catch (Exception e) {
        System.out.println(e.getMessage());
    }
}