Example usage for org.apache.lucene.index DirectoryReader indexExists

List of usage examples for org.apache.lucene.index DirectoryReader indexExists

Introduction

In this page you can find the example usage for org.apache.lucene.index DirectoryReader indexExists.

Prototype

public static boolean indexExists(Directory directory) throws IOException 

Source Link

Document

Returns true if an index likely exists at the specified directory.

Usage

From source file:liredemo.LireDemoFrame.java

License:Open Source License

private void buttonStartMosaicingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonStartMosaicingActionPerformed
    try {/*from   w w  w.  j  a  v  a 2 s .  c  o m*/
        if (!DirectoryReader.indexExists(open(Paths.get(textfieldIndexName.getText())))) {
            JOptionPane.showMessageDialog(this,
                    "Did not find existing index!\n" + "Use the \"Index\" function to create a new one.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        } else if (textfieldMosaicImage.getText().length() > 4) {
            mosaicImage();
        } else {
            JOptionPane.showMessageDialog(this,
                    "Please select an image to create mosaic first.\n"
                            + "Use the \"Open image ...\" button to do this.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:lucene.security.LoadTest.java

License:Apache License

private static void runTest(AccessControlFactory accessControlFactory) throws IOException {
    File file = new File("./src/test/resouces/loadtestindex-" + accessControlFactory.getClass().getName());
    FSDirectory directory = FSDirectory.open(file);
    if (!file.exists() || !DirectoryReader.indexExists(directory)) {
        long s = System.nanoTime();
        createIndex(directory, accessControlFactory);
        long e = System.nanoTime();
        System.out.println("Index Creation Time [" + (e - s) / 1000000.0 + "]");
    }//from  www . j  a  v a 2  s . c o m
    DirectoryReader reader = DirectoryReader.open(directory);

    IndexSearcher searcher = new IndexSearcher(reader);

    SecureIndexSearcher secureIndexSearcher1 = new SecureIndexSearcher(reader, accessControlFactory,
            Arrays.asList("nothing"), Arrays.asList("nothing"), new HashSet<String>());

    SecureIndexSearcher secureIndexSearcher2 = new SecureIndexSearcher(reader, accessControlFactory,
            Arrays.asList("r1"), Arrays.asList("nothing"), new HashSet<String>());

    MatchAllDocsQuery query = new MatchAllDocsQuery();
    for (int p = 0; p < 10; p++) {
        hitEnterToContinue();
        runSearch(searcher, query);
        hitEnterToContinue();
        runSearch(secureIndexSearcher1, query);
        hitEnterToContinue();
        runSearch(secureIndexSearcher2, query);
    }
}

From source file:luceneGazateer.EntryData.java

License:Apache License

public ArrayList<EntryData> searchDocuments(String indexerPath, String inputRecord, DocType recordType)
        throws IOException {

    File indexfile = new File(indexerPath);
    indexDir = FSDirectory.open(indexfile.toPath());

    //inputRecord.replace(","," ");
    if (!DirectoryReader.indexExists(indexDir)) {
        LOG.log(Level.SEVERE, "No Lucene Index Dierctory Found, Invoke indexBuild() First !");
        System.out.println("No Lucene Index Dierctory Found, Invoke indexBuild() First !");
        System.exit(1);//from   w w w .  j  a va2  s  . co  m
    }

    IndexReader reader = DirectoryReader.open(indexDir);

    IndexSearcher searcher = new IndexSearcher(reader);

    Query q = null;

    HashMap<String, ArrayList<ArrayList<String>>> allCandidates = new HashMap<String, ArrayList<ArrayList<String>>>();

    if (!allCandidates.containsKey(inputRecord)) {
        try {
            ArrayList<ArrayList<String>> topHits = new ArrayList<ArrayList<String>>();
            //System.out.println("query is : "+inputRecord);
            q = new MultiFieldQueryParser(new String[] { "DATA" }, analyzer).parse(inputRecord);

            TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage);
            searcher.search(q, collector);
            ScoreDoc[] hits = collector.topDocs().scoreDocs;
            for (int i = 0; i < hits.length; ++i) {
                ArrayList<String> tmp1 = new ArrayList<String>();
                int docId = hits[i].doc;
                Document d;
                try {
                    d = searcher.doc(docId);
                    tmp1.add(d.get("ID"));
                    tmp1.add(d.get("DATA"));
                    tmp1.add(((Float) hits[i].score).toString());

                } catch (IOException e) {
                    e.printStackTrace();
                }
                topHits.add(tmp1);
            }
            allCandidates.put(inputRecord, topHits);
        } catch (org.apache.lucene.queryparser.classic.ParseException e) {
            e.printStackTrace();
        }
    }

    ArrayList<EntryData> resolvedEntities = new ArrayList<EntryData>();
    pickBestCandidates(resolvedEntities, allCandidates);
    reader.close();

    return resolvedEntities;

}

From source file:net.sf.logsaw.index.internal.ARunWithIndexReader.java

License:Open Source License

/**
 * Opens a fresh index reader.//w ww .  jav  a2  s.c om
 * @param log the log resource
 * @return a new index reader or <code>null</code>
 * @throws IOException if an error occurred
 */
protected IndexReader openReader(ILogResource log) throws IOException {
    IndexReader reader = null;
    Directory dir = FSDirectory.open(IndexPlugin.getDefault().getIndexFile(log));
    if (DirectoryReader.indexExists(dir)) {
        logger.info("Opening index reader for '" + log.getName() + "'..."); //$NON-NLS-1$ //$NON-NLS-2$
        reader = DirectoryReader.open(dir);
    }
    return reader;
}

From source file:net.simpleframework.ado.lucene.AbstractLuceneManager.java

License:Apache License

@Override
public boolean indexExists() {
    try {//  w w w.  j a v a2 s.  c  o  m
        return DirectoryReader.indexExists(directory);
    } catch (final IOException e) {
        throw ADOException.of(e);
    }
}

From source file:net.stargraph.core.impl.lucene.LuceneSearcher.java

License:Open Source License

private synchronized IndexSearcher getLuceneSearcher() {
    try {//from   ww w. jav  a2s. c  o m
        if (indexReader == null) {
            if (!DirectoryReader.indexExists(directory)) {
                return null;
            }
            indexReader = DirectoryReader.open(directory);
            indexSearcher = new IndexSearcher(indexReader);
        }
        return indexSearcher;
    } catch (IOException e) {
        throw new StarGraphException(e);
    }
}

From source file:NewsIR_search.CumulativeIndexer.java

public CumulativeIndexer() throws IOException, ClassCastException, ClassNotFoundException {

    String fname;//from   w  w w  .j ava 2s.c  o  m

    GetProjetBaseDirAndSetProjectPropFile setPropFile = new GetProjetBaseDirAndSetProjectPropFile();
    prop = setPropFile.prop;

    // Stanford ner text config
    if (prop.getProperty("ner.classify").contentEquals("true"))
        classifier = CRFClassifier.getClassifier(prop.getProperty("stanford.ner.classifier"));

    if (prop.getProperty("pos.tag").contentEquals("true"))
        tagger = new MaxentTagger(prop.getProperty("stanford.pos.model"));

    setAnalyzer();

    /* property files are loaded */

    /* collection path setting */
    if (prop.containsKey("collSpec")) {
        boolIndexFromSpec = true;
    } else if (prop.containsKey("collPath")) {
        boolIndexFromSpec = false;
        collPath = prop.getProperty("collPath");
        collDir = new File(collPath);
        if (!collDir.exists() || !collDir.canRead()) {
            System.err.println("Collection directory '" + collDir.getAbsolutePath()
                    + "' does not exist or is not readable");
            System.exit(1);
        }
    } else {
        System.err.println("Neither collPath not collSpec is present");
        System.exit(1);
    }
    /* collection path set */

    /* index path setting */
    fname = prop.getProperty("indexPath");
    if (!fname.endsWith("/"))
        fname = fname.concat("/");
    for (int i = 0; i < 10; i++) {
        indexFile[i] = new File(fname.concat(Integer.toString(i + 20) + "/"));
        if (!indexFile[i].exists())
            indexFile[i].mkdirs();
        System.out.println(indexFile[i].getAbsoluteFile());
        Directory[] indexDir = new Directory[10];
        indexDir[i] = FSDirectory.open(indexFile[i]);
        /* index path set */

        if (DirectoryReader.indexExists(indexDir[i])) {
            System.err.println("Index exists in " + indexFile[i].getAbsolutePath());
            boolIndexExists = true;
        } else {
            System.out.println("Will create the index in: " + indexFile[i].getName());
            boolIndexExists = false;
            /* Create a new index in the directory, removing any previous indexed documents */
            IndexWriterConfig iwcfg = new IndexWriterConfig(Version.LATEST, analyzer);
            iwcfg.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
            /*  */
            indexWriter[i] = new IndexWriter(indexDir[i], iwcfg);

        }
    }
    boolDumpIndex = Boolean.parseBoolean(prop.getProperty("dumpIndex", "false"));
    if (boolIndexExists == true && boolDumpIndex == true) {
        dumpPath = prop.getProperty("dumpPath");
    }
}

From source file:NewsIR_search.Indexer.java

public Indexer() throws IOException, ClassCastException, ClassNotFoundException {

    GetProjetBaseDirAndSetProjectPropFile setPropFile = new GetProjetBaseDirAndSetProjectPropFile();
    prop = setPropFile.prop;//from   w w w .  j a  v  a  2  s.co m
    tweet_starts_from_date = Integer.parseInt(prop.getProperty("tweet.starts.from.date", "20"));
    tweet_ends_from_date = Integer.parseInt(prop.getProperty("tweet.ends.from.date", "29"));

    String tmp = prop.getProperty("index_fields", "null");
    if (!tmp.contentEquals("null")) {
        index_fields = new String[tmp.split(",").length];
        for (int i = 0; i < tmp.split(",").length; i++) {
            index_fields[i] = tmp.split(",")[i];
        }
    }

    tmp = prop.getProperty("index_fields_with_analyze", "null");
    if (!tmp.contentEquals("null")) {
        index_fields_with_analyze = new String[tmp.split(",").length];
        for (int i = 0; i < tmp.split(",").length; i++) {
            index_fields_with_analyze[i] = tmp.split(",")[i];
        }
    }

    INDEX_FIELDS = new String[index_fields.length];

    setAnalyzer();

    /* property files are loaded */

    /* collection path setting */
    if (prop.containsKey("collSpec")) {
        boolIndexFromSpec = true;
    } else if (prop.containsKey("collPath")) {
        boolIndexFromSpec = false;
        collPath = prop.getProperty("collPath");
        collDir = new File(collPath);
        if (!collDir.exists() || !collDir.canRead()) {
            System.err.println("Collection directory '" + collDir.getAbsolutePath()
                    + "' does not exist or is not readable");
            System.exit(1);
        }
    } else {
        System.err.println("Neither collPath not collSpec is present");
        System.exit(1);
    }
    /* collection path set */

    String indexBasePath = prop.getProperty("indexPath");
    System.err.println(indexBasePath);
    if (indexBasePath.endsWith("/"))
        ;
    else {
        indexBasePath = indexBasePath + "/";
    }
    System.err.println(indexBasePath);
    /* index path setting */
    indexFile = new File(indexBasePath);
    Directory indexDir = FSDirectory.open(indexFile);

    /* index path set */
    if (DirectoryReader.indexExists(indexDir)) {
        System.err.println("Index exists in " + indexFile.getAbsolutePath());
        boolIndexExists = true;
    } else {
        System.out.println("Will create the index in: " + indexFile.getName());
        boolIndexExists = false;
        /* Create a new index in the directory, removing any previous indexed documents */
        IndexWriterConfig iwcfg = new IndexWriterConfig(Version.LATEST, analyzer);
        iwcfg.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

        /*  */
        indexWriter = new IndexWriter(indexDir, iwcfg);

    }

    boolDumpIndex = Boolean.parseBoolean(prop.getProperty("dumpIndex", "false"));
    if (boolIndexExists == true && boolDumpIndex == true) {
        dumpPath = prop.getProperty("dumpPath");
    }
}

From source file:NewsIR_search.Indexer2ndLevel.java

public Indexer2ndLevel() throws IOException, ClassCastException, ClassNotFoundException {

    GetProjetBaseDirAndSetProjectPropFile setPropFile = new GetProjetBaseDirAndSetProjectPropFile();
    prop = setPropFile.prop;// ww  w . j ava  2 s .  c om

    // if(prop.getProperty("pos.tag","false").toLowerCase().contentEquals("true"))
    postag = new POStag();
    //if(prop.getProperty("ner.classify","false").toLowerCase().contentEquals("true"))
    nertag = new NERtag();
    setAnalyzer();
    bulkTagNo = 200;

    String indexBasePath = prop.getProperty("indexPath");

    if (indexBasePath.endsWith("/"))
        ;
    else {
        indexBasePath = indexBasePath + "/";
    }
    System.err.println(indexBasePath);

    /* index path setting */
    indexFile4reader = new File(indexBasePath);
    indexDir4reader = FSDirectory.open(indexFile4reader);
    indexReader = DirectoryReader.open(indexDir4reader);

    String tmp = new File(indexBasePath).getParentFile().toPath().toString().concat("/2ndLevel/");
    System.err.println("tmp=" + tmp);
    indexFile4writer = new File(tmp);
    Directory indexDir4writer = FSDirectory.open(indexFile4writer);

    /* index path set */
    if (DirectoryReader.indexExists(indexDir4reader)) {
        System.err.println("Index exists in " + indexFile4reader.getAbsolutePath());

        System.out.println("Will create the index in: " + indexFile4writer.getName());
        //boolIndexExists = false;
        boolIndexExists = true;
        /* Create a new index in the directory, removing any previous indexed documents */
        IndexWriterConfig iwcfg = new IndexWriterConfig(Version.LATEST, analyzer);
        iwcfg.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

        /*  */
        indexWriter = new IndexWriter(indexDir4writer, iwcfg);
        System.err.println("Index writer created");
    } else {
        System.err.println("Index Does not exists index in " + indexFile4reader.getAbsolutePath());
        boolIndexExists = false;
        return;
    }

    boolDumpIndex = Boolean.parseBoolean(prop.getProperty("dumpIndex", "false"));
    if (boolIndexExists == true && boolDumpIndex == true) {
        dumpPath = prop.getProperty("dumpPath");
    }
}

From source file:org.apache.blur.lucene.search.FacetQueryTest.java

License:Apache License

private IndexReader createIndex(int docCount, int facetFields, boolean ram)
        throws CorruptIndexException, LockObtainFailedException, IOException {
    Directory directory;// w  ww . j ava 2s.c om
    if (ram) {
        directory = new RAMDirectory();
    } else {
        File dir = new File("./target/tmp/facet_tmp");
        if (dir.exists()) {
            directory = FSDirectory.open(dir);
            if (DirectoryReader.indexExists(directory)) {
                DirectoryReader reader = DirectoryReader.open(directory);
                if (reader.numDocs() == docCount) {
                    return reader;
                }
                reader.close();
                directory.close();
            }
        }
        rmr(dir);
        directory = FSDirectory.open(dir);
    }
    IndexWriterConfig conf = new IndexWriterConfig(LUCENE_VERSION, new KeywordAnalyzer());
    IndexWriter writer = new IndexWriter(directory, conf);
    FieldType fieldType = new FieldType();
    fieldType.setStored(true);
    fieldType.setIndexed(true);
    fieldType.setOmitNorms(true);
    long start = System.nanoTime();
    for (int i = 0; i < docCount; i++) {
        long now = System.nanoTime();
        if (start + TimeUnit.SECONDS.toNanos(5) < now) {
            System.out.println("Indexing doc " + i + " of " + docCount);
            start = System.nanoTime();
        }
        Document document = new Document();
        document.add(new Field("f1", "value", fieldType));
        document.add(new Field("f2", "v" + i, fieldType));
        for (int f = 0; f < facetFields; f++) {
            document.add(new Field("facet" + f, "value", fieldType));
        }
        writer.addDocument(document);
    }
    writer.close();
    return DirectoryReader.open(directory);
}