Example usage for org.apache.lucene.search IndexSearcher IndexSearcher

List of usage examples for org.apache.lucene.search IndexSearcher IndexSearcher

Introduction

In this page you can find the example usage for org.apache.lucene.search IndexSearcher IndexSearcher.

Prototype

public IndexSearcher(IndexReaderContext context) 

Source Link

Document

Creates a searcher searching the provided top-level IndexReaderContext .

Usage

From source file:com.devb.search.IndicSearcher.java

License:Apache License

private void callSearch(boolean j) {
    System.out.println("Servlet Ctx " + servletContext.getRealPath("/"));
    String indexPath = servletContext.getRealPath("/") + "/hindex/";
    String docsPath = servletContext.getRealPath("/") + "/hdocs/";

    final File docDir = new File(docsPath);
    if (!docDir.exists() || !docDir.canRead()) {
        System.out.println("Document directory '" + docDir.getAbsolutePath()
                + "' does not exist or is not readable, " + "please check the path\n");
        return;//from ww  w . j  a v a 2 s  . c  om
    }

    IndexReader reader = null;
    IndexSearcher searcher = null;
    Analyzer analyzer = null;
    String field = "contents";

    try {
        reader = DirectoryReader.open(FSDirectory.open(new File(indexPath)));
        searcher = new IndexSearcher(reader);
        analyzer = new HindiAnalyzer();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    QueryParser parser = new QueryParser(field, analyzer);
    String /*ByteBuffer*/ line = null;
    Query query = null;

    try {
        // line = Charset.forName("UTF-8").encode(this.id);
        line = this.id;

        // line = line.trim();
        if (line == null) {
            return;
        }
        System.out.println("Hindi StandardSearcher / callSearch Line " + line);
        query = parser.parse(line);
        System.out.println("Hindi StandardSearcher / callSearch Hindi Query " + query);
        final int maxHits = 10;
        ScoreDoc[] hits = searcher.search(query, null, maxHits).scoreDocs;
        try {
            // Iterate through the results:
            for (int i = 0; i < hits.length; i++) {
                Document hitDoc = searcher.doc(hits[i].doc);

                if (j) {
                    JSONObject jo = new JSONObject();
                    jo.put("query", query.toString(field));
                    jo.put("path", hitDoc.get("path"));
                    jo.put("line", hitDoc.get("linenumber"));
                    jo.put("contents", hitDoc.get("contents"));

                    ja.put(jo);
                } else {
                    SearchResult ns = new SearchResult();
                    ns.setQuery(query.toString(field));
                    ns.setDocPath(hitDoc.get("path"));
                    ns.setLineNum(hitDoc.get("linenumber"));
                    ns.setContents(hitDoc.get("contents"));
                    contentProvider.put(String.valueOf(i), ns);
                }
            }
        } catch (Exception ito) {
            ito.printStackTrace();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    try {
        reader.close();
    } catch (IOException ioe) {

    }
}

From source file:com.devb.search.StandardSearcher.java

License:Apache License

private void callSearch(boolean j) {
    System.out.println("Servlet Ctx " + servletContext.getRealPath("/"));
    String indexPath = servletContext.getRealPath("/") + "/index/";
    String docsPath = servletContext.getRealPath("/") + "/docs/";

    final File docDir = new File(docsPath);
    if (!docDir.exists() || !docDir.canRead()) {
        System.out.println("Document directory '" + docDir.getAbsolutePath()
                + "' does not exist or is not readable, " + "please check the path\n");
        return;//from   w w  w  . j a  v  a  2 s. c o  m
    }

    IndexReader reader = null;
    IndexSearcher searcher = null;
    Analyzer analyzer = null;
    String field = "contents";

    try {
        reader = DirectoryReader.open(FSDirectory.open(new File(indexPath)));
        searcher = new IndexSearcher(reader);
        analyzer = new StandardAnalyzer();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    QueryParser parser = new QueryParser(field, analyzer);
    String line = null;
    Query query = null;

    try {
        line = this.id;

        line = line.trim();
        if (line.length() == 0) {
            return;
        }
        query = parser.parse(line);
        final int maxHits = 10;
        ScoreDoc[] hits = searcher.search(query, null, maxHits).scoreDocs;
        try {
            // Iterate through the results:
            for (int i = 0; i < hits.length; i++) {
                Document hitDoc = searcher.doc(hits[i].doc);

                if (j) {
                    JSONObject jo = new JSONObject();
                    jo.put("query", query.toString(field));
                    jo.put("path", hitDoc.get("path"));
                    jo.put("line", hitDoc.get("linenumber"));
                    jo.put("contents", hitDoc.get("contents"));

                    ja.put(jo);
                } else {
                    SearchResult ns = new SearchResult();
                    ns.setQuery(query.toString(field));
                    ns.setDocPath(hitDoc.get("path"));
                    ns.setLineNum(hitDoc.get("linenumber"));
                    ns.setContents(hitDoc.get("contents"));
                    contents.put(String.valueOf(i), ns);
                }
            }
        } catch (Exception ito) {
            ito.printStackTrace();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    try {
        reader.close();
    } catch (IOException ioe) {

    }
}

From source file:com.difference.historybook.index.lucene.LuceneIndex.java

License:Apache License

/**
 * Constructor for LuceneIndex//from  w w w .  j  ava 2s.  c o  m
 * 
 * @param dataDirectory   Path to the directory to create an index directory within.
 * @throws IndexException
 */
public LuceneIndex(Path dataDirectory) throws IndexException {

    //TODO: Check to make sure directory is read/writable
    path = dataDirectory.resolve(INDEXDIR);

    try {
        dir = FSDirectory.open(path);
        analyzer = new StandardAnalyzer();
        IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
        iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
        writer = new IndexWriter(dir, iwc);

        reader = DirectoryReader.open(writer, false);
        searcher = new IndexSearcher(reader);
        parser = new QueryParser(IndexDocumentAdapter.FIELD_SEARCH, analyzer);
    } catch (IOException e) {
        LOG.error(e.getLocalizedMessage());
        throw new IndexException(e);
    }
}

From source file:com.difference.historybook.index.lucene.LuceneIndex.java

License:Apache License

@Override
public void indexPage(String collection, String url, Instant timestamp, String body) throws IndexException {
    HtmlTextExtractor extractor = new HtmlTextExtractor(body, url);

    Document doc = new IndexDocumentAdapter().setCollection(collection).setUrl(url).setTimestamp(timestamp)
            .setTitle(extractor.getTitle()).setContent(extractor.getContent()).getAsDocument();

    try {/*  w w w .  ja  v a2 s. c o m*/
        writer.addDocument(doc);
        writer.commit();
        reader.close();
        reader = DirectoryReader.open(writer, false);
        searcher = new IndexSearcher(reader);
    } catch (IOException e) {
        LOG.error(e.getLocalizedMessage());
        throw new IndexException(e);
    }
}

From source file:com.digitalpebble.ngrams.NGramCorpus.java

License:Apache License

/**
 * Loads the indexReaders from the directory
 * //  w  w w .ja  v a  2 s .c  o m
 * @throws IOException
 **/
public NGramCorpus(String indexDirectory) throws IOException {
    Directory directory = new SimpleFSDirectory(new File(indexDirectory));
    searcher = new IndexSearcher(directory);
    // get the total number of tokens for this corpus
    // which is stored for 1-grams
    TermQuery tq = new TermQuery(new Term("totalTokenNums", "1"));
    totalNumberTokens = getOccurrences(tq);
}

From source file:com.discursive.jccook.xml.bardsearch.TermSearch.java

License:Apache License

public static void main(String[] pArgs) throws Exception {
    logger.info("Searching for " + pArgs[0]);
    Searcher searcher = new IndexSearcher("index");
    Analyzer analyzer = new SimpleAnalyzer();
    Query query = QueryParser.parse(pArgs[0], "speech", analyzer);
    Hits hits = searcher.search(query);//from  w  w w  .  j a  va 2 s . co  m
    logger.info("Searching Done, hit: " + hits.length());

    System.out.println("Score | Play | Act | Scene | Speaker");

    for (int i = 0; i < hits.length(); i++) {
        Document doc = hits.doc(i);
        System.out.print((int) (hits.score(i) * 100));
        System.out.print(" | " + doc.get("play") + " | " + doc.get("act"));
        System.out.print(" | " + doc.get("scene"));
        System.out.print(" | " + doc.get("speaker") + "\n");
    }
}

From source file:com.docdoku.server.IndexSearcherBean.java

License:Open Source License

public Set<DocumentMasterKey> searchInIndex(String pWorkspaceId, String pContent) {
    try {//from  w w w  .  j  a v a2 s  .co m
        Set<DocumentMasterKey> indexedKeys = new HashSet<DocumentMasterKey>();

        Query fullNameQuery = new WildcardQuery(new Term("fullName", pWorkspaceId + "/*"));
        Query contentQuery = new TermQuery(new Term("content", pContent));
        BooleanQuery mainQuery = new BooleanQuery();
        mainQuery.add(fullNameQuery, BooleanClause.Occur.MUST);
        mainQuery.add(contentQuery, BooleanClause.Occur.MUST);

        if (!indexReader.isCurrent()) {
            //TODO use IndexReader.reopen(); when available
            indexReader.close();
            indexReader = IndexReader.open(FSDirectory.open(new File(indexPath)));
        }
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);
        ScoreDoc[] hits = indexSearcher.search(mainQuery, 500).scoreDocs;
        for (int i = 0; i < hits.length; i++) {
            org.apache.lucene.document.Document doc = indexReader.document(hits[i].doc);
            String fullName = doc.get("fullName");
            String[] partRefs = BinaryResource.parseOwnerRef(fullName).split("/");
            DocumentMasterKey key = new DocumentMasterKey(pWorkspaceId, partRefs[0], partRefs[1]);
            indexedKeys.add(key);
        }

        return indexedKeys;
    } catch (CorruptIndexException ex) {
        throw new EJBException(ex);
    } catch (IOException ex) {
        throw new EJBException(ex);
    }
}

From source file:com.doculibre.constellio.lucene.BaseLuceneIndexHelper.java

License:Open Source License

protected synchronized int getDocNum(T object) {
    int docNum;//w ww. j a  va 2 s .c  om
    String uniqueIndexFieldName = getUniqueIndexFieldName();
    String uniqueIndexFieldValue = getUniqueIndexFieldValue(object);
    if (uniqueIndexFieldValue != null) {
        String query = uniqueIndexFieldName + ":" + uniqueIndexFieldValue;
        try {
            Analyzer analyzer = analyzerProvider.getAnalyzer(Locale.FRENCH);
            QueryParser multiFielsQP = new QueryParser(Version.LUCENE_44, uniqueIndexFieldName, analyzer);
            Query luceneQuery = multiFielsQP.parse(query);

            Directory directory = FSDirectory.open(indexDir);
            IndexReader reader = DirectoryReader.open(directory);
            IndexSearcher indexSearcher = new IndexSearcher(reader);
            TopDocs topDocs = indexSearcher.search(luceneQuery, reader.maxDoc());
            if (topDocs.totalHits > 0) {
                docNum = topDocs.scoreDocs[0].doc;
            } else {
                docNum = -1;
            }
            //               indexSearcher.close();
            // TODO add finally
            reader.close();
            directory.close();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        } catch (CorruptIndexException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        docNum = -1;
    }
    return docNum;
}

From source file:com.doculibre.constellio.lucene.LuceneSearchResultsProvider.java

License:Open Source License

private synchronized void initIfNecessary() {
    if (topDocs == null) {
        try {/* w  ww . j av  a  2s  .  co  m*/
            Directory directory = FSDirectory.open(indexDir);
            Analyzer analyzer = analyzerProvider.getAnalyzer(Locale.FRENCH);
            MultiFieldQueryParser parser = new MultiFieldQueryParser(Version.LUCENE_44, searchFields, analyzer);
            parser.setAllowLeadingWildcard(true);
            try {
                luceneQuery = parser.parse(luceneTextQuery);
            } catch (ParseException e) {
                try {
                    luceneQuery = parser.parse(QueryParser.escape(luceneTextQuery));
                } catch (ParseException e1) {
                    throw new RuntimeException(e1);
                }
            }
            indexReader = DirectoryReader.open(directory);
            indexSearcher = new IndexSearcher(indexReader);
            //              Sort sort;
            //              if (sortField != null) {
            //                  sort = new Sort(new SortField(sortField, Locale.CANADA_FRENCH, Boolean.FALSE.equals(sortAscending)));
            //              } else {
            //                  sort = null;
            //              }
            topDocs = indexSearcher.search(luceneQuery, indexReader.maxDoc());
            directory.close();
        } catch (CorruptIndexException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.dreamerpartner.codereview.lucene.SearchHelper.java

License:Apache License

@SuppressWarnings("deprecation")
public static Document getById(String module, String id) {
    if (StringUtils.isEmpty(id))
        return null;
    IndexReader reader = null;//from   ww w  . j  a v a 2  s.  c o  m
    try {
        reader = DirectoryReader.open(FSDirectory.open(new File(LuceneUtil.getIndexPath(module))));
        IndexSearcher searcher = new IndexSearcher(reader);

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
        Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_0);
        //?
        QueryParser parser = new QueryParser(Version.LUCENE_4_10_0, "id", analyzer);
        Query query = parser.parse(id);
        return searchOne(in, searcher, query);
    } catch (Exception e) {
        logger.error(id + " getById fail.", e);
    } finally {
        try {
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}