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

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

Introduction

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

Prototype

public SolrQuery setQuery(String query) 

Source Link

Usage

From source file:net.yacy.search.index.ErrorCacheFiller.java

License:Open Source License

/**
 * Fills the error cache with recently failed document hashes found in the index
 *///  w  ww  .  java  2s  .c o m
@Override
public void run() {
    final SolrQuery params = new SolrQuery();
    params.setParam("defType", "edismax");
    params.setStart(0);
    params.setRows(1000);
    params.setFacet(false);
    params.setSort(new SortClause(CollectionSchema.load_date_dt.getSolrFieldName(), SolrQuery.ORDER.desc)); // load_date_dt = faildate
    params.setFields(CollectionSchema.id.getSolrFieldName());
    params.setQuery(CollectionSchema.failreason_s.getSolrFieldName() + AbstractSolrConnector.CATCHALL_DTERM);
    params.set(CommonParams.DF, CollectionSchema.id.getSolrFieldName()); // DisMaxParams.QF or CommonParams.DF must be given
    SolrDocumentList docList;
    try {
        docList = this.sb.index.fulltext().getDefaultConnector().getDocumentListByParams(params);
        if (docList != null)
            for (int i = docList.size() - 1; i >= 0; i--) {
                SolrDocument doc = docList.get(i);
                String hash = (String) doc.getFieldValue(CollectionSchema.id.getSolrFieldName());
                cache.putHashOnly(hash);
            }
    } catch (IOException e) {
        ConcurrentLog.logException(e);
    }
}

From source file:net.yacy.search.query.QueryParams.java

License:Open Source License

private SolrQuery solrTextQuery(final boolean getFacets, final boolean excludeintext_image) {
    if (this.cachedQuery != null) {
        this.cachedQuery.setStart(this.offset);
        if (!getFacets)
            this.cachedQuery.setFacet(false);
        return this.cachedQuery;
    }/*from w w w  .  j  a va2  s.  c om*/

    // construct query
    final SolrQuery params = getBasicParams(getFacets,
            this.queryGoal.collectionTextFilterQuery(excludeintext_image));
    int rankingProfile = this.ranking.coeff_date == RankingProfile.COEFF_MAX ? 1
            : (this.modifier.sitehash != null || this.modifier.sitehost != null) ? 2 : 0;
    params.setQuery(this.queryGoal.collectionTextQuery().toString());
    Ranking actRanking = indexSegment.fulltext().getDefaultConfiguration().getRanking(rankingProfile); // for a by-date ranking select different ranking profile

    String fq = actRanking.getFilterQuery();
    String bq = actRanking.getBoostQuery();
    String bf = actRanking.getBoostFunction();
    final String qf = actRanking.getQueryFields();
    if (!qf.isEmpty())
        params.setParam(DisMaxParams.QF, qf);
    if (this.queryGoal.getIncludeSize() > 1) {
        // add boost on combined words
        if (bq.length() > 0)
            bq += " ";
        bq += CollectionSchema.text_t.getSolrFieldName() + ":\"" + this.queryGoal.getIncludeString() + "\"^10";
    }
    if (fq.length() > 0) {
        String[] oldfq = params.getFilterQueries();
        ArrayList<String> newfq = new ArrayList<>(oldfq.length + 1);
        for (String x : oldfq)
            newfq.add(x);
        newfq.add(fq);
        params.setFilterQueries(newfq.toArray(new String[newfq.size()]));
    }
    if (bq.length() > 0)
        params.setParam(DisMaxParams.BQ, bq);
    if (bf.length() > 0)
        params.setParam("boost", bf); // a boost function extension, see http://wiki.apache.org/solr/ExtendedDisMax#bf_.28Boost_Function.2C_additive.29

    // prepare result
    ConcurrentLog.info("Protocol", "SOLR QUERY: " + params.toString());
    this.cachedQuery = params;
    return params;
}

From source file:net.yacy.search.query.QueryParams.java

License:Open Source License

private SolrQuery solrImageQuery(boolean getFacets) {
    if (this.cachedQuery != null) {
        this.cachedQuery.setStart(this.offset);
        if (!getFacets)
            this.cachedQuery.setFacet(false);
        return this.cachedQuery;
    }//  ww  w .j  ava2s  .  com

    // construct query
    final SolrQuery params = getBasicParams(getFacets, this.queryGoal.collectionImageFilterQuery());
    params.setQuery(this.queryGoal.collectionImageQuery(this.modifier).toString());

    // set boosts
    StringBuilder bq = new StringBuilder();
    bq.append(CollectionSchema.url_file_ext_s.getSolrFieldName()).append(":\"jpg\"");
    bq.append(" OR ").append(CollectionSchema.url_file_ext_s.getSolrFieldName()).append(":\"tif\"");
    bq.append(" OR ").append(CollectionSchema.url_file_ext_s.getSolrFieldName()).append(":\"tiff\"");
    bq.append(" OR ").append(CollectionSchema.url_file_ext_s.getSolrFieldName()).append(":\"png\"");
    params.setParam(DisMaxParams.BQ, bq.toString());

    // prepare result
    ConcurrentLog.info("Protocol", "SOLR QUERY: " + params.toString());
    this.cachedQuery = params;
    return params;
}

From source file:nl.b3p.viewer.search.PDOKSearchClient.java

License:Open Source License

@Override
public SearchResult search(String term) {
    SearchResult result = new SearchResult();
    try {// w w w.ja  v a 2 s  . co m
        JSONArray respDocs = new JSONArray();
        SolrQuery query = new SolrQuery();
        // add asterisk to make it match partial queries (for autosuggest)
        term += "*";
        if (this.filter != null) {
            term += " " + this.filter;
        }
        query.setQuery(term);
        // specify fields to retrieve (null values wil be omitted in the response),
        //   the default is listed at https://github.com/PDOK/locatieserver/wiki/API-Locatieserver#52url-parameters
        //   this list is probably still longer than needed, so maybe could be pruned
        query.setParam("fl",
                "identificatie,weergavenaam,bron,type,openbareruimte_id,openbareruimtetype,straatnaam,adresseerbaarobject_id,nummeraanduiding_id,huisnummer,huisletter,huisnummertoevoeging,huis_nlt,postcode,woonplaatscode,woonplaatsnaam,gemeentenaam,provinciecode,provincienaam,kadastraal_object_id,kadastrale_gemeentecode,kadastrale_gemeentenaam,kadastrale_sectie,perceelnummer,kadastrale_grootte,gekoppeld_perceel,kadastrale_aanduiding,centroide_rd,boundingbox_rd,geometrie_rd,score");
        query.setRequestHandler("/free");
        QueryResponse rsp = server.query(query);
        SolrDocumentList list = rsp.getResults();

        for (SolrDocument solrDocument : list) {
            JSONObject doc = solrDocumentToResult(solrDocument);
            if (doc != null) {
                respDocs.put(doc);
            }
        }
        result.setResults(respDocs);
        result.setLimitReached(list.getNumFound() > list.size());
    } catch (SolrServerException ex) {
        log.error("Cannot search:", ex);
    }
    return result;
}

From source file:nl.b3p.viewer.search.SolrSearchClient.java

License:Open Source License

@Override
public SearchResult search(String term) {
    SearchResult result = new SearchResult();
    JSONArray respDocs = new JSONArray();
    try {/*from w  w w. j a  v  a 2s  .  c o m*/
        if (term == null) {
            term = "";
        } else {
            term = term.replaceAll("\\:", "\\\\:");
            term += " AND (";
        }
        SolrServer server = SolrInitializer.getServerInstance();
        String extraQuery = createAttributeSourceQuery();
        if (!extraQuery.isEmpty()) {
            term += extraQuery + ")";
        } else {
            term += "searchConfig:\\-1)"; // Dummy expression to always evaluate to false and return no results
        }
        SolrQuery query = new SolrQuery();
        query.setQuery(term);
        query.setRequestHandler("/select");
        QueryResponse rsp = server.query(query);
        SolrDocumentList list = rsp.getResults();

        for (SolrDocument solrDocument : list) {
            JSONObject doc = solrDocumentToResult(solrDocument);
            if (doc != null) {
                respDocs.put(doc);
            }
        }
        result.setResults(respDocs);
        result.setLimitReached(list.getNumFound() > list.size());

    } catch (SolrServerException ex) {
        Logger.getLogger(SolrSearchClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(SolrSearchClient.class.getName()).log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:nl.b3p.viewer.search.SolrSearchClient.java

License:Open Source License

@Override
public JSONArray autosuggest(String term) throws JSONException {
    JSONObject obj = new JSONObject();
    JSONArray respDocs = new JSONArray();
    try {//w  ww  . ja v a 2  s  .  c om
        SolrServer server = SolrInitializer.getServerInstance();

        JSONObject response = new JSONObject();
        response.put("docs", respDocs);
        obj.put("response", response);
        String extraQuery = createAttributeSourceQuery();
        term += " AND (";
        if (!extraQuery.isEmpty()) {
            term += extraQuery + ")";
        } else {
            term += "searchConfig:\\-1)"; // Dummy expression to always evaluate to false and return no results
        }
        SolrQuery query = new SolrQuery();
        query.setQuery(term);
        query.setRequestHandler("/select");
        QueryResponse rsp = server.query(query);
        SolrDocumentList list = rsp.getResults();

        for (SolrDocument solrDocument : list) {
            JSONObject doc = solrDocumentToAutosuggest(solrDocument);
            if (doc != null) {
                respDocs.put(doc);
            }
        }
        response.put("docs", respDocs);
        return respDocs;
    } catch (SolrServerException ex) {
        Logger.getLogger(SolrSearchClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    return respDocs;
}

From source file:nl.knaw.dans.common.solr.converter.SolrQueryRequestConverter.java

License:Apache License

public static SolrQuery convert(SearchRequest request) throws SolrSearchEngineException {
    SolrQuery queryObj = new SolrQuery();

    // set query/* www.  j  a  va  2  s  . co m*/
    String query = "";
    String qstr = request.getQuery().getQueryString();
    if (qstr != null)
        query += qstr;
    FieldSet<?> fieldQueries = request.getFieldQueries();
    if (fieldQueries != null) {
        for (Field<?> fieldQuery : fieldQueries) {
            query += fieldQueryToString(fieldQuery) + " ";
        }
    }
    queryObj.setQuery(query);

    // set filter queries
    FieldSet<?> filterQueries = request.getFilterQueries();
    if (filterQueries != null) {
        int i = 0;
        String[] fq = new String[filterQueries.size()];
        for (Field<?> field : filterQueries) {
            fq[i] = fieldQueryToString(field);
            i++;
        }
        queryObj.setFilterQueries(fq);
    }

    // set sort fields
    List<SortField> sortFields = request.getSortFields();
    if (sortFields != null) {
        for (SortField sortField : sortFields) {
            ORDER order;
            if (sortField.getValue().equals(SortOrder.DESC))
                order = ORDER.desc;
            else
                order = ORDER.asc;
            String sortFieldName = sortField.getName();
            if (sortField.getSortType().equals(SortType.BY_RELEVANCE_SCORE))
                sortFieldName = "score";
            queryObj.addSortField(sortFieldName, order);
        }
    }

    // faceting enabled
    Set<String> facetFields = request.getFacetFields();
    boolean enableFaceting = facetFields != null && facetFields.size() > 0;
    queryObj.setFacet(enableFaceting);
    if (enableFaceting) {
        for (String facetField : facetFields) {
            queryObj.addFacetField(facetField);
        }
    }

    // hit highlighting
    queryObj.setHighlight(request.isHighlightingEnabled());

    // paging
    queryObj.setRows(request.getLimit());
    queryObj.setStart(request.getOffset());

    // misc settings
    queryObj.setIncludeScore(true);

    return queryObj;
}

From source file:nl.knaw.huygens.facetedsearch.AbstractSolrServer.java

License:Open Source License

@Override
public Map<String, Object> search(FacetedSearchParameters<?> fsp) throws IndexException {
    ElaborateSearchParameters sp = (ElaborateSearchParameters) fsp;
    Log.info("searchparameters={}", sp);
    queryComposer.compose(sp);/*from  ww  w.  j  a  va  2  s  . co m*/
    String queryString = queryComposer.getSearchQuery();
    String[] facetFields = getFacetFields(sp);
    //      Log.debug("search({},{})", queryString, sp.getSort());
    Map<String, String> textFieldMap = sp.getTextFieldsToSearch();

    SolrQuery query = new SolrQuery();
    String[] fieldsToReturn = getIndexFieldToReturn(sp.getResultFields());
    query.setQuery(queryString)//
            .setFields(fieldsToReturn)//
            .setRows(ROWS)//
            .addFacetField(facetFields)//
            .setFacetMinCount(1)//
            .setFacetLimit(FACET_LIMIT);
    if (queryComposer.mustHighlight()) {
        query//
                .setHighlight(true)//
                .setHighlightSnippets(500)//
                .setHighlightFragsize(HIGHLIGHT_FRAGSIZE);

        query.set(HighlightParams.MERGE_CONTIGUOUS_FRAGMENTS, false);
        query.set(HighlightParams.MAX_CHARS, -1);
        query.set(HighlightParams.FIELDS, textFieldMap.keySet().toArray(new String[textFieldMap.size()]));
        query.set(HighlightParams.Q, queryComposer.getHighlightQuery());
    }
    query = setSort(query, sp);

    Map<String, Object> data = getSearchData(sp, facetFields, query, fieldsToReturn);
    return data;
}

From source file:org.ala.dao.FulltextSearchDaoImplSolr.java

License:Open Source License

/**
  * Re-usable method for performing SOLR searches - takes query string input
  */*from  w  w w .j  av a  2 s. c o m*/
  * @param queryString
  * @param filterQuery
  * @param pageSize
  * @param startIndex
  * @param sortField
  * @param sortDirection
  * @return
  * @throws SolrServerException
  */
private SearchResultsDTO doSolrSearch(String queryString, String filterQuery[], String[] facets,
        Integer pageSize, Integer startIndex, String sortField, String sortDirection) throws Exception {
    SolrQuery solrQuery = initSolrQuery(facets); // general search settings
    solrQuery.setFields("*", "score");
    solrQuery.setQuery(queryString);
    return doSolrQuery(solrQuery, filterQuery, pageSize, startIndex, sortField, sortDirection);
}

From source file:org.ala.dao.FulltextSearchDaoImplSolr.java

License:Open Source License

/**
 * Re-usable method for performing a SOLR search that returns the RAW query response
 * @param queryString//from w w w . ja  v  a 2  s. c  om
 * @param filterQuery
 * @param pageSize
 * @param startIndex
 * @param sortField
 * @param sortDirection
 * @return
 * @throws Exception
 */
private QueryResponse doSolrSearchForQueryResponse(String queryString, String filterQuery[], String[] fields,
        Integer pageSize, Integer startIndex, String sortField, String sortDirection) throws Exception {
    SolrQuery solrQuery = initSolrQuery(null); // general search settings
    solrQuery.setFields(fields);
    solrQuery.setQuery(queryString);
    return getSolrQueryResponse(solrQuery, filterQuery, pageSize, startIndex, sortField, sortDirection);
}