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

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

Introduction

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

Prototype

public static DirectoryReader open(final IndexCommit commit) throws IOException 

Source Link

Document

Expert: returns an IndexReader reading the index in the given IndexCommit .

Usage

From source file:com.berico.clavin.resolver.impl.lucene.LuceneComponentsFactory.java

License:Apache License

/**
 * Initialize the SearcherManager (and other components).
 * @return This object (it's needlessly fluent!).
 * @throws IOException /*  w ww  .  java 2s . c  om*/
 */
public LuceneComponentsFactory initializeSearcher() throws IOException {

    initializeCommon();

    // instantiate an index searcher
    indexSearcher = new IndexSearcher(DirectoryReader.open(index));

    // override default TF/IDF score to ignore multiple appearances
    indexSearcher.setSimilarity(new BinarySimilarity());

    // Instantiate the searcher manager.
    searcherManager = new SearcherManager(index, null);

    // Do it.
    return this;
}

From source file:com.berico.clavin.resolver.lucene.LuceneLocationResolver.java

License:Apache License

/**
 * Builds a {@link LuceneLocationResolver} by loading a pre-built Lucene
 * index from disk and setting configuration parameters for
 * resolving location names to GeoName objects.
 * //from ww  w.j  a v a 2s.c  o  m
 * @param indexDir            Lucene index directory to be loaded
 * @param maxHitDepth         number of candidate matches to consider
 * @param maxContextWindow      how much context to consider when resolving
 * @throws IOException
 * @throws ParseException
 */
public LuceneLocationResolver(File indexDir, int maxHitDepth, int maxContextWindow)
        throws IOException, ParseException {

    // load the Lucene index directory from disk
    index = FSDirectory.open(indexDir);

    // index employs simple lower-casing & tokenizing on whitespace
    indexAnalyzer = new WhitespaceLowerCaseAnalyzer();
    indexSearcher = new IndexSearcher(DirectoryReader.open(index));

    // override default TF/IDF score to ignore multiple appearances
    indexSearcher.setSimilarity(new BinarySimilarity());

    this.maxHitDepth = maxHitDepth;
    this.maxContextWindow = maxContextWindow;

    // run an initial throw-away query just to "prime the pump" for
    // the cache, so we can accurately measure performance speed
    // per: http://wiki.apache.org/lucene-java/ImproveSearchingSpeed
    indexSearcher.search(
            new AnalyzingQueryParser(Version.LUCENE_40, "indexName", indexAnalyzer).parse("Reston"), null,
            maxHitDepth, populationSort);
}

From source file:com.bericotech.clavin.gazetteer.query.LuceneGazetteer.java

License:Apache License

/**
 * Builds a {@link LuceneGazetteer} by loading a pre-built Lucene
 * index from disk and setting configuration parameters for
 * resolving location names to GeoName objects.
 *
 * @param indexDir              Lucene index directory to be loaded
 * @throws ClavinException      if an error occurs opening the index
 *//*from ww w  .j a v a2s.co m*/
public LuceneGazetteer(final File indexDir) throws ClavinException {
    try {
        // load the Lucene index directory from disk
        index = FSDirectory.open(indexDir);

        indexSearcher = new IndexSearcher(DirectoryReader.open(index));

        // override default TF/IDF score to ignore multiple appearances
        indexSearcher.setSimilarity(new BinarySimilarity());

        // run an initial throw-away query just to "prime the pump" for
        // the cache, so we can accurately measure performance speed
        // per: http://wiki.apache.org/lucene-java/ImproveSearchingSpeed
        indexSearcher.search(
                new AnalyzingQueryParser(Version.LUCENE_4_9, INDEX_NAME.key(), INDEX_ANALYZER).parse("Reston"),
                null, DEFAULT_MAX_RESULTS, POPULATION_SORT);
    } catch (ParseException pe) {
        throw new ClavinException("Error executing priming query.", pe);
    } catch (IOException ioe) {
        throw new ClavinException("Error opening gazetteer index.", ioe);
    }
}

From source file:com.bitranger.parknshop.common.fulltext.SearchCustomer.java

License:Open Source License

public List<PsCustomer> search(String value) throws IOException {
    // get the index
    IndexReader reader = DirectoryReader.open(FSDirectory.open(BuildIndexForItem.getIndexFile()));
    // use this to search
    IndexSearcher indexSearcher = new IndexSearcher(reader);
    // use the queryParser to wrap your request
    QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_45, queryString, analyzer);

    List<PsCustomer> customer = new ArrayList<PsCustomer>();

    Query query = null;//from   w w w.  j av a 2 s  .  co m
    try {
        query = queryParser.parse("title:" + value + "~");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    // we get what we want in the topdocs
    TopDocs topDocs = indexSearcher.search(query, 25);
    System.out.println(":" + topDocs.totalHits + "");
    // ScoreDoc[] scoreDoc = topDocs.scoreDocs;
    for (int i = 0; i < topDocs.scoreDocs.length; i++) {
        Document resultDocument = indexSearcher.doc(topDocs.scoreDocs[i].doc);
        PsCustomer mycustomer = new PsCustomer();
        mycustomer.setNickname(resultDocument.get((indexField[0])));
        mycustomer.setEmail(resultDocument.get((indexField[1])));
        mycustomer.setPassword(resultDocument.get((indexField[2])));
        mycustomer.setGender(Short.valueOf(resultDocument.get((indexField[3]))));
        mycustomer.setName(resultDocument.get((indexField[4])));
        customer.add(mycustomer);

    }
    return customer;
}

From source file:com.bitranger.parknshop.common.fulltext.SearchItem.java

License:Open Source License

public List<PsItem> search(String value) throws IOException {
    // get the index
    IndexReader reader = DirectoryReader.open(FSDirectory.open(BuildIndexForItem.getIndexFile()));
    // use this to search
    IndexSearcher indexSearcher = new IndexSearcher(reader);
    // use the queryParser to wrap your request
    QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_45, queryString, analyzer);

    List<PsItem> item = new ArrayList<PsItem>();

    Query query = null;/*  ww w  . j a  v a2  s  .  c  om*/
    try {
        query = queryParser.parse("title:" + value + "~");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    // we get what we want in the topdocs
    TopDocs topDocs = indexSearcher.search(query, 25);
    System.out.println(":" + topDocs.totalHits + "");
    // ScoreDoc[] scoreDoc = topDocs.scoreDocs;
    for (int i = 0; i < topDocs.scoreDocs.length; i++) {
        Document resultDocument = indexSearcher.doc(topDocs.scoreDocs[i].doc);
        PsItem myitem = new PsItem();
        myitem.setName(resultDocument.get((indexField[0])));
        myitem.setIntroduction(resultDocument.get((indexField[1])));
        myitem.setPrice(Double.valueOf(resultDocument.get((indexField[2]))));
        myitem.setUrlPicture(resultDocument.get((indexField[3])));
        myitem.setExtra1(resultDocument.get((indexField[4])));
        myitem.setExtra2(resultDocument.get((indexField[5])));
        myitem.setCountPurchase(Integer.valueOf(resultDocument.get((indexField[6]))));
        myitem.setCountFavourite(Integer.valueOf(resultDocument.get((indexField[7]))));
        myitem.setCountClick(Integer.valueOf(resultDocument.get((indexField[8]))));
        myitem.setVote(Double.valueOf(resultDocument.get((indexField[9]))));
        item.add(myitem);

    }
    return item;
}

From source file:com.bitranger.parknshop.common.fulltext.SearchOrder.java

License:Open Source License

public List<PsOrder> search(String value) throws IOException {
    // get the index
    IndexReader reader = DirectoryReader.open(FSDirectory.open(BuildIndexForItem.getIndexFile()));
    // use this to search
    IndexSearcher indexSearcher = new IndexSearcher(reader);
    // use the queryParser to wrap your request
    QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_45, queryString, analyzer);

    List<PsOrder> order = new ArrayList<PsOrder>();

    Query query = null;/*w  w  w  .j  a v a  2s . c  o  m*/
    try {
        query = queryParser.parse("title:" + value + "~");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    // we get what we want in the topdocs
    TopDocs topDocs = indexSearcher.search(query, 25);
    System.out.println(":" + topDocs.totalHits + "");
    // ScoreDoc[] scoreDoc = topDocs.scoreDocs;
    for (int i = 0; i < topDocs.scoreDocs.length; i++) {
        Document resultDocument = indexSearcher.doc(topDocs.scoreDocs[i].doc);
        PsOrder myorder = new PsOrder();
        myorder.setId(Integer.valueOf(resultDocument.get((indexField[0]))));
        myorder.setStatus(Short.valueOf(resultDocument.get((indexField[3]))));
        myorder.setTrackingNumber(resultDocument.get((indexField[4])));
        myorder.setPriceTotal(Double.valueOf(resultDocument.get((indexField[9]))));
        order.add(myorder);

    }
    return order;
}

From source file:com.bitranger.parknshop.common.fulltext.SearchSeller.java

License:Open Source License

public List<PsSeller> search(String value) throws IOException {
    // get the index
    IndexReader reader = DirectoryReader.open(FSDirectory.open(BuildIndexForItem.getIndexFile()));
    // use this to search
    IndexSearcher indexSearcher = new IndexSearcher(reader);
    // use the queryParser to wrap your request
    QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_45, queryString, analyzer);

    List<PsSeller> seller = new ArrayList<PsSeller>();

    Query query = null;//from   ww  w  .j a  v a 2s.  c  o m
    try {
        query = queryParser.parse("title:" + value + "~");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    // we get what we want in the topdocs
    TopDocs topDocs = indexSearcher.search(query, 25);
    System.out.println(":" + topDocs.totalHits + "");
    // ScoreDoc[] scoreDoc = topDocs.scoreDocs;
    for (int i = 0; i < topDocs.scoreDocs.length; i++) {
        Document resultDocument = indexSearcher.doc(topDocs.scoreDocs[i].doc);
        PsSeller myseller = new PsSeller();
        myseller.setId(Integer.valueOf(resultDocument.get((indexField[0]))));
        myseller.setNickname(resultDocument.get((indexField[1])));
        myseller.setPersonIdNum(resultDocument.get((indexField[2])));
        myseller.setEmail(resultDocument.get((indexField[3])));
        myseller.setPassword(resultDocument.get((indexField[4])));
        myseller.setStatus(Short.valueOf(resultDocument.get((indexField[5]))));
        seller.add(myseller);

    }
    return seller;
}

From source file:com.bitranger.parknshop.common.fulltext.SearchShop.java

License:Open Source License

public List<PsShop> search(String value) throws IOException {
    // get the index
    IndexReader reader = DirectoryReader.open(FSDirectory.open(BuildIndexForItem.getIndexFile()));
    // use this to search
    IndexSearcher indexSearcher = new IndexSearcher(reader);
    // use the queryParser to wrap your request
    QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_45, queryString, analyzer);

    List<PsShop> shop = new ArrayList<PsShop>();

    Query query = null;// w  w  w  . java 2s.com
    try {
        query = queryParser.parse("title:" + value + "~");
    } catch (ParseException e) {
        e.printStackTrace();
    }
    // we get what we want in the topdocs
    TopDocs topDocs = indexSearcher.search(query, 25);
    System.out.println(":" + topDocs.totalHits + "");
    // ScoreDoc[] scoreDoc = topDocs.scoreDocs;
    for (int i = 0; i < topDocs.scoreDocs.length; i++) {
        Document resultDocument = indexSearcher.doc(topDocs.scoreDocs[i].doc);
        PsShop myshop = new PsShop();
        myshop.setId(Integer.valueOf(resultDocument.get((indexField[0]))));
        myshop.setName(resultDocument.get((indexField[2])));
        myshop.setStatus(Short.valueOf(resultDocument.get((indexField[3]))));
        myshop.setIntroduction(resultDocument.get((indexField[4])));
        myshop.setVote(Double.valueOf(resultDocument.get((indexField[6]))));
        shop.add(myshop);

    }

    return shop;
}

From source file:com.bluedragon.search.collection.Collection.java

License:Open Source License

/**
 * Retrieves the IndexSearcher object.  This object is cached against this collection and is intended
 * to be used amongst several threads.   This is the recommended approach.
 * /*from   w  ww  .  j  a v  a  2s. com*/
 * If new content is added to this collection then it won't be available for searching until a new
 * indexsearcher is created
 * 
 * @return
 * @throws CorruptIndexException
 * @throws IOException
 */
public synchronized IndexSearcher getIndexSearcher() throws CorruptIndexException, IOException {
    lastUsed = System.currentTimeMillis();

    if (indexsearcher != null)
        return indexsearcher;

    setDirectory();
    indexsearcher = new IndexSearcher(DirectoryReader.open(directory));

    totalDocs = indexsearcher.getIndexReader().numDocs();

    return indexsearcher;
}

From source file:com.chenyi.langeasy.lucene.SearchTest.java

License:Apache License

public static void search() throws Exception {
    String index = "F:/Personal/ws_indigo/lucene/index";
    String field = "contents";

    IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
    IndexSearcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();

    QueryParser parser = new QueryParser(field, analyzer);
    String[] wordLst = new String[] { "abaft", "abase", "abnegation", "abominate", "abridge", "adjure",
            "adroit", "adulterate", "aggrandize", "allegory", "amalgam", "amalgamate", "amiable", "amortize",
            "anachronism", "apposite", "approbatory", "archetype", "arrogate", "artifice", "aseptic",
            "asperity", "assay", "attenuate", "baneful", "bauble", "behoove", "bemuse", "besmirch", "betroth",
            "boor", "bumptious", "bungler", "burgeon", "canard", "castigate", "catharsis", "cavil", "chaffing",
            "chary", "choleric", "chortle", "churlishness", "circumlocution", "circumlocutory", "cloture",
            "coda", "coffer", "cogitate", "cognate", "cognizant", "comeliness", "commiserate", "complaisance",
            "conjoin", "connotative", "contumacious", "contusion", "conviviality", "convoke", "corpulence",
            "curmudgeon", "dally", "dauntless", "decadence", "decisiveness", "delineate", "deliquesce",
            "denigrate", "deprecate", "depredation", "descant", "despoil", "determinate", "dichotomy",
            "digress", "dilettante", "disapprobation", "disheartened", "disputatious", "dissemble", "dissonant",
            "distention", "divestiture", "ebullience", "ecclesiastic", "edify", "educe", "efface",
            "effervescence", "effluvium", "effrontery", "effusive", "egress", "elaboration", "ellipsis",
            "embarkation", "enamored", "encomium", "encumber", "enervate", "enfeeble", "epicure", "epigram",
            "equinox", "equivocations", "estimable", "euphony", "evanescent", "exculpate", "exigent",
            "extemporize", "extricable", "exultation", "fatuous", "fecund", "fervid", "fetter", "froward",
            "fulsome", "fustian", "garrulous", "germane", "gerrymander", "gibber", "hackneyed", "harangue",
            "heretic", "homeostasis", "idiosyncrasy", "impale", "impenitent", "imperturbable", "impiety",
            "impolitic", "imprecate", "improvident", "impugn", "imputation", "inchoate", "incommodious",
            "incorporeal", "indigence", "indolent", "indubitably", "infamy", "ingenuous", "inimical",
            "instigate", "insubordinate", "intercede", "inveterate", "iota", "irreproachable", "kith",
            "knavery", "lambaste", "lambent", "latency", "levity", "licentious", "ligneous", "litigate",
            "lugubrious", "macerate", "maculate", "malediction", "malinger", "maudlin", "mendacious",
            "mesmerize", "minatory", "miscreant", "miser", "mollify", "morose", "munificent", "nefariousness",
            "nettle", "noisome", "obdurate", "obeisance", "obfuscate", "objurgate", "obstinate", "obtrude",
            "obviate", "odium", "omniscient", "opalescent", "opprobrious", "ossify", "ostensible", "ostracize",
            "palindrome", "palliate", "pallor", "panegyric", "parsimonious", "peccadillo", "pedagogue",
            "pellucid", "penitent", "perdition", "perfidious", "perquisite", "phlegmatic", "pinioned",
            "plenary", "polemicist", "portend", "prate", "prefatory", "preponderate", "prescience",
            "prevaricate", "promontory", "propinquity", "propitiate", "proselytize", "provident", "qualm",
            "quiescence", "raconteur", "ramification", "recondite", "recumbent", "recusant", "redolent",
            "refurbish", "relegate", "remonstrate", "renascence", "repast", "reprehend", "reprobate", "reproof",
            "repudiate", "retroaction", "revile", "rivet", "roseate", "ruffian", "sagacious", "salutatory",
            "sapid", "saturnine", "savant", "scanty", "sedulous", "servile", "slovenly", "soliloquy",
            "solubility", "spelunker", "splenetic", "suffuse", "sunder", "suppliant", "surreptitious", "torpid",
            "traduce", "tranquillity", "transmutation", "transpire", "troth", "truncate", "tumid", "turpitude",
            "unfeigned", "unwonted", "usury", "winsome", "zealot", "zephyr" };
    List<String> unmatchList = new ArrayList<>();
    for (String word : wordLst) {
        boolean result = search(searcher, parser, word);
        if (!result) {
            unmatchList.add(word);// w w  w  .j ava  2 s .co  m
        }
    }
    reader.close();

    System.out.println("findWTotal: " + findWTotal);
    System.out.println("findSTotal: " + findSTotal);
    System.out.println(new JSONArray(unmatchList).toString(3));
    System.out.println(unmatchList.size());
    System.out.println();

    String[] arr2 = new String[] { "abaft", "approbatory", "betroth", "bungler", "churlishness", "contumacious",
            "deliquesce", "extricable", "froward", "imprecate", "incommodious", "ligneous", "minatory",
            "nefariousness", "objurgate", "obtrude", "opprobrious", "preponderate", "recusant", "retroaction",
            "sapid", "sedulous", "traduce", "tumid", "unwonted" };
    String[] unmatchArr = new String[unmatchList.size()];
    unmatchArr = unmatchList.toArray(unmatchArr);
    CompareResult.compare(arr2, unmatchArr);

    // boolean result = search(searcher, parser, "abc");
}