⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 searchserviceimpl.java

📁 很好的搜索代码,大家都很难下载!抓紧时间啊!不要错过!
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                if (startAt >= hits.length() || startAt < 0) {
                    startAt = 0;
                }
                // only get the number of results we're interested in that is from startAt to endAt, or last
                int endAt = startAt + numberOfResults;
                // set the max index to maxpage or last
                if (endAt > hits.length()) {
                    endAt = hits.length();
                }
                log.debug("Returning hits " + startAt + " to " + (endAt - 1));

                // get all the hits into results array
                Result[] results = new Result[endAt - startAt];

                Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"highlight\">", "</span>"),
                    new QueryScorer(localquery));

                // get all the hits into Result
                for (int j = startAt; j < endAt; j++) {
                    Document doc = hits.doc(j);
                    float score = hits.score(j);
                    results[j - startAt] = doc2ResultHelper(doc, score, highlighter, analyzer);
                }
                log.info("The query '" + queryString + "', has " + hits.length() + " hits, returning " + maxResults + " results: "
                    + (startAt + 1) + " to " + endAt);

                return new SearchResult(results, hits.length(), startAt, endAt);
            }
            catch (org.apache.lucene.queryParser.ParseException pe) {
                throw new SearchException("Error executing query '" + queryString + "'", pe);
            }
            catch (TooManyClauses e) {
                throw new SearchException("Error executing query '" + queryString
                    + ". Too complex, possibly spanning more than 1024 days'", e);
            }
            finally {
                if (ms != null) {
                    ms.close();
                }
            }
        }
        catch (Exception e) {
            log.error("Error executing query '" + queryString + "', " + e);
            throw new SearchException("Error executing query '" + queryString + "'", e);
        }
    }

    /**
     * Create IndexSearchers for all given document collections.
     * 
     * @param names the names of collections
     * @return Array of IndexSearchers based on given collection names
     * @throws IndexException
     * @throws IOException
     */
    private IndexSearcher[] createSearchersForCollectionsByName(final String[] names) throws IndexException, IOException {
        // create an array of searchers, one searcher per valid
        // collection this will be argument to MultiSearcher
        List allSearchersList = new ArrayList();
        // if any collection specified, find it by name using the
        // CollectionManager
        if (names != null && names.length > 0) {
            for (int i = 0; i < names.length; i++) {
                String colName = names[i];
                DocumentCollection thisCollection = collectionManager.getCollectionByName(colName);
                if (thisCollection != null) {
                    addCollectionIfValidToSearchers(thisCollection, allSearchersList);
                } else {
                    log.warn("Invalid collection '" + colName + "' specified, skipping");
                }
            }
        } else {
            // no collection specified, use all
            log.warn("No collections specified, assuming you want all");
            List allCollections = collectionManager.getCollections();
            Iterator colIt = allCollections.iterator();
            while (colIt.hasNext()) {
                FileSystemCollection thisCollection = (FileSystemCollection) colIt.next();
                addCollectionIfValidToSearchers(thisCollection, allSearchersList);
            }
        }

        IndexSearcher[] allSearchers = new IndexSearcher[allSearchersList.size()];

        for (int j = 0; j < allSearchersList.size(); j++) {
            allSearchers[j] = (IndexSearcher) allSearchersList.get(j);
        }

        return allSearchers;
    }

    private void addCollectionIfValidToSearchers(DocumentCollection thisCollection, List allSearchersList) throws IndexException,
        IOException {
        if (thisCollection.isIndexValid()) {
            if (thisCollection.getIndexDirWithManagerDefaults() != null) {
                // create IndexSearcher with String argument,
                // not IndexReader, as reader will stay open
                allSearchersList.add(new IndexSearcher(thisCollection.getIndexDirWithManagerDefaults().toString()));
                log.info("Searching in collection: " + thisCollection.getName());
            }
        } else {
            log.warn("Skipping possibly invalid collection '" + thisCollection.getName() + "'.");
        }
    }

    /**
     * Helper that creates a Result from a Document.
     * 
     * @param doc the Document
     * @param score the score of the Document in the hit
     * @param hl the Highlighter used
     * @param an the Analyzer used
     * 
     * @return Result the resulting object that is used in the model.
     */
    private Result doc2ResultHelper(final Document doc, final float score, final Highlighter hl, final Analyzer an) {
        String docTitle = doc.get("title");
        String docName = doc.get("name");
        String docPath = doc.get("path");
        String zipName = doc.get("zipName");
        if (log.isDebugEnabled()) {
            log.debug("Preparing result " + docName + ":" + zipName);
        }
        String zipPath = doc.get("zipPath");
        String docURL = "";
        String docCache = "";
        String docCollection = doc.get("collection");

        // get the collection
        DocumentCollection thisCollection = collectionManager.getCollectionByName(docCollection);

        if (thisCollection != null) {
            docURL = thisCollection.getUrlDefault();

            if (thisCollection.isKeepCacheWithManagerDefaults()) {
                docCache = thisCollection.getCacheUrlWithManagerDefaults();
            }
        } else {
            log.error("Unknown collection '" + docCollection + "' found, can not find its URL.");
        }

        // get the modification date, and convert it to a readable form date is stored as (yyyyMMdd)
        DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
        Date docDate = null;

        try {
            docDate = df1.parse(doc.get("modified"));
        }
        catch (ParseException e) {
            log.debug("Invalid date retrieved, trying backward compatibility with v 1.0-rc3-patch1");

            // backward compatibility with v 1.0-rc3-patch1 storage of date:
            // Keyword<modified:0cee68g00>
            docDate = DateField.stringToDate(doc.get("modified"));
            if (docDate == null) {
                log.warn("Invalid date retrieved, returning epoch (1970) for " + docName);
                docDate = new Date(0);
            }
        }

        String docSize = doc.get("size");
        String docType = doc.get("type");
        String docISBN = doc.get("isbn");

        // use the name if it has no title
        // TODO this logic could go into Result
        if ((docTitle == null) || docTitle.equals("")) {
            if ((zipName == null) || zipName.equals("")) {
                docTitle = docName;
            } else {
                docTitle = zipName;
            }
        }
        // then make a Result
        Result thisResult = new Result();

        // highlight the title with search terms
        String highlightedText;
        TokenStream tokenStream = an.tokenStream("title", new StringReader(docTitle));

        try {
            highlightedText = hl.getBestFragment(tokenStream, docTitle);

            if ((highlightedText != null) && (highlightedText.length() > 0)) {
                docTitle = highlightedText;
            }
        }
        catch (IOException e1) {
            log.warn("Can't highlight " + docTitle, e1);
        }

        thisResult.setTitle(docTitle);

        // highlight the name with search terms
        /*
         * tokenStream = an.tokenStream("title", new StringReader(docName)); try { highlightedText = hl.getBestFragment(tokenStream,
         * docName); log.debug("name after highlighting: " + highlightedText); if (highlightedText != null &&
         * highlightedText.length() > 0) { docName = highlightedText; } } catch (IOException e1) { log.warn("Can't highlight " +
         * docName, e1); }
         */
        thisResult.setName(docName);
        thisResult.setCollection(docCollection);
        thisResult.setPath(docPath);
        thisResult.setURL(docURL);
        thisResult.setCache(docCache);
        thisResult.setZipName(zipName);
        thisResult.setZipPath(zipPath);
        thisResult.setScore(score);
        thisResult.setISBN(docISBN);

        String text = doc.get("summary");
        if (text == null) {
            text = "";
        }

        // highlight the summary with search terms
        tokenStream = an.tokenStream("summary", new StringReader(text));

        try {
            highlightedText = hl.getBestFragment(tokenStream, text);

            if ((highlightedText != null) && (highlightedText.length() > 0)) {
                text = highlightedText;
            }
        }
        catch (IOException e1) {
            log.warn("Can't highlight " + text, e1);
        }

        thisResult.setSummary(text);

        thisResult.setModificationDate(docDate);
        thisResult.setSize(docSize);
        thisResult.setType(docType);

        return thisResult;
    }

    /**
     * @return Returns the allBoostableFields.
     */
    public String[] getAllBoostableFields() {
        return allBoostableFields;
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -