All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.metaeffekt.artifact.resolver.generic.index.lucene.AbstractLuceneIndex Maven / Gradle / Ivy

There is a newer version: 0.134.0
Show newest version
package org.metaeffekt.artifact.resolver.generic.index.lucene;

import lombok.Getter;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Abstract base class supporting the basic features for lucene index implementations.
 */
@Slf4j
public abstract class AbstractLuceneIndex implements AutoCloseable {

    @Getter
    private final Analyzer analyzer;

    @Getter
    private final Directory directory;

    protected AbstractLuceneIndex(@NonNull File directoryPath, @NonNull Analyzer analyzer) throws IOException {
        this.directory = FSDirectory.open(directoryPath.toPath());
        this.analyzer = analyzer;
    }

    @Override
    public void close() throws Exception {
        analyzer.close();
        directory.close();
    }

    protected TopDocs getTopDocs(Query query, int n, IndexSearcher searcher) throws IOException {
        return searcher.search(query, n);
    }

    @NonNull
    public List runQuery(Query query, int n, IndexSearcher searcher) throws IOException {
        List foundDocuments = new ArrayList<>();

        final TopDocs topDocs = searcher.search(query, n);

        if (topDocs == null || topDocs.scoreDocs == null) {
            return Collections.emptyList();
        }

        final ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            Document foundDoc = searcher.doc(scoreDoc.doc);

            if (foundDoc != null) {
                foundDocuments.add(foundDoc);
            } else {
                log.warn("Got unexpected null document while performing index search.");
            }
        }

        return foundDocuments;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy