Example usage for org.apache.solr.client.solrj SolrQuery getHighlight

List of usage examples for org.apache.solr.client.solrj SolrQuery getHighlight

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj SolrQuery getHighlight.

Prototype

public boolean getHighlight() 

Source Link

Usage

From source file:org.ambraproject.search.service.SolrSearchService.java

License:Apache License

private SearchResultSinglePage readQueryResults(QueryResponse queryResponse, SolrQuery query) {
    SolrDocumentList documentList = queryResponse.getResults();

    if (log.isInfoEnabled()) {
        StringBuilder filterQueriesForLog = new StringBuilder();
        if (query.getFilterQueries() != null && query.getFilterQueries().length > 0) {
            for (String filterQuery : query.getFilterQueries()) {
                filterQueriesForLog.append(filterQuery).append(" , ");
            }/*from   www .  ja v  a  2s  .  c  om*/
            if (filterQueriesForLog.length() > 3) {
                filterQueriesForLog.replace(filterQueriesForLog.length() - 3, filterQueriesForLog.length(), "");
            } else {
                filterQueriesForLog.append("No Filter Queries");
            }
        }

        log.info("query.getQuery():{ " + query.getQuery() + " }" + ", query.getSortFields():{ "
                + (query.getSortFields() == null ? null : Arrays.asList(query.getSortFields())) + " }"
                + ", query.getFilterQueries():{ " + filterQueriesForLog.toString() + " }" + ", found:"
                + documentList.getNumFound() + ", start:" + documentList.getStart() + ", max_score:"
                + documentList.getMaxScore() + ", QTime:" + queryResponse.getQTime() + "ms");

        // TODO: implement spell-checking in a meaningful manner.  This loop exists only to generate log output.
        // TODO: Add "spellcheckAlternatives" or something like it to the SearchHits class so it can be displayed to the user like Google's "did you mean..."
        // TODO: Turn off spellchecking for the "author" field.
        if (queryResponse.getSpellCheckResponse() != null
                && queryResponse.getSpellCheckResponse().getSuggestionMap() != null
                && queryResponse.getSpellCheckResponse().getSuggestionMap().keySet().size() > 0) {
            StringBuilder sb = new StringBuilder("Spellcheck alternative suggestions:");
            for (String token : queryResponse.getSpellCheckResponse().getSuggestionMap().keySet()) {
                sb.append(" { ").append(token).append(" : ");
                if (queryResponse.getSpellCheckResponse().getSuggestionMap().get(token).getAlternatives()
                        .size() < 1) {
                    sb.append("NO ALTERNATIVES");
                } else {
                    for (String alternative : queryResponse.getSpellCheckResponse().getSuggestionMap()
                            .get(token).getAlternatives()) {
                        sb.append(alternative).append(", ");
                    }
                    sb.replace(sb.length() - 2, sb.length(), ""); // Remove last comma and space.
                }
                sb.append(" } ,");
            }
            log.info(sb.replace(sb.length() - 2, sb.length(), "").toString()); // Remove last comma and space.
        } else {
            log.info("Solr thinks everything in the query is spelled correctly.");
        }
    }

    Map<String, Map<String, List<String>>> highlightings = queryResponse.getHighlighting();

    List<SearchHit> searchResults = new ArrayList<SearchHit>();
    for (SolrDocument document : documentList) {

        String id = getFieldValue(document, "id", String.class, query.toString());
        String message = id == null ? query.toString() : id;
        Float score = getFieldValue(document, "score", Float.class, message);
        String title = getFieldValue(document, "title_display", String.class, message);
        Date publicationDate = getFieldValue(document, "publication_date", Date.class, message);
        String eissn = getFieldValue(document, "eissn", String.class, message);
        String journal = getFieldValue(document, "journal", String.class, message);
        String articleType = getFieldValue(document, "article_type", String.class, message);

        List<String> authorList = getFieldMultiValue(document, message, String.class, "author_display");

        String highlights = null;
        if (query.getHighlight()) {
            highlights = getHighlights(highlightings.get(id));
        }

        SearchHit hit = new SearchHit(score, id, title, highlights, authorList, publicationDate, eissn, journal,
                articleType);

        if (log.isDebugEnabled())
            log.debug(hit.toString());

        searchResults.add(hit);
    }

    //here we assume that number of hits is always going to be withing range of int
    SearchResultSinglePage results = new SearchResultSinglePage((int) documentList.getNumFound(), -1,
            searchResults, query.getQuery());

    if (queryResponse.getFacetField("subject_facet") != null) {
        results.setSubjectFacet(facetCountsToHashMap(queryResponse.getFacetField("subject_facet")));
    }

    if (queryResponse.getFacetField("author_facet") != null) {
        results.setAuthorFacet(facetCountsToHashMap(queryResponse.getFacetField("author_facet")));
    }

    if (queryResponse.getFacetField("editor_facet") != null) {
        results.setEditorFacet(facetCountsToHashMap(queryResponse.getFacetField("editor_facet")));
    }

    if (queryResponse.getFacetField("article_type_facet") != null) {
        results.setArticleTypeFacet(facetCountsToHashMap(queryResponse.getFacetField("article_type_facet")));
    }

    if (queryResponse.getFacetField("affiliate_facet") != null) {
        results.setInstitutionFacet(facetCountsToHashMap(queryResponse.getFacetField("affiliate_facet")));
    }

    if (queryResponse.getFacetField("cross_published_journal_key") != null) {
        results.setJournalFacet(
                facetCountsToHashMap(queryResponse.getFacetField("cross_published_journal_key")));
    }

    return results;
}

From source file:org.apache.jackrabbit.oak.plugins.index.solr.query.FilterQueryParser.java

License:Apache License

static SolrQuery getQuery(Filter filter, QueryIndex.IndexPlan plan, OakSolrConfiguration configuration) {

    SolrQuery solrQuery = new SolrQuery();
    setDefaults(solrQuery, configuration);

    StringBuilder queryBuilder = new StringBuilder();

    FullTextExpression ft = filter.getFullTextConstraint();
    if (ft != null) {
        queryBuilder.append(parseFullTextExpression(ft, configuration));
        queryBuilder.append(' ');
    } else if (filter.getFulltextConditions() != null) {
        Collection<String> fulltextConditions = filter.getFulltextConditions();
        for (String fulltextCondition : fulltextConditions) {
            queryBuilder.append(fulltextCondition).append(" ");
        }//from   ww  w. j a  v a  2s  . c  o m
    }

    List<QueryIndex.OrderEntry> sortOrder = plan.getSortOrder();
    if (sortOrder != null) {
        for (QueryIndex.OrderEntry orderEntry : sortOrder) {
            SolrQuery.ORDER order;
            if (QueryIndex.OrderEntry.Order.ASCENDING.equals(orderEntry.getOrder())) {
                order = SolrQuery.ORDER.asc;
            } else {
                order = SolrQuery.ORDER.desc;
            }
            String sortingField;
            if (JcrConstants.JCR_PATH.equals(orderEntry.getPropertyName())) {
                sortingField = partialEscape(configuration.getPathField()).toString();
            } else if (JcrConstants.JCR_SCORE.equals(orderEntry.getPropertyName())) {
                sortingField = "score";
            } else {
                if (orderEntry.getPropertyName().indexOf('/') >= 0) {
                    log.warn("cannot sort on relative properties, ignoring {} clause", orderEntry);
                    continue; // sorting by relative properties not supported until index time aggregation is supported
                }
                sortingField = partialEscape(
                        getSortingField(orderEntry.getPropertyType().tag(), orderEntry.getPropertyName()))
                                .toString();
            }
            solrQuery.addOrUpdateSort(sortingField, order);
        }
    }

    Collection<Filter.PropertyRestriction> propertyRestrictions = filter.getPropertyRestrictions();
    if (propertyRestrictions != null && !propertyRestrictions.isEmpty()) {
        for (Filter.PropertyRestriction pr : propertyRestrictions) {
            if (pr.isNullRestriction()) {
                // can not use full "x is null"
                continue;
            }
            // facets
            if (QueryImpl.REP_FACET.equals(pr.propertyName)) {
                solrQuery.setFacetMinCount(1);
                solrQuery.setFacet(true);
                String value = pr.first.getValue(Type.STRING);
                solrQuery.addFacetField(
                        value.substring(QueryImpl.REP_FACET.length() + 1, value.length() - 1) + "_facet");
            }

            // native query support
            if (SolrQueryIndex.NATIVE_SOLR_QUERY.equals(pr.propertyName)
                    || SolrQueryIndex.NATIVE_LUCENE_QUERY.equals(pr.propertyName)) {
                String nativeQueryString = String.valueOf(pr.first.getValue(pr.first.getType()));
                if (isSupportedHttpRequest(nativeQueryString)) {
                    // pass through the native HTTP Solr request
                    String requestHandlerString = nativeQueryString.substring(0,
                            nativeQueryString.indexOf('?'));
                    if (!"select".equals(requestHandlerString)) {
                        if (requestHandlerString.charAt(0) != '/') {
                            requestHandlerString = "/" + requestHandlerString;
                        }
                        solrQuery.setRequestHandler(requestHandlerString);
                    }
                    String parameterString = nativeQueryString.substring(nativeQueryString.indexOf('?') + 1);
                    for (String param : parameterString.split("&")) {
                        String[] kv = param.split("=");
                        if (kv.length != 2) {
                            throw new RuntimeException("Unparsable native HTTP Solr query");
                        } else {
                            // more like this
                            if ("/mlt".equals(requestHandlerString)) {
                                if ("stream.body".equals(kv[0])) {
                                    kv[0] = "q";
                                    String mltFlString = "mlt.fl=";
                                    int mltFlIndex = parameterString.indexOf(mltFlString);
                                    if (mltFlIndex > -1) {
                                        int beginIndex = mltFlIndex + mltFlString.length();
                                        int endIndex = parameterString.indexOf('&', beginIndex);
                                        String fields;
                                        if (endIndex > beginIndex) {
                                            fields = parameterString.substring(beginIndex, endIndex);
                                        } else {
                                            fields = parameterString.substring(beginIndex);
                                        }
                                        kv[1] = "_query_:\"{!dismax qf=" + fields + " q.op=OR}" + kv[1] + "\"";
                                    }
                                }
                                if ("mlt.fl".equals(kv[0]) && ":path".equals(kv[1])) {
                                    // rep:similar passes the path of the node to find similar documents for in the :path
                                    // but needs its indexed content to find similar documents
                                    kv[1] = configuration.getCatchAllField();
                                }
                            }
                            if ("/spellcheck".equals(requestHandlerString)) {
                                if ("term".equals(kv[0])) {
                                    kv[0] = "spellcheck.q";
                                }
                                solrQuery.setParam("spellcheck", true);
                            }
                            if ("/suggest".equals(requestHandlerString)) {
                                if ("term".equals(kv[0])) {
                                    kv[0] = "suggest.q";
                                }
                                solrQuery.setParam("suggest", true);
                            }
                            solrQuery.setParam(kv[0], kv[1]);
                        }
                    }
                    return solrQuery;
                } else {
                    queryBuilder.append(nativeQueryString);
                }
            } else {
                if (SolrQueryIndex.isIgnoredProperty(pr, configuration)) {
                    continue;
                }

                String first = null;
                if (pr.first != null) {
                    first = partialEscape(String.valueOf(pr.first.getValue(pr.first.getType()))).toString();
                }
                String last = null;
                if (pr.last != null) {
                    last = partialEscape(String.valueOf(pr.last.getValue(pr.last.getType()))).toString();
                }

                String prField = configuration.getFieldForPropertyRestriction(pr);
                CharSequence fieldName = partialEscape(prField != null ? prField : pr.propertyName);
                if ("jcr\\:path".equals(fieldName.toString())) {
                    queryBuilder.append(configuration.getPathField());
                    queryBuilder.append(':');
                    queryBuilder.append(first);
                } else {
                    if (pr.first != null && pr.last != null && pr.first.equals(pr.last)) {
                        queryBuilder.append(fieldName).append(':');
                        queryBuilder.append(first);
                    } else if (pr.first == null && pr.last == null) {
                        if (!queryBuilder.toString().contains(fieldName + ":")) {
                            queryBuilder.append(fieldName).append(':');
                            queryBuilder.append('*');
                        }
                    } else if ((pr.first != null && pr.last == null) || (pr.last != null && pr.first == null)
                            || (!pr.first.equals(pr.last))) {
                        // TODO : need to check if this works for all field types (most likely not!)
                        queryBuilder.append(fieldName).append(':');
                        queryBuilder.append(createRangeQuery(first, last, pr.firstIncluding, pr.lastIncluding));
                    } else if (pr.isLike) {
                        // TODO : the current parameter substitution is not expected to work well
                        queryBuilder.append(fieldName).append(':');
                        queryBuilder.append(partialEscape(String.valueOf(pr.first.getValue(pr.first.getType()))
                                .replace('%', '*').replace('_', '?')));
                    } else {
                        throw new RuntimeException("[unexpected!] not handled case");
                    }
                }
            }
            queryBuilder.append(" ");
        }
    }

    if (configuration.useForPrimaryTypes()) {
        String[] pts = filter.getPrimaryTypes().toArray(new String[filter.getPrimaryTypes().size()]);
        StringBuilder ptQueryBuilder = new StringBuilder();
        for (int i = 0; i < pts.length; i++) {
            String pt = pts[i];
            if (i == 0) {
                ptQueryBuilder.append("(");
            }
            if (i > 0 && i < pts.length) {
                ptQueryBuilder.append("OR ");
            }
            ptQueryBuilder.append("jcr\\:primaryType").append(':').append(partialEscape(pt)).append(" ");
            if (i == pts.length - 1) {
                ptQueryBuilder.append(")");
                ptQueryBuilder.append(' ');
            }
        }
        solrQuery.addFilterQuery(ptQueryBuilder.toString());
    }

    if (filter.getQueryStatement() != null && filter.getQueryStatement().contains(QueryImpl.REP_EXCERPT)) {
        if (!solrQuery.getHighlight()) {
            // enable highlighting
            solrQuery.setHighlight(true);
            // defaults
            solrQuery.set("hl.fl", "*");
            solrQuery.set("hl.encoder", "html");
            solrQuery.set("hl.mergeContiguous", true);
            solrQuery.setHighlightSimplePre("<strong>");
            solrQuery.setHighlightSimplePost("</strong>");
        }
    }

    if (configuration.useForPathRestrictions()) {
        Filter.PathRestriction pathRestriction = filter.getPathRestriction();
        if (pathRestriction != null) {
            String path = purgePath(filter, plan.getPathPrefix());
            String fieldName = configuration.getFieldForPathRestriction(pathRestriction);
            if (fieldName != null) {
                if (pathRestriction.equals(Filter.PathRestriction.ALL_CHILDREN)) {
                    solrQuery.addFilterQuery(fieldName + ':' + path);
                } else {
                    queryBuilder.append(fieldName);
                    queryBuilder.append(':');
                    queryBuilder.append(path);
                }
            }
        }
    }

    if (configuration.collapseJcrContentNodes()) {
        solrQuery.addFilterQuery("{!collapse field=" + configuration.getCollapsedPathField() + " min="
                + configuration.getPathDepthField() + " hint=top_fc nullPolicy=expand}");
    }

    if (queryBuilder.length() == 0) {
        queryBuilder.append("*:*");
    }
    String escapedQuery = queryBuilder.toString();
    solrQuery.setQuery(escapedQuery);

    if (log.isDebugEnabled()) {
        log.debug("JCR query {} has been converted to Solr query {}", filter.getQueryStatement(),
                solrQuery.toString());
    }

    return solrQuery;
}

From source file:org.eclipse.rdf4j.sail.solr.SolrIndex.java

License:Open Source License

/**
 * Parse the passed query.//from   www. j  a  va 2s. c o  m
 * 
 * @param query
 *        string
 * @return the parsed query
 * @throws ParseException
 *         when the parsing brakes
 */
@Override
protected Iterable<? extends DocumentScore> query(Resource subject, String query, URI propertyURI,
        boolean highlight) throws MalformedQueryException, IOException {
    SolrQuery q = prepareQuery(propertyURI, new SolrQuery(query));
    if (highlight) {
        q.setHighlight(true);
        String field = (propertyURI != null) ? SearchFields.getPropertyField(propertyURI) : "*";
        q.addHighlightField(field);
        q.setHighlightSimplePre(SearchFields.HIGHLIGHTER_PRE_TAG);
        q.setHighlightSimplePost(SearchFields.HIGHLIGHTER_POST_TAG);
        q.setHighlightSnippets(2);
    }

    QueryResponse response;
    if (q.getHighlight()) {
        q.addField("*");
    } else {
        q.addField(SearchFields.URI_FIELD_NAME);
    }
    q.addField("score");
    try {
        if (subject != null) {
            response = search(subject, q);
        } else {
            response = search(q);
        }
    } catch (SolrServerException e) {
        throw new IOException(e);
    }
    SolrDocumentList results = response.getResults();
    final Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
    return Iterables.transform(results, new Function<SolrDocument, DocumentScore>() {

        @Override
        public DocumentScore apply(SolrDocument document) {
            SolrSearchDocument doc = new SolrSearchDocument(document);
            Map<String, List<String>> docHighlighting = (highlighting != null) ? highlighting.get(doc.getId())
                    : null;
            return new SolrDocumentScore(doc, docHighlighting);
        }
    });
}

From source file:org.opencms.search.solr.CmsSolrIndex.java

License:Open Source License

/**
 * Performs the actual search.<p>//from   www  .  j  a  v  a 2s .  co m
 *
 * @param cms the current OpenCms context
 * @param ignoreMaxRows <code>true</code> to return all all requested rows, <code>false</code> to use max rows
 * @param query the OpenCms Solr query
 * @param response the servlet response to write the query result to, may also be <code>null</code>
 * @param ignoreSearchExclude if set to false, only contents with search_exclude unset or "false" will be found - typical for the the non-gallery case
 * @param filter the resource filter to use
 *
 * @return the found documents
 *
 * @throws CmsSearchException if something goes wrong
 *
 * @see #search(CmsObject, CmsSolrQuery, boolean)
 */
@SuppressWarnings("unchecked")
public CmsSolrResultList search(CmsObject cms, final CmsSolrQuery query, boolean ignoreMaxRows,
        ServletResponse response, boolean ignoreSearchExclude, CmsResourceFilter filter)
        throws CmsSearchException {

    // check if the user is allowed to access this index
    checkOfflineAccess(cms);
    if (!ignoreSearchExclude) {
        query.addFilterQuery(CmsSearchField.FIELD_SEARCH_EXCLUDE + ":\"false\"");
    }

    int previousPriority = Thread.currentThread().getPriority();
    long startTime = System.currentTimeMillis();

    // remember the initial query
    SolrQuery initQuery = query.clone();

    query.setHighlight(false);
    LocalSolrQueryRequest solrQueryRequest = null;
    try {

        // initialize the search context
        CmsObject searchCms = OpenCms.initCmsObject(cms);

        // change thread priority in order to reduce search impact on overall system performance
        if (getPriority() > 0) {
            Thread.currentThread().setPriority(getPriority());
        }

        // the lists storing the found documents that will be returned
        List<CmsSearchResource> resourceDocumentList = new ArrayList<CmsSearchResource>();
        SolrDocumentList solrDocumentList = new SolrDocumentList();

        // Initialize rows, offset, end and the current page.
        int rows = query.getRows() != null ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();
        if (!ignoreMaxRows && (rows > ROWS_MAX)) {
            rows = ROWS_MAX;
        }
        int start = query.getStart() != null ? query.getStart().intValue() : 0;
        int end = start + rows;
        int page = 0;
        if (rows > 0) {
            page = Math.round(start / rows) + 1;
        }

        // set the start to '0' and expand the rows before performing the query
        query.setStart(new Integer(0));
        query.setRows(new Integer((5 * rows * page) + start));

        // perform the Solr query and remember the original Solr response
        QueryResponse queryResponse = m_solr.query(query);
        long solrTime = System.currentTimeMillis() - startTime;

        // initialize the counts
        long hitCount = queryResponse.getResults().getNumFound();
        start = -1;
        end = -1;
        if ((rows > 0) && (page > 0) && (hitCount > 0)) {
            // calculate the final size of the search result
            start = rows * (page - 1);
            end = start + rows;
            // ensure that both i and n are inside the range of foundDocuments.size()
            start = new Long((start > hitCount) ? hitCount : start).intValue();
            end = new Long((end > hitCount) ? hitCount : end).intValue();
        } else {
            // return all found documents in the search result
            start = 0;
            end = new Long(hitCount).intValue();
        }
        long visibleHitCount = hitCount;
        float maxScore = 0;

        // If we're using a postprocessor, (re-)initialize it before using it
        if (m_postProcessor != null) {
            m_postProcessor.init();
        }

        // process found documents
        List<CmsSearchResource> allDocs = new ArrayList<CmsSearchResource>();
        int cnt = 0;
        for (int i = 0; (i < queryResponse.getResults().size()) && (cnt < end); i++) {
            try {
                SolrDocument doc = queryResponse.getResults().get(i);
                CmsSolrDocument searchDoc = new CmsSolrDocument(doc);
                if (needsPermissionCheck(searchDoc)) {
                    // only if the document is an OpenCms internal resource perform the permission check
                    CmsResource resource = filter == null ? getResource(searchCms, searchDoc)
                            : getResource(searchCms, searchDoc, filter);
                    if (resource != null) {
                        // permission check performed successfully: the user has read permissions!
                        if (cnt >= start) {
                            if (m_postProcessor != null) {
                                doc = m_postProcessor.process(searchCms, resource,
                                        (SolrInputDocument) searchDoc.getDocument());
                            }
                            resourceDocumentList.add(new CmsSearchResource(resource, searchDoc));
                            if (null != doc) {
                                solrDocumentList.add(doc);
                            }
                            maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore;
                        }
                        allDocs.add(new CmsSearchResource(resource, searchDoc));
                        cnt++;
                    } else {
                        visibleHitCount--;
                    }
                } else {
                    // if permission check is not required for this index,
                    // add a pseudo resource together with document to the results
                    resourceDocumentList.add(new CmsSearchResource(PSEUDO_RES, searchDoc));
                    solrDocumentList.add(doc);
                    maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore;
                    cnt++;
                }
            } catch (Exception e) {
                // should not happen, but if it does we want to go on with the next result nevertheless
                LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_ERR_RESULT_ITERATION_FAILED_0), e);
            }
        }
        // the last documents were all secret so let's take the last found docs
        if (resourceDocumentList.isEmpty() && (allDocs.size() > 0)) {
            page = Math.round(allDocs.size() / rows) + 1;
            int showCount = allDocs.size() % rows;
            showCount = showCount == 0 ? rows : showCount;
            start = allDocs.size() - new Long(showCount).intValue();
            end = allDocs.size();
            if (allDocs.size() > start) {
                resourceDocumentList = allDocs.subList(start, end);
                for (CmsSearchResource r : resourceDocumentList) {
                    maxScore = maxScore < r.getDocument().getScore() ? r.getDocument().getScore() : maxScore;
                    solrDocumentList.add(((CmsSolrDocument) r.getDocument()).getSolrDocument());
                }
            }
        }
        long processTime = System.currentTimeMillis() - startTime - solrTime;

        // create and return the result
        solrDocumentList.setStart(start);
        solrDocumentList.setMaxScore(new Float(maxScore));
        solrDocumentList.setNumFound(visibleHitCount);

        queryResponse.getResponse().setVal(queryResponse.getResponse().indexOf(QUERY_RESPONSE_NAME, 0),
                solrDocumentList);

        queryResponse.getResponseHeader().setVal(queryResponse.getResponseHeader().indexOf(QUERY_TIME_NAME, 0),
                new Integer(new Long(System.currentTimeMillis() - startTime).intValue()));
        long highlightEndTime = System.currentTimeMillis();
        SolrCore core = m_solr instanceof EmbeddedSolrServer
                ? ((EmbeddedSolrServer) m_solr).getCoreContainer().getCore(getCoreName())
                : null;
        CmsSolrResultList result = null;
        try {
            SearchComponent highlightComponenet = null;
            if (core != null) {
                highlightComponenet = core.getSearchComponent("highlight");
                solrQueryRequest = new LocalSolrQueryRequest(core, queryResponse.getResponseHeader());
            }
            SolrQueryResponse solrQueryResponse = null;
            if (solrQueryRequest != null) {
                // create and initialize the solr response
                solrQueryResponse = new SolrQueryResponse();
                solrQueryResponse.setAllValues(queryResponse.getResponse());
                int paramsIndex = queryResponse.getResponseHeader().indexOf(HEADER_PARAMS_NAME, 0);
                NamedList<Object> header = null;
                Object o = queryResponse.getResponseHeader().getVal(paramsIndex);
                if (o instanceof NamedList) {
                    header = (NamedList<Object>) o;
                    header.setVal(header.indexOf(CommonParams.ROWS, 0), new Integer(rows));
                    header.setVal(header.indexOf(CommonParams.START, 0), new Long(start));
                }

                // set the OpenCms Solr query as parameters to the request
                solrQueryRequest.setParams(initQuery);

                // perform the highlighting
                if ((header != null) && (initQuery.getHighlight()) && (highlightComponenet != null)) {
                    header.add(HighlightParams.HIGHLIGHT, "on");
                    if ((initQuery.getHighlightFields() != null)
                            && (initQuery.getHighlightFields().length > 0)) {
                        header.add(HighlightParams.FIELDS,
                                CmsStringUtil.arrayAsString(initQuery.getHighlightFields(), ","));
                    }
                    String formatter = initQuery.getParams(HighlightParams.FORMATTER) != null
                            ? initQuery.getParams(HighlightParams.FORMATTER)[0]
                            : null;
                    if (formatter != null) {
                        header.add(HighlightParams.FORMATTER, formatter);
                    }
                    if (initQuery.getHighlightFragsize() != 100) {
                        header.add(HighlightParams.FRAGSIZE, new Integer(initQuery.getHighlightFragsize()));
                    }
                    if (initQuery.getHighlightRequireFieldMatch()) {
                        header.add(HighlightParams.FIELD_MATCH,
                                new Boolean(initQuery.getHighlightRequireFieldMatch()));
                    }
                    if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePost())) {
                        header.add(HighlightParams.SIMPLE_POST, initQuery.getHighlightSimplePost());
                    }
                    if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePre())) {
                        header.add(HighlightParams.SIMPLE_PRE, initQuery.getHighlightSimplePre());
                    }
                    if (initQuery.getHighlightSnippets() != 1) {
                        header.add(HighlightParams.SNIPPETS, new Integer(initQuery.getHighlightSnippets()));
                    }
                    ResponseBuilder rb = new ResponseBuilder(solrQueryRequest, solrQueryResponse,
                            Collections.singletonList(highlightComponenet));
                    try {
                        rb.doHighlights = true;
                        DocListAndSet res = new DocListAndSet();
                        SchemaField idField = OpenCms.getSearchManager().getSolrServerConfiguration()
                                .getSolrSchema().getUniqueKeyField();

                        int[] luceneIds = new int[rows];
                        int docs = 0;
                        for (SolrDocument doc : solrDocumentList) {
                            String idString = (String) doc.getFirstValue(CmsSearchField.FIELD_ID);
                            int id = solrQueryRequest.getSearcher().getFirstMatch(
                                    new Term(idField.getName(), idField.getType().toInternal(idString)));
                            luceneIds[docs++] = id;
                        }
                        res.docList = new DocSlice(0, docs, luceneIds, null, docs, 0);
                        rb.setResults(res);
                        rb.setQuery(QParser.getParser(initQuery.getQuery(), null, solrQueryRequest).getQuery());
                        rb.setQueryString(initQuery.getQuery());
                        highlightComponenet.prepare(rb);
                        highlightComponenet.process(rb);
                        highlightComponenet.finishStage(rb);
                    } catch (Exception e) {
                        LOG.error(e.getMessage() + " in query: " + initQuery, new Exception(e));
                    }

                    // Make highlighting also available via the CmsSolrResultList
                    queryResponse.setResponse(solrQueryResponse.getValues());

                    highlightEndTime = System.currentTimeMillis();
                }
            }

            result = new CmsSolrResultList(initQuery, queryResponse, solrDocumentList, resourceDocumentList,
                    start, new Integer(rows), end, page, visibleHitCount, new Float(maxScore), startTime,
                    highlightEndTime);
            if (LOG.isDebugEnabled()) {
                Object[] logParams = new Object[] { new Long(System.currentTimeMillis() - startTime),
                        new Long(result.getNumFound()), new Long(solrTime), new Long(processTime),
                        new Long(result.getHighlightEndTime() != 0 ? result.getHighlightEndTime() - startTime
                                : 0) };
                LOG.debug(query.toString() + "\n"
                        + Messages.get().getBundle().key(Messages.LOG_SOLR_SEARCH_EXECUTED_5, logParams));
            }
            if (response != null) {
                writeResp(response, solrQueryRequest, solrQueryResponse);
            }
        } finally {
            if (solrQueryRequest != null) {
                solrQueryRequest.close();
            }
            if (core != null) {
                core.close();
            }
        }
        return result;
    } catch (Exception e) {
        throw new CmsSearchException(Messages.get().container(Messages.LOG_SOLR_ERR_SEARCH_EXECUTION_FAILD_1,
                CmsEncoder.decode(query.toString()), e), e);
    } finally {
        if (solrQueryRequest != null) {
            solrQueryRequest.close();
        }
        // re-set thread to previous priority
        Thread.currentThread().setPriority(previousPriority);
    }

}

From source file:org.springframework.data.solr.core.DefaultQueryParserTests.java

License:Apache License

@Test
public void testConstructSolrQueryWithEmptyHighlightOption() {
    SimpleHighlightQuery query = new SimpleHighlightQuery(new SimpleStringCriteria("field_1:value_1"));
    query.setHighlightOptions(new HighlightOptions());

    SolrQuery solrQuery = queryParser.constructSolrQuery(query);
    Assert.assertTrue(solrQuery.getHighlight());
    Assert.assertArrayEquals(new String[] { Criteria.WILDCARD }, solrQuery.getHighlightFields());
}

From source file:org.springframework.data.solr.core.DefaultQueryParserTests.java

License:Apache License

@Test
public void testConstructSolrQueryWithoutHighlightOption() {
    SimpleHighlightQuery query = new SimpleHighlightQuery(new SimpleStringCriteria("field_1:value_1"));

    SolrQuery solrQuery = queryParser.constructSolrQuery(query);
    Assert.assertFalse(solrQuery.getHighlight());
}