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

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

Introduction

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

Prototype

public SolrQuery setTimeAllowed(Integer milliseconds) 

Source Link

Document

Set the maximum time allowed for this query.

Usage

From source file:com.frank.search.solr.core.QueryParserBase.java

License:Apache License

/**
 * Set/*from  w ww.  jav a  2s  .c  o  m*/
 * {@link org.apache.solr.client.solrj.SolrQuery#setTimeAllowed(Integer)}
 *
 * @param solrQuery
 * @param timeAllowed
 */
protected void appendTimeAllowed(SolrQuery solrQuery, Integer timeAllowed) {
    if (timeAllowed != null) {
        solrQuery.setTimeAllowed(timeAllowed);
    }
}

From source file:no.sesat.search.mode.command.SolrSearchCommand.java

License:Open Source License

/** Override this to set additional parameters in the SolrQuery.
 * Crucial for any override to call super.modifyQuery(query)
 **//*from w w  w  .  j ava  2s. co  m*/
protected void modifyQuery(final SolrQuery query) {

    // @XXX does this ruin solr caching
    query.set("uniqueId", context.getDataModel().getParameters().getUniqueId());

    // add any filtering query
    if (0 < getSearchConfiguration().getFilteringQuery().length()) {
        query.setFilterQueries(getSearchConfiguration().getFilteringQuery());
    }

    // also add any filter
    if (0 < getFilter().length()) {
        query.addFilterQuery(getFilter());
    }

    // custom query type
    if (null != getSearchConfiguration().getQueryType()
            && 0 < getSearchConfiguration().getQueryType().length()) {
        query.setQueryType(getSearchConfiguration().getQueryType());
    }

    // The request handler may be configured in the index which fields to return in the results
    if (0 < getSearchConfiguration().getResultFieldMap().size()) {
        query.setFields(getSearchConfiguration().getResultFieldMap().keySet().toArray(new String[] {}));
    }

    createFacets(query);

    // when the root logger is set to DEBUG do not limit connection times
    if (Logger.getRootLogger().getLevel().isGreaterOrEqual(Level.INFO)) {
        query.setTimeAllowed(getSearchConfiguration().getTimeout());
    }

    // sorting
    if (isUserSortable()) {
        final String sort = getUserSortBy();
        if (null != sort) {
            final String[] sortSplit = sort.split(" ");
            query.addSortField(sortSplit[0], SolrQuery.ORDER.valueOf(sortSplit[1]));
        }
    }
    final Map<String, String> sortMap = getSearchConfiguration().getSortMap();
    for (Map.Entry<String, String> entry : sortMap.entrySet()) {
        final SolrQuery.ORDER order = SolrQuery.ORDER.valueOf(entry.getValue());
        query.addSortField(entry.getKey(), order);
    }
}

From source file:no.sesat.search.query.token.SolrTokenEvaluator.java

License:Open Source License

/**
 * Search solr and find out if the given tokens are company, firstname, lastname etc
 * @param query//  w w  w  . j ava  2s . c  o m
 */
@SuppressWarnings("unchecked")
private Map<String, List<TokenMatch>> query(final String query) throws EvaluationException {

    LOG.trace("queryFast( " + query + " )");
    Map<String, List<TokenMatch>> result = null;

    if (query != null && 0 < query.length()) {

        try {
            result = (Map<String, List<TokenMatch>>) CACHE_QUERY.getFromCache(query, REFRESH_PERIOD);

        } catch (NeedsRefreshException nre) {

            boolean updatedCache = false;
            result = new HashMap<String, List<TokenMatch>>();
            String url = null;

            try {
                final String token = query.replaceAll("\"", "");

                // set up query
                final SolrQuery solrQuery = new SolrQuery().setQuery("list_entry_shingle:\"" + token + "\"")
                        .setRows(INITIAL_ROWS_TO_FETCH);

                // when the root logger is set to DEBUG do not limit connection times
                if (Logger.getRootLogger().getLevel().isGreaterOrEqual(Level.INFO)) {
                    // default timeout is half second. TODO make configuration.
                    solrQuery.setTimeAllowed(500);
                }

                // query for hits
                QueryResponse response = factory.getSolrServer().query(solrQuery);
                final int numberOfHits = (int) response.getResults().getNumFound();

                boolean more = false;
                do {
                    DUMP.info(solrQuery.toString());

                    final SolrDocumentList docs = response.getResults();

                    // iterate through docs
                    for (SolrDocument doc : docs) {

                        final String name = (String) doc.getFieldValue("list_name");
                        final String exactname = EXACT_PREFIX + name;

                        // remove words made solely of characters that the parser considers whitespace
                        final String hit = ((String) doc.getFieldValue("list_entry"))
                                .replaceAll("\\b" + SKIP_REGEX + "+\\b", " ");

                        final String synonym = (String) doc.getFieldValue("list_entry_synonym");

                        if (factory.usesListName(name, exactname)) {

                            addMatch(name, hit, synonym, query, result);

                            if (hit.equalsIgnoreCase(query.trim())) {

                                addMatch(exactname, hit, synonym, query, result);
                            }
                        }
                    }

                    int rest = numberOfHits - INITIAL_ROWS_TO_FETCH;
                    if (!more && rest > 0) {
                        more = true;
                        solrQuery.setStart(INITIAL_ROWS_TO_FETCH);
                        solrQuery.setRows(rest);
                        // query
                        response = factory.getSolrServer().query(solrQuery);
                    } else {
                        more = false;
                    }
                } while (more);

                result = Collections.<String, List<TokenMatch>>unmodifiableMap(result);
                CACHE_QUERY.putInCache(query, result);
                updatedCache = true;

            } catch (SolrServerException ex) {
                LOG.error(ex.getMessage(), ex);
                throw new EvaluationException(ERR_QUERY_FAILED + url, ex);

            } finally {
                if (!updatedCache) {
                    CACHE_QUERY.cancelUpdate(query);
                }
            }
        }
    } else {
        result = Collections.<String, List<TokenMatch>>emptyMap();
    }
    return result;
}

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

License:Apache License

private SolrQuery createQuery(String queryString, int startPage, int pageSize, boolean useDismax) {
    SolrQuery query = new SolrQuery(queryString);
    query.setTimeAllowed(queryTimeout);
    query.setIncludeScore(true); // The relevance (of each results element) to the search terms.
    query.setHighlight(true);/*from  w  w w.ja va2s .  c  om*/

    if (useDismax) {
        query.set("defType", "dismax");
    }

    //TODO: Put The "options" from the "queryField" picklist into a config file.
    //This list matches the "options" from the "queryField" picklist on unformattedSearch.ftl,
    //without the "date" fields.

    query.set("hl.fl", this.highlightFields);
    query.set("hl.requireFieldMatch", true);
    query.setStart(startPage * pageSize); // Which results element to return first in this batch.
    query.setRows(pageSize); // The number of results elements to return.
    // request only fields that we need to display
    query.setFields("id", "score", "title_display", "publication_date", "eissn", "journal", "article_type",
            "author_display");
    query.addFacetField("subject_facet");
    query.addFacetField("author_facet");
    query.addFacetField("editor_facet");
    query.addFacetField("article_type_facet");
    query.addFacetField("affiliate_facet");
    query.set("facet.method", "fc");
    query.setFacetLimit(MAX_FACET_SIZE);
    query.setFacetMinCount(MIN_FACET_COUNT);
    // Add a filter to ensure that Solr never returns partial documents
    query.addFilterQuery(createFilterFullDocuments());

    return query;
}

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

License:Apache License

private SolrQuery createJournalFacetQuery(String queryString, boolean useDismax) {
    SolrQuery query = new SolrQuery(queryString);
    query.setTimeAllowed(queryTimeout);
    query.setIncludeScore(false);//from  ww  w .  ja v a2  s .  c o  m
    query.setHighlight(false);
    query.setRows(0);
    query.setFacetLimit(MAX_FACET_SIZE);
    query.setFacetMinCount(MIN_FACET_COUNT);

    if (useDismax) {
        query.set("defType", "dismax");
    }

    query.addFacetField("cross_published_journal_key");
    // Add a filter to ensure that Solr never returns partial documents
    query.addFilterQuery(createFilterFullDocuments());

    return query;
}

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

License:Apache License

private SolrQuery createKeywordFacetQuery(String queryString) {
    SolrQuery query = new SolrQuery();
    query.setTimeAllowed(queryTimeout);
    query.setIncludeScore(false);//from   w ww.  j  av a2s. c  o m
    query.setHighlight(false);
    query.setRows(0);
    query.set("defType", "dismax");
    query.set("qf", "doc_partial_body");
    query.addFacetField("doc_partial_type");
    query.setFacetLimit(MAX_FACET_SIZE);
    query.setFacetMinCount(MIN_FACET_COUNT);
    // Add a filter to ensure that Solr never returns partial documents
    query.addFilterQuery(createFilterPartialDocuments());
    query.setQuery(queryString);

    return query;
}

From source file:org.ambraproject.service.feed.FeedServiceImpl.java

License:Apache License

@Override
public Document getSearchArticles(final FeedSearchParameters sParams) throws ApplicationException {

    log.debug("Performing RSS Feed Search");

    SolrQuery query = null;

    if (sParams.getUnformattedQuery().equals("")) {
        log.debug("Simple Rss Search performed on the String: " + sParams.getQuery());
        query = new SolrQuery(sParams.getQuery());
        query.set("defType", "dismax");
    } else {/*ww w  .  ja  v a  2  s  .c om*/
        log.debug("Simple Rss Search performed on the String: " + sParams.getUnformattedQuery());
        query = new SolrQuery(sParams.getUnformattedQuery());
    }

    query.setTimeAllowed(queryTimeout);
    query.setIncludeScore(true); // The relevance (of each results element) to the search terms.
    query.setHighlight(false);
    // request only fields that we need
    query.setFields("id", "title_display", "publication_date", "author_without_collab_display",
            "author_collab_only_display", "author_display", "volume", "issue", "article_type",
            "subject_hierarchy", "abstract_primary_display", "copyright");
    query.addFilterQuery("doc_type:full");
    query.addFilterQuery("!article_type_facet:\"Issue Image\"");
    query.addFacetField("cross_published_journal_key");

    // Form field description: "Journals".  Query Filter.
    if (sParams.getFilterJournals() != null && sParams.getFilterJournals().length > 0) {
        query.addFilterQuery(createFilterLimitForJournals(sParams.getFilterJournals()));
    }

    // Form field description: "Subject Categories".  Query Filter.
    if (sParams.getFilterSubjects() != null && sParams.getFilterSubjects().length > 0) {
        query.addFilterQuery(createFilterLimitForSubject(sParams.getFilterSubjects()));
    }

    // Form field description: "Article Types".  Query Filter.
    if (sParams.getFilterArticleType() != null && sParams.getFilterArticleType().length > 0) {
        query.addFilterQuery(createFilterLimitForArticleType(sParams.getFilterArticleType()));
    }

    //Set the sort ordering for results, if applicable.
    setSort(query, sParams);

    //If the keywords parameter is specified, we need to change what field we're querying against
    //aka, body, conclusions, materials and methods ... etc ...
    if (sParams.getFilterKeyword().length() > 0) {
        String fieldkey = sParams.getFilterKeyword();

        if (!validKeywords.containsKey(fieldkey)) {
            throw new ApplicationException("Invalid filterKeyword value of " + fieldkey + " specified");
        }
        String fieldName = (String) validKeywords.get(fieldkey);
        query.set("qf", fieldName);
    }

    query.set("wt", "xml");

    Document result = null;
    try {
        result = solrHttpService.makeSolrRequestForRss(query.toString());
    } catch (SolrException e) {
        e.printStackTrace();
    }
    return result;
}

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

License:Apache License

private SolrQuery createQuery(String queryString, int startPage, int pageSize, boolean useDismax) {
    SolrQuery query = new SolrQuery(queryString);
    query.setTimeAllowed(queryTimeout);
    query.setIncludeScore(true); // The relevance (of each results element) to the search terms.
    query.setHighlight(false);/*from  ww w.  j  av  a 2 s. co m*/

    if (useDismax) {
        query.set("defType", "dismax");
    }

    //TODO: Put The "options" from the "queryField" picklist into a config file.
    //This list matches the "options" from the "queryField" picklist on unformattedSearch.ftl,
    //without the "date" fields.

    query.setStart(startPage * pageSize); // Which results element to return first in this batch.
    query.setRows(pageSize); // The number of results elements to return.
    // request only fields that we need to display
    query.setFields("id", "score", "title_display", "publication_date", "eissn", "journal", "article_type",
            "author_display", "abstract", "abstract_primary_display", "striking_image", "figure_table_caption",
            "subject", "expression_of_concern", "retraction");
    query.addFacetField("subject_facet");
    query.addFacetField("author_facet");
    query.addFacetField("editor_facet");
    query.addFacetField("article_type_facet");
    query.addFacetField("affiliate_facet");
    query.set("facet.method", "fc");
    query.setFacetLimit(MAX_FACET_SIZE);
    query.setFacetMinCount(MIN_FACET_COUNT);
    // Add a filter to ensure that Solr never returns partial documents
    query.addFilterQuery(createFilterFullDocuments());

    return query;
}

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

License:Apache License

private SolrQuery createFacetsQuery(String queryString, String field, boolean useDismax) {
    SolrQuery query = new SolrQuery(queryString);
    query.setTimeAllowed(queryTimeout);
    query.setIncludeScore(false);/*from   w ww .  ja va2  s. c  om*/
    query.setHighlight(false);
    query.setRows(0);
    query.setFacetLimit(MAX_FACET_SIZE);
    query.setFacetMinCount(MIN_FACET_COUNT);

    if (useDismax) {
        query.set("defType", "dismax");
    }

    query.addFacetField(field);
    // Add a filter to ensure that Solr never returns partial documents
    query.addFilterQuery(createFilterFullDocuments());

    return query;
}

From source file:org.codelibs.fess.service.SearchService.java

License:Apache License

public List<Map<String, Object>> getDocumentList(final String query, final int start, final int rows,
        final FacetInfo facetInfo, final GeoInfo geoInfo, final MoreLikeThisInfo mltInfo,
        final String[] responseFields, final String[] docValuesFields, final boolean forUser) {
    if (start > queryHelper.getMaxSearchResultOffset()) {
        throw new ResultOffsetExceededException("The number of result size is exceeded.");
    }//from  w w  w  . ja  v  a  2 s  . c om

    final long startTime = System.currentTimeMillis();

    final SolrGroup solrGroup = solrGroupManager.getSolrGroup(QueryType.QUERY);

    QueryResponse queryResponse = null;
    final SolrQuery solrQuery = new SolrQuery();
    final SearchQuery searchQuery = queryHelper.build(query, forUser);
    final String q = searchQuery.getQuery();
    if (StringUtil.isNotBlank(q)) {
        // fields
        solrQuery.setFields(responseFields);
        // query
        solrQuery.setQuery(q);
        solrQuery.setStart(start);
        solrQuery.setRows(rows);
        solrQuery.set("mm", searchQuery.getMinimumShouldMatch());
        solrQuery.set("defType", searchQuery.getDefType());
        for (final Map.Entry<String, String[]> entry : queryHelper.getQueryParamMap().entrySet()) {
            solrQuery.set(entry.getKey(), entry.getValue());
        }
        // filter query
        if (searchQuery.hasFilterQueries()) {
            solrQuery.addFilterQuery(searchQuery.getFilterQueries());
        }
        // sort
        final SortField[] sortFields = searchQuery.getSortFields();
        if (sortFields.length != 0) {
            for (final SortField sortField : sortFields) {
                solrQuery.addSort(sortField.getField(),
                        Constants.DESC.equals(sortField.getOrder()) ? SolrQuery.ORDER.desc
                                : SolrQuery.ORDER.asc);
            }
        } else if (queryHelper.hasDefaultSortFields()) {
            for (final SortField sortField : queryHelper.getDefaultSortFields()) {
                solrQuery.addSort(sortField.getField(),
                        Constants.DESC.equals(sortField.getOrder()) ? SolrQuery.ORDER.desc
                                : SolrQuery.ORDER.asc);
            }
        }
        // highlighting
        if (queryHelper.getHighlightingFields() != null && queryHelper.getHighlightingFields().length != 0) {
            for (final String hf : queryHelper.getHighlightingFields()) {
                solrQuery.addHighlightField(hf);
            }
            solrQuery.setHighlightSnippets(queryHelper.getHighlightSnippetSize());
        }
        // shards
        if (queryHelper.getShards() != null) {
            solrQuery.setParam("shards", queryHelper.getShards());
        }
        // geo
        if (geoInfo != null && geoInfo.isAvailable()) {
            solrQuery.addFilterQuery(geoInfo.toGeoQueryString());
            final String additionalGeoQuery = queryHelper.getAdditionalGeoQuery();
            if (StringUtil.isNotBlank(additionalGeoQuery)) {
                solrQuery.addFilterQuery(additionalGeoQuery);
            }
        }
        // facets
        if (facetInfo != null) {
            solrQuery.setFacet(true);
            if (facetInfo.field != null) {
                for (final String f : facetInfo.field) {
                    if (queryHelper.isFacetField(f)) {
                        solrQuery.addFacetField(f);
                    } else {
                        throw new FessSolrQueryException("EFESS0002", new Object[] { f });
                    }
                }
            }
            if (facetInfo.query != null) {
                for (final String fq : facetInfo.query) {
                    final String facetQuery = queryHelper.buildFacetQuery(fq);
                    if (StringUtil.isNotBlank(facetQuery)) {
                        solrQuery.addFacetQuery(facetQuery);
                    } else {
                        throw new FessSolrQueryException("EFESS0003", new Object[] { fq, facetQuery });
                    }
                }
            }
            if (facetInfo.limit != null) {
                solrQuery.setFacetLimit(Integer.parseInt(facetInfo.limit));
            }
            if (facetInfo.minCount != null) {
                solrQuery.setFacetMinCount(Integer.parseInt(facetInfo.minCount));
            }
            if (facetInfo.missing != null) {
                solrQuery.setFacetMissing(Boolean.parseBoolean(facetInfo.missing));
            }
            if (facetInfo.prefix != null) {
                solrQuery.setFacetPrefix(facetInfo.prefix);
            }
            if (facetInfo.sort != null && queryHelper.isFacetSortValue(facetInfo.sort)) {
                solrQuery.setFacetSort(facetInfo.sort);
            }
        }
        // mlt
        if (mltInfo != null) {
            final String mltField = queryHelper.getMoreLikeThisField(mltInfo.field);
            if (mltField != null) {
                solrQuery.set("mlt", true);
                if (mltInfo.count != null) {
                    solrQuery.set("mlt.count", Integer.parseInt(mltInfo.count));
                }
                solrQuery.set("mlt.fl", mltField);
            }
        }

        if (queryHelper.getTimeAllowed() >= 0) {
            solrQuery.setTimeAllowed(queryHelper.getTimeAllowed());
        }
        final Set<Entry<String, String[]>> paramSet = queryHelper.getRequestParameterSet();
        if (!paramSet.isEmpty()) {
            for (final Map.Entry<String, String[]> entry : paramSet) {
                solrQuery.set(entry.getKey(), entry.getValue());
            }
        }

        if (docValuesFields != null) {
            for (final String docValuesField : docValuesFields) {
                solrQuery.add(Constants.DCF, docValuesField);
            }
        }

        queryResponse = solrGroup.query(solrQuery, SolrRequest.METHOD.POST);
    }
    final long execTime = System.currentTimeMillis() - startTime;

    final QueryResponseList queryResponseList = ComponentUtil.getQueryResponseList();
    queryResponseList.init(queryResponse, rows);
    queryResponseList.setSearchQuery(q);
    queryResponseList.setSolrQuery(solrQuery.toString());
    queryResponseList.setExecTime(execTime);
    return queryResponseList;
}