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.icdd.lucence.SearchFiles.java

License:Apache License

public List<Document> searchFilesWeb(String queryString) {
    // //from  w ww  .ja  v  a2 s . c  om
    String index = "F:/download/index/";
    // 
    String field = "contents";
    int repeat = 0;
    // ????
    boolean raw = false;
    // ?10?
    int hitsPerPage = 10;
    List<Document> docs = new ArrayList<Document>();
    try {
        IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
        IndexSearcher searcher = new IndexSearcher(reader);
        Analyzer analyzer = new StandardAnalyzer();

        QueryParser parser = new QueryParser(field, analyzer);

        if (queryString == null) {
            System.out.println("Enter query:");
            return null;
        }
        String line = queryString;
        line = line.trim();
        if (line.length() == 0) {
            return null;
        }
        try {
            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, 100);
                }
                Date end = new Date();
                System.out.println("Time: " + (end.getTime() - start.getTime()) + "ms");
            }

            docs = doPagingSearchWeb(docs, searcher, query, hitsPerPage, raw);
        } catch (ParseException e) {

            e.printStackTrace();
        }
        reader.close();

    } catch (IOException e) {

        e.printStackTrace();
    }
    return docs;
}

From source file:com.impetus.kundera.index.LuceneIndexer.java

License:Apache License

/**
 * Returns default index reader./*w ww .  ja  v a2 s . co m*/
 * 
 * @return index reader.
 */
private IndexReader getIndexReader() {
    // removed flushInternal() call while reading
    if (reader == null) {
        try {
            if (!isInitialized) {
                Directory sourceDir = FSDirectory.open(getIndexDirectory().toPath());
                copy(sourceDir, index);
                isInitialized = true;
            }
            reader = DirectoryReader.open(index);
        } catch (IndexNotFoundException infex) {
            log.warn("No index found in given directory, caused by:", infex.getMessage());
        } catch (Exception e) {
            log.error("Error while instantiating LuceneIndexer, Caused by :.", e);
            throw new LuceneIndexingException(e);
        }
    }
    return reader;
}

From source file:com.isa.basic.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   w w w. j av  a2  s .c  o  m*/
    }

    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(Paths.get(index)));
    IndexSearcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new StandardAnalyzer();

    BufferedReader in = null;
    if (queries != null) {
        in = Files.newBufferedReader(Paths.get(queries), StandardCharsets.UTF_8);
    } else {
        in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
    }
    QueryParser parser = new QueryParser(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++) {
                TopDocs searchResults = 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:com.it.lucene.test.IndexSearch.java

private void doSearch(Query query) {
    try {/*www  .ja v a2 s .com*/
        // 2?IndexSearcher
        // 2.1 IndexReader
        // 2.1Directory
        Directory directory = FSDirectory.open(new File("F:\\Lucene Index"));
        IndexReader reader = DirectoryReader.open(directory);
        IndexSearcher searcher = new IndexSearcher(reader);
        // 3?indexSearcher?
        // ?
        TopDocs topDocs = searcher.search(query, 10);

        // 4??
        // ???
        long count = topDocs.totalHits;

        System.out.println("???:" + count);

        ScoreDoc[] scoreDocs = topDocs.scoreDocs;

        for (ScoreDoc scoreDoc : scoreDocs) {
            int docId = scoreDoc.doc;
            Document doc = searcher.doc(docId);
            System.out.println("?ID" + doc.get("id"));
            System.out.println("???" + doc.get("name"));
            System.out.println("?" + doc.get("price"));
            System.out.println("?pic" + doc.get("pic"));
        }
        // 5?IndexReader
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.javapr.plaintextindex.search.Suchen.java

License:Apache License

public void sucheString(String line) throws IOException, ParseException

{
    frame = new JFrame();
    frame.setTitle("Lucene Suche");
    frame.setSize(400, 180);/*from  w  w w . ja  va 2s .co  m*/
    frame.setLocation(400, 400);
    frame.setVisible(true);
    panel = new JPanel(new BorderLayout(5, 5));
    list = new JList();
    panel1 = new JPanel(new GridLayout(1, 1));
    panelLabel = new JPanel(new GridLayout(2, 1));
    pane = new JScrollPane(panel1);
    labelAnzData = new JLabel();
    alert = new JLabel();
    suche = new JLabel();
    dir = new JLabel();
    panel.add(panelLabel, BorderLayout.WEST);
    panel.add(pane, BorderLayout.CENTER);
    frame.add(panel);

    String field = "contents";
    int hitsPerPage = 10;

    try {
        IndexReader indexReader = DirectoryReader.open(FSDirectory.open(new File(Prop.Indexdirectory(null))));
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_42);
        QueryParser parser = new QueryParser(Version.LUCENE_42, field, analyzer);

        list1 = new ArrayList<Object>();

        try {
            Query query = parser.parse(line);

            suche = new JLabel("Suche nach: " + line);
            panelLabel.add(suche);

            TopDocs results = indexSearcher.search(query, 5 * hitsPerPage);
            ScoreDoc[] hits = results.scoreDocs;

            int end = hits.length;

            //Liste erzeugen und mit gefundenen Dateinamen fllen
            for (int i = 0; i < end; i++) {
                Document doc = indexSearcher.doc(hits[i].doc);
                String path = doc.get("filename");
                File file = new File(Prop.Filestoindex(null) + "\\" + doc.get("filename"));
                if (path != null) {
                    list1.add(path + ", " + file.length() / 1024 + "kb");
                }
            }

            labelAnzData = new JLabel(hits.length + " Gefundene Datei(en): ");
            panelLabel.add(labelAnzData);
            list = new JList(list1.toArray());
            panel1.add(list);

        } catch (ParseException p) {
            alert = new JLabel("String eingeben!");
            panel.add(alert);
            ;
        }
    } catch (IOException e) {
        dir.setText("<html><body>Index-Datei nicht gefunden!<br>Bitte Index erstellen!</body></html>");
        panel.add(dir);
    }
}

From source file:com.justinleegrant.myluceneplayground.SimpleFacetsExample.java

License:Apache License

/** User runs a query and counts facets. */
private List<FacetResult> facetsWithSearch() throws IOException {
    DirectoryReader indexReader = DirectoryReader.open(indexDir);
    IndexSearcher searcher = new IndexSearcher(indexReader);
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir);

    FacetsCollector fc = new FacetsCollector();

    // MatchAllDocsQuery is for "browsing" (counts facets
    // for all non-deleted docs in the index); normally
    // you'd use a "normal" query:
    FacetsCollector.search(searcher, new MatchAllDocsQuery(), 10, fc);

    // Retrieve results
    List<FacetResult> results = new ArrayList<>();

    // Count both "Publish Date" and "Author" dimensions
    Facets facets = new FastTaxonomyFacetCounts(taxoReader, config, fc);
    results.add(facets.getTopChildren(10, "Author"));
    results.add(facets.getTopChildren(10, "Publish Date"));

    indexReader.close();/* w ww .  jav a  2 s .  c om*/
    taxoReader.close();

    return results;
}

From source file:com.justinleegrant.myluceneplayground.SimpleFacetsExample.java

License:Apache License

/** User runs a query and counts facets only without collecting the matching documents.*/
private List<FacetResult> facetsOnly() throws IOException {
    DirectoryReader indexReader = DirectoryReader.open(indexDir);
    IndexSearcher searcher = new IndexSearcher(indexReader);
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir);

    FacetsCollector fc = new FacetsCollector();

    // MatchAllDocsQuery is for "browsing" (counts facets
    // for all non-deleted docs in the index); normally
    // you'd use a "normal" query:
    searcher.search(new MatchAllDocsQuery(), null /*Filter */, fc);

    // Retrieve results
    List<FacetResult> results = new ArrayList<>();

    // Count both "Publish Date" and "Author" dimensions
    Facets facets = new FastTaxonomyFacetCounts(taxoReader, config, fc);

    results.add(facets.getTopChildren(10, "Author"));
    results.add(facets.getTopChildren(10, "Publish Date"));

    indexReader.close();/*from   ww  w.  j  av  a  2s  .c om*/
    taxoReader.close();

    return results;
}

From source file:com.justinleegrant.myluceneplayground.SimpleFacetsExample.java

License:Apache License

/** User drills down on 'Publish Date/2010', and we
 *  return facets for both 'Publish Date' and 'Author',
 *  using DrillSideways. *//* ww w  .  j a  va2s  .  c  o  m*/
private List<FacetResult> drillSideways() throws IOException {
    DirectoryReader indexReader = DirectoryReader.open(indexDir);
    IndexSearcher searcher = new IndexSearcher(indexReader);
    TaxonomyReader taxoReader = new DirectoryTaxonomyReader(taxoDir);

    // Passing no baseQuery means we drill down on all
    // documents ("browse only"):
    DrillDownQuery q = new DrillDownQuery(config);

    // Now user drills down on Publish Date/2010:
    q.add("Publish Date", "2010");

    DrillSideways ds = new DrillSideways(searcher, config, taxoReader);
    DrillSidewaysResult result = ds.search(q, 10);

    // Retrieve results
    List<FacetResult> facets = result.facets.getAllDims(10);

    indexReader.close();
    taxoReader.close();

    return facets;
}

From source file:com.khepry.frackhem.entities.Blendeds.java

License:Apache License

public QueryResult initialize(String indexFolderPath, String taxonomyFolderPath) {
    QueryResult queryResult = new QueryResult();

    String message = "";

    File indexFolder = new File(indexFolderPath);
    if (!indexFolder.exists()) {
        message = "Index path does not exist: " + indexFolderPath;
        queryResult.setNotValid(true);//from   www  . ja va  2  s . com
        queryResult.setMessage(message);
        if (outputToSystemErr) {
            System.err.println(message);
        }
        if (outputToMsgQueue) {
            progressMessageQueue.send(new MessageInput(message));
        }
    }

    File taxonomyFolder = new File(taxonomyFolderPath);
    if (!taxonomyFolder.exists()) {
        message = "Taxonomy path does not exist: " + taxonomyFolderPath;
        queryResult.setNotValid(true);
        queryResult.setMessage(message);
        if (outputToSystemErr) {
            System.err.println(message);
        }
        if (outputToMsgQueue) {
            progressMessageQueue.send(new MessageInput(message));
        }
    }

    if (indexFolder.exists() && taxonomyFolder.exists()) {
        try {
            indexReader = DirectoryReader.open(FSDirectory.open(indexFolder));
            indexSearcher = new IndexSearcher(indexReader);
            analyzer = new StandardAnalyzer(Version.LUCENE_44);
            taxonomyReader = new DirectoryTaxonomyReader(FSDirectory.open(taxonomyFolder));
            initialized = true;
        } catch (IOException e) {
            message = e.getMessage();
            if (outputToSystemErr) {
                System.err.println(message);
            }
            if (outputToMsgQueue) {
                progressMessageQueue.send(new MessageInput(message));
            }
        }
    }

    return queryResult;
}

From source file:com.liang.minisearch.domain.search.Engine.java

protected DirectoryReader getReader() throws IOException {
    if (this.indexReader == null) {
        this.indexReader = DirectoryReader.open(getDirectory());
    } else {/* www.j  a v  a2  s  .  c o m*/
        DirectoryReader newReader = DirectoryReader.openIfChanged(this.indexReader);
        if (newReader != null) {
            this.indexReader = newReader;
        }
    }

    return this.indexReader;
}