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:ca.dracode.ais.indexer.FileSearcher.java

License:Open Source License

public FileSearcher() {
    IndexReader indexReader;/* w ww  .  j av  a2s . c  o m*/
    IndexSearcher indexSearcher = null;
    try {
        File indexDirFile = new File(FileIndexer.getRootStorageDir());
        Directory tmpDir = FSDirectory.open(indexDirFile);
        indexReader = DirectoryReader.open(tmpDir);
        indexSearcher = new IndexSearcher(indexReader);
    } catch (IOException ioe) {
        Log.e(TAG, "Error", ioe);
    }

    this.indexSearcher = indexSearcher;
}

From source file:ca.mcgill.cs.creco.logic.search.CategorySearch.java

License:Apache License

@Override
public List<Category> queryCategories(String pQueryString) {
    List<Category> searchResult = new ArrayList<Category>();
    try {/*from w  ww .j ava 2  s.c  o m*/
        DirectoryReader reader = DirectoryReader.open(aDirectory);
        IndexSearcher searcher = new IndexSearcher(reader);
        TopScoreDocCollector results = TopScoreDocCollector.create(MAX_NUM_RESULTS, true);

        // Search category names
        Query categoryNameQuery = new QueryParser(VERSION, CATEGORY_NAME, aAnalyzer).parse(pQueryString);
        searcher.search(categoryNameQuery, results);

        // Search flattened text (only product names for now)
        Query flattenedTextQuery = new QueryParser(VERSION, FLATTENED_TEXT, aAnalyzer).parse(pQueryString);
        searcher.search(flattenedTextQuery, results);

        for (ScoreDoc scoredResult : results.topDocs().scoreDocs) {
            Document doc = searcher.doc(scoredResult.doc);
            Category resultCategory = aDataStore.getCategory(doc.get(CATEGORY_ID));

            if (!searchResult.contains(resultCategory) && resultCategory.getNumberOfProducts() > 0) {
                searchResult.add(resultCategory);
            }
        }
    } catch (IOException e) {
        LOG.error(e.getMessage());
    } catch (ParseException e) {
        LOG.error(e.getMessage());
    }
    return searchResult;
}

From source file:ca.pgon.freenetknowledge.search.impl.LuceneSearchEngine.java

License:Apache License

@Override
public List<SearchResultEntry> searchTerm(String term) {
    IndexSearcher indexSearcher = null;//from w w  w  .  j  ava2s .  c  o m
    try {
        // Init the needed components
        IndexReader indexReader = IndexReader.open(directory);
        indexSearcher = new IndexSearcher(indexReader);
        QueryParser queryParser = new QueryParser(LUCENE_VERSION, INDEX_CONTENT, analyzer);

        // Create the query
        Query query;
        query = queryParser.parse(term);

        // Get the search result
        TopDocs topDocs = indexSearcher.search(query, LUCENE_MAX_HITS);
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;

        // Change them to urls
        Map<String, SearchResultEntry> alreadyIn = new HashMap<>();
        List<SearchResultEntry> results = new ArrayList<>();
        for (ScoreDoc sd : scoreDocs) {
            // Get the url
            Document document = indexSearcher.doc(sd.doc);
            String urlId = document.get(INDEX_FOR_URL);

            SearchResultEntry sre;
            if (alreadyIn.containsKey(urlId)) {
                sre = alreadyIn.get(urlId);
            } else {
                sre = new SearchResultEntry();
                UrlEntity ue = urlDAO.get(Integer.valueOf(urlId));
                sre.urlEntity = ue;

                if (ue == null) {
                    continue;
                }
                if (ue.isError()) {
                    continue;
                }

                alreadyIn.put(urlId, sre);
                results.add(sre);
            }

            // Add the description
            String fullDescription = document.get(INDEX_CONTENT);
            String partialDescription = SearchTools.getPartAround(fullDescription,
                    SearchTools.findWordPosition(fullDescription, term), LUCENE_MAX_DESCRIPTION_CARACTERS);
            partialDescription = partialDescription.replace('\n', ' ');
            partialDescription = partialDescription.replace('\r', ' ');
            if (!sre.description.contains(partialDescription)) {
                sre.description.add(partialDescription);
            }
        }

        return results;
    } catch (ParseException e) {
        logger.log(Level.SEVERE, "Error while parsing the search term", e);
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Error while searching", e);
    } finally {
        if (indexSearcher != null) {
            try {
                indexSearcher.close();
            } catch (IOException e) {
            }
        }
    }

    return null;
}

From source file:ca.ualberta.entitylinking.common.indexing.AliasLuceneIndex.java

License:Open Source License

public boolean loadIndex(String diskDir) {
    Directory dir = null;//from ww  w. j av a2s.co m

    try {
        dir = new RAMDirectory(new MMapDirectory(new File(diskDir)));
        if (!IndexReader.indexExists(dir))
            return false;

        reader = IndexReader.open(dir);
        String[] keyArray = FieldCache.DEFAULT.getStrings(reader, "docID");
        //   int[] sizeArray= FieldCache.DEFAULT.getInts(reader, "size");
        searcher = new IndexSearcher(reader);

        for (int i = 0; i < keyArray.length; i++)
            docIDMap.put(keyArray[i], i);
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("Loading index done22!!");
    return true;
}

From source file:ca.ualberta.entitylinking.common.indexing.WikipediaIndex.java

License:Open Source License

public void loadIndex(String diskDir) {
    Directory dir = null;/*from   w w  w.  j  a  v  a2s .c  o m*/

    try {
        dir = new RAMDirectory(new MMapDirectory(new File(diskDir)));
        if (!IndexReader.indexExists(dir))
            return;

        reader = IndexReader.open(dir);
        searcher = new IndexSearcher(reader);
        System.out.println("Loading WikipediaIndex done!!!");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:calliope.search.AeseSearch.java

License:Open Source License

/**
 * Search the index for the given expression
 * @param expr the expression to be parsed
 * @param langCode the language of the expression and index
 * @param profile the hit profile (where to start from etc)
 * @return the result docs/*from   w w  w  .j a  va  2 s .  c  o  m*/
 */
public static String searchIndex(String expr, String langCode, HitProfile profile) {
    StringBuilder sb = new StringBuilder();
    try {
        Analyzer analyzer = AeseSearch.createAnalyzer(langCode);
        DirectoryReader reader = DirectoryReader.open(AeseSearch.index);
        if (reader != null) {
            IndexSearcher searcher = new IndexSearcher(reader);
            QueryParser qp = new QueryParser(Version.LUCENE_45, "text", analyzer);
            Query q = qp.parse(expr);
            TopDocs hits = searcher.search(q, AeseSearch.maxHits);
            ScoreDoc[] docs = hits.scoreDocs;
            for (int j = profile.from; j < profile.to && j < docs.length; j++) {
                Document doc = searcher.doc(docs[j].doc);
                String vid = doc.get(LuceneFields.VID);
                String docID = doc.get(LuceneFields.DOCID);
                Highlighter h = new Highlighter(new QueryScorer(q));
                String text = getCorTexVersion(docID, vid);
                sb.append(formatDocID(docID));
                sb.append(" ");
                sb.append(formatVersionID(vid));
                sb.append(" ");
                String frag = h.getBestFragment(analyzer, "text", text);
                sb.append("<span class=\"found\">");
                sb.append(frag);
                sb.append("</span>\n");
            }
            profile.numHits = docs.length;
        }
        reader.close();
    } catch (Exception e) {
        sb.append(e.getMessage());
    }
    return sb.toString();
}

From source file:cc.osint.graphd.graph.Graph.java

License:Apache License

public Graph(String graphName) throws Exception {
    this.graphName = graphName;
    gr = new ListenableDirectedWeightedGraph<JSONVertex, JSONEdge>(JSONEdge.class);
    connectivityInspector = new ConnectivityInspector<JSONVertex, JSONEdge>(gr);
    vertices = new ConcurrentHashMap<String, JSONVertex>();

    // event handlers
    gr.addVertexSetListener(this);
    gr.addGraphListener(this);
    gr.addVertexSetListener(connectivityInspector);
    gr.addGraphListener(connectivityInspector);

    // simulation components
    executorService = Executors.newCachedThreadPool();
    fiberFactory = new PoolFiberFactory(executorService);
    vertexProcesses = new ProcessGroup<JSONVertex, JSONObject>(this, "vertex_processors", executorService,
            fiberFactory);/*from w ww.  j  a  v  a  2 s. com*/
    edgeProcesses = new ProcessGroup<JSONEdge, JSONObject>(this, "edge_processors", executorService,
            fiberFactory);
    graphProcesses = new ProcessGroup<EventObject, JSONObject>(this, "graph_processors", executorService,
            fiberFactory);
    endpointChannelProcesses = new ProcessGroup<String, JSONObject>(this, "endpoint_channel_processors",
            executorService, fiberFactory);

    // graph index
    luceneDirectory = new RAMDirectory();
    indexWriter = new IndexWriter(luceneDirectory, analyzer, IndexWriter.MaxFieldLength.LIMITED);
    indexReader = indexWriter.getReader();
    searcher = new IndexSearcher(indexReader);

    // process registry
    simLuceneDirectory = new RAMDirectory();
    simIndexWriter = new IndexWriter(simLuceneDirectory, analyzer, IndexWriter.MaxFieldLength.LIMITED);
    simIndexReader = simIndexWriter.getReader();
    simSearcher = new IndexSearcher(simIndexReader);

}

From source file:cc.osint.graphd.graph.Graph.java

License:Apache License

private void refreshGraphIndex() throws Exception {
    long t0 = System.currentTimeMillis();
    indexWriter.commit();/*from  w  w  w  .ja va 2 s .c o m*/
    IndexReader newReader = indexReader.reopen();
    if (newReader != indexReader) {
        searcher.close();
        indexReader.close();
        indexReader = newReader;
        searcher = new IndexSearcher(indexReader);
    }
    long elapsed = System.currentTimeMillis() - t0;
    //log.info("refreshGraphIndex: " + elapsed + "ms");
}

From source file:cc.osint.graphd.graph.Graph.java

License:Apache License

private void refreshSimIndex() throws Exception {
    long t0 = System.currentTimeMillis();
    simIndexWriter.commit();/*from   w  w  w  .  jav  a2 s.  c  o m*/
    IndexReader newReader = simIndexReader.reopen();
    if (newReader != simIndexReader) {
        simSearcher.close();
        simIndexReader.close();
        simIndexReader = newReader;
        simSearcher = new IndexSearcher(simIndexReader);
    }
    long elapsed = System.currentTimeMillis() - t0;
    //log.info("refreshSimIndex: " + elapsed + "ms");
}

From source file:cc.pp.analyzer.ik.demo.IKAnalyzerDemo.java

License:Apache License

public static void main(String[] args) {

    //Lucene Document??
    String fieldName = "text";
    ////from  ww w.j ava  2s.  co m
    String text = "IK Analyzer???????";

    //IKAnalyzer?
    Analyzer analyzer = new IKAnalyzer(Version.LUCENE_48, true);

    Directory directory = null;
    IndexWriter iwriter = null;
    DirectoryReader ireader = null;
    IndexSearcher isearcher = null;
    try {
        //
        directory = new RAMDirectory();

        //?IndexWriterConfig
        IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_48, analyzer);
        iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
        iwriter = new IndexWriter(directory, iwConfig);
        //
        Document doc = new Document();
        doc.add(new LongField("ID", 1000, Field.Store.YES));
        doc.add(new TextField(fieldName, text, Field.Store.YES));
        iwriter.addDocument(doc);
        iwriter.close();

        //?**********************************
        //?
        ireader = DirectoryReader.open(directory);
        isearcher = new IndexSearcher(ireader);

        String keyword = "?";
        //         String keyword = "";
        //QueryParser?Query
        QueryParser qp = new QueryParser(Version.LUCENE_48, fieldName, analyzer);
        qp.setDefaultOperator(QueryParser.AND_OPERATOR);
        Query query = qp.parse(keyword);
        System.out.println("Query = " + query);

        //?5?
        TopDocs topDocs = isearcher.search(query, 5);
        System.out.println("" + topDocs.totalHits);
        //
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (int i = 0; i < topDocs.totalHits; i++) {
            Document targetDoc = isearcher.doc(scoreDocs[i].doc);
            System.out.println("" + targetDoc.toString());
        }

    } catch (CorruptIndexException e) {
        e.printStackTrace();
    } catch (LockObtainFailedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } finally {
        if (ireader != null) {
            try {
                ireader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (directory != null) {
            try {
                directory.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}