Example usage for org.apache.solr.common.params CommonParams START

List of usage examples for org.apache.solr.common.params CommonParams START

Introduction

In this page you can find the example usage for org.apache.solr.common.params CommonParams START.

Prototype

String START

To view the source code for org.apache.solr.common.params CommonParams START.

Click Source Link

Document

zero based offset of matching documents to retrieve

Usage

From source file:com.tsgrp.solr.handler.NYPhilSearchHandler.java

License:Mozilla Public License

/**
 * @see org.apache.solr.handler.component.SearchHandler#handleRequestBody(org.apache.solr.request.SolrQueryRequest,
 *      org.apache.solr.request.SolrQueryResponse)
 *//*from   w ww.  jav a  2s  .c  om*/
@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp)
        throws Exception, ParseException, InstantiationException, IllegalAccessException {
    SolrParams requestParams = req.getParams();

    NamedList<Object> params = requestParams.toNamedList();

    //for now lets echo the handler and all the params for debugging purposes
    //params.add( CommonParams.HEADER_ECHO_HANDLER, Boolean.TRUE );
    //params.add( CommonParams.HEADER_ECHO_PARAMS, CommonParams.EchoParamStyle.ALL );

    String rows = (String) params.get(CommonParams.ROWS);
    if (rows == null || rows.trim().length() < 1) {
        //setup items per page, default to 10 items
        params.add(CommonParams.ROWS, 10);
        rows = "10";
    }

    //enable faceting and only return facets with at least 1 item
    params.add(FacetParams.FACET, Boolean.TRUE);
    params.add(FacetParams.FACET_MINCOUNT, 1);

    //defult ordering to index order (alphabetical)
    params.add(FacetParams.FACET_SORT, FacetParams.FACET_SORT_INDEX);

    //only return a maximum of 10 facet values
    params.add(FacetParams.FACET_LIMIT, 10);

    //always add facets unless they are explicitly not requested
    String addFacets = (String) params.get(PARAM_GENERATE_FACETS);
    boolean generateFacets = (addFacets == null) ? true : addFacets.equalsIgnoreCase("true");

    //enable highlighting
    params.add(HighlightParams.HIGHLIGHT, Boolean.TRUE);

    //remove the query if provided, always want to use our translated query
    String originalQuery = (String) params.remove(CommonParams.Q);

    if (logger.isDebugEnabled()) {
        logger.debug("Original query: " + originalQuery);
    }

    //setup sorting params
    String sortColumn = (String) params.get(PARAM_SORT_COLUMN);
    String sortOrder = (String) params.get(PARAM_SORT_ORDER);
    if (sortColumn != null && sortOrder != null) {
        params.add(CommonParams.SORT, sortColumn + " " + sortOrder);
    }

    //get date fields
    String sDateFrom = (String) params.get(PARAM_DATE_FROM);
    String sDateTo = (String) params.get(PARAM_DATE_TO);
    Date dateFrom = null;
    Date dateTo = null;
    if (sDateFrom != null && sDateTo != null) {
        dateFrom = DATE_FORMAT_PARAM.parse(sDateFrom);
        dateTo = DATE_FORMAT_PARAM.parse(sDateTo);
    }

    String keywords = (String) params.get(PARAM_KEYWORDS);

    if (keywords == null || keywords.trim().length() < 1) {
        //query everything since nothing was provided
        keywords = "*";
    }

    //always use the extended dismax parser
    params.add("defType", ExtendedDismaxQParserPlugin.NAME);

    //the keywords sent in are the query since we're in DISMAX mode
    params.add(CommonParams.Q, keywords);

    String pageIndex = (String) params.get(PARAM_PAGE_INDEX);
    String resultsPerPage = (String) params.get(PARAM_RESULTS_PER_PAGE);
    if (resultsPerPage == null || resultsPerPage.trim().length() < 0) {
        resultsPerPage = "10";
    }

    if (pageIndex == null || pageIndex.trim().length() < 1) {
        pageIndex = "1";
    }

    //figure out the skip count, use the (pageIndex - 1) * resultsPerPage
    //ie pageIndex = 3, 10 results per page, we'll set start to (3-1)*10 = 20
    int start = (Integer.parseInt(pageIndex) - 1) * Integer.parseInt(resultsPerPage);
    params.add(CommonParams.START, start);

    String doctype = (String) params.get(PARAM_DOCTYPE);
    if (doctype == null || doctype.trim().length() < 1) {
        doctype = "";
    }

    String facetQuery = (String) params.get(PARAM_FACET_QUERY);
    if (facetQuery != null && facetQuery.trim().length() > 0) {
        //facetQuery is pre formatted and correct, just add it as a filter query
        params.add(CommonParams.FQ, facetQuery);
    }

    String suggestedQuery = (String) params.get(PARAM_SUGGESTED_QUERY);
    if (suggestedQuery != null && suggestedQuery.trim().length() > 0) {
        //suggestedQuery is pre formatted and correct, just add it as a filter query
        params.add(CommonParams.FQ, suggestedQuery);
    }

    //base fields
    params.add(DisMaxParams.QF, "nyp:DocumentType");
    params.add(DisMaxParams.QF, "nyp:Notes");

    //program fields
    params.add(DisMaxParams.QF, "npp:ProgramID");
    params.add(DisMaxParams.QF, "npp:Season");
    params.add(DisMaxParams.QF, "npp:OrchestraCode");
    params.add(DisMaxParams.QF, "npp:OrchestraName");
    params.add(DisMaxParams.QF, "npp:LocationName");
    params.add(DisMaxParams.QF, "npp:VenueName");
    params.add(DisMaxParams.QF, "npp:EventTypeName");
    params.add(DisMaxParams.QF, "npp:SubEventName");
    params.add(DisMaxParams.QF, "npp:ConductorName");
    params.add(DisMaxParams.QF, "npp:SoloistsNames");
    params.add(DisMaxParams.QF, "npp:SoloistsInstrumentName");
    params.add(DisMaxParams.QF, "npp:WorksComposerNames");
    params.add(DisMaxParams.QF, "npp:WorksTitle");
    params.add(DisMaxParams.QF, "npp:WorksShortTitle");
    params.add(DisMaxParams.QF, "npp:WorksConductorNames");

    //printedMusic fields
    params.add(DisMaxParams.QF, "npm:LibraryID");
    params.add(DisMaxParams.QF, "npm:ShortTitle");
    params.add(DisMaxParams.QF, "npm:ComposerName");
    params.add(DisMaxParams.QF, "npm:PublisherName");
    params.add(DisMaxParams.QF, "npm:ComposerNameTitle");
    params.add(DisMaxParams.QF, "npm:ScoreMarkingArtist");
    params.add(DisMaxParams.QF, "npm:ScoreEditionTypeDesc");
    params.add(DisMaxParams.QF, "npm:ScoreNotes");

    //part fields
    params.add(DisMaxParams.QF, "npm:PartTypeDesc");
    params.add(DisMaxParams.QF, "npm:PartMarkingArtist");
    params.add(DisMaxParams.QF, "npm:UsedByArtistName");

    //businessRecord fields
    params.add(DisMaxParams.QF, "npb:BoxNumber");
    params.add(DisMaxParams.QF, "npb:RecordGroup");
    params.add(DisMaxParams.QF, "npb:Series");
    params.add(DisMaxParams.QF, "npb:SubSeries");
    params.add(DisMaxParams.QF, "npb:Folder");
    params.add(DisMaxParams.QF, "npb:Names");
    params.add(DisMaxParams.QF, "npb:Subject");
    params.add(DisMaxParams.QF, "npb:Abstract");

    //visual fields
    params.add(DisMaxParams.QF, "npv:ID");
    params.add(DisMaxParams.QF, "npv:BoxNumber");
    params.add(DisMaxParams.QF, "npv:PhilharmonicSource");
    params.add(DisMaxParams.QF, "npv:OutsideSource");
    params.add(DisMaxParams.QF, "npv:Photographer");
    params.add(DisMaxParams.QF, "npv:CopyrightHolder");
    params.add(DisMaxParams.QF, "npv:PlaceOfImage");
    params.add(DisMaxParams.QF, "npv:PersonalNames");
    params.add(DisMaxParams.QF, "npv:CorporateNames");
    params.add(DisMaxParams.QF, "npv:Event");
    params.add(DisMaxParams.QF, "npv:ImageType");
    params.add(DisMaxParams.QF, "npv:LocationName");
    params.add(DisMaxParams.QF, "npv:VenueName");

    //audio fields
    params.add(DisMaxParams.QF, "npa:ProgramID");
    params.add(DisMaxParams.QF, "npa:Location");
    params.add(DisMaxParams.QF, "npa:EventTypeName");
    params.add(DisMaxParams.QF, "npa:ConductorName");
    params.add(DisMaxParams.QF, "npa:SoloistsAndInstruments");
    params.add(DisMaxParams.QF, "npa:ComposerWork");
    params.add(DisMaxParams.QF, "npa:OrchestraName");
    params.add(DisMaxParams.QF, "npa:IntermissionFeature");
    params.add(DisMaxParams.QF, "npa:LocationName");
    params.add(DisMaxParams.QF, "npa:VenueName");
    params.add(DisMaxParams.QF, "npa:SubEventName");
    params.add(DisMaxParams.QF, "npa:URLLocation");
    params.add(DisMaxParams.QF, "npa:IntermissionGuests");
    params.add(DisMaxParams.QF, "npa:Announcer");

    //video fields
    params.add(DisMaxParams.QF, "npx:ProgramID");
    params.add(DisMaxParams.QF, "npx:Location");
    params.add(DisMaxParams.QF, "npx:EventTypeName");
    params.add(DisMaxParams.QF, "npx:ConductorName");
    params.add(DisMaxParams.QF, "npx:SoloistsAndInstruments");
    params.add(DisMaxParams.QF, "npx:ComposerNameWork");
    params.add(DisMaxParams.QF, "npx:OrchestraName");
    params.add(DisMaxParams.QF, "npx:IntermissionFeature");
    params.add(DisMaxParams.QF, "npx:LocationName");
    params.add(DisMaxParams.QF, "npx:VenueName");
    params.add(DisMaxParams.QF, "npx:SubEventName");
    params.add(DisMaxParams.QF, "npx:IntermissionGuests");
    params.add(DisMaxParams.QF, "npx:Announcer");

    params.add(DisMaxParams.QF, "npt:tagged");

    //add in all the restrictions that can be applied to a document type count in the same filter query

    //this includes all DATE range queries
    //if a date query does not exist, the TYPE is queried so all results are shown
    //restriction is applied to business records so only the web publishable items are shown
    StringBuffer filterTypesCountsQuery = new StringBuffer();

    if (dateFrom != null && dateTo != null) {
        //program date query
        filterTypesCountsQuery.append("(npp\\:Date:[" + solrField.toExternal(dateFrom) + " TO "
                + solrField.toExternal(dateTo) + "])");

        //printedMusic (scores) and parts have no date range, so just or in the type so those results come back
        filterTypesCountsQuery.append(" OR (nyp\\:DocumentType:Printed Music)");
        filterTypesCountsQuery.append(" OR (nyp\\:DocumentType:Part)");

        //business record range AND web publishable restriction
        filterTypesCountsQuery
                .append(" OR (nyp\\:WebPublishable:true AND ((npb\\:DateFrom:[" + solrField.toExternal(dateFrom)
                        + " TO *] AND npb\\:DateTo:[* TO " + solrField.toExternal(dateTo) + "])");
        filterTypesCountsQuery.append(" OR (npb\\:DateFrom:[* TO " + solrField.toExternal(dateFrom)
                + "] AND npb\\:DateTo:[* TO " + solrField.toExternal(dateTo) + "] AND npb\\:DateTo:["
                + solrField.toExternal(dateFrom) + " TO *])");
        filterTypesCountsQuery.append(" OR (npb\\:DateFrom:[" + solrField.toExternal(dateFrom)
                + " TO *] AND npb\\:DateTo:[" + solrField.toExternal(dateTo)
                + " TO *] AND npb\\:DateFrom:[* TO " + solrField.toExternal(dateFrom) + "])))");

        //visual
        filterTypesCountsQuery.append(" OR ((npv\\:DateFrom:[" + solrField.toExternal(dateFrom)
                + " TO *] AND npv\\:DateTo:[* TO " + solrField.toExternal(dateTo) + "])");
        filterTypesCountsQuery.append(" OR (npv\\:DateFrom:[* TO " + solrField.toExternal(dateFrom)
                + "] AND npv\\:DateTo:[* TO " + solrField.toExternal(dateTo) + "] AND npv\\:DateTo:["
                + solrField.toExternal(dateFrom) + " TO *])");
        filterTypesCountsQuery.append(" OR (npv\\:DateFrom:[" + solrField.toExternal(dateFrom)
                + " TO *] AND npv\\:DateTo:[" + solrField.toExternal(dateTo)
                + " TO *] AND npv\\:DateFrom:[* TO " + solrField.toExternal(dateFrom) + "]))");

        //audio
        filterTypesCountsQuery.append(" OR (npa\\:Date:[" + solrField.toExternal(dateFrom) + " TO "
                + solrField.toExternal(dateTo) + "])");

        //video
        filterTypesCountsQuery.append(" OR (npx\\:Date:[" + solrField.toExternal(dateFrom) + " TO "
                + solrField.toExternal(dateTo) + "])");
    } else {
        //no date queries, just perform query based on type restrictions            
        filterTypesCountsQuery.append(
                "(nyp\\:DocumentType:Program) OR (nyp\\:DocumentType:Printed Music)  OR (nyp\\:DocumentType:Part) OR (nyp\\:DocumentType:Business Record AND nyp\\:WebPublishable:true)");
        filterTypesCountsQuery.append(
                " OR (nyp\\:DocumentType:Visual) OR (nyp\\:DocumentType:Audio) OR (nyp\\:DocumentType:Video)");
    }

    params.add(CommonParams.FQ, filterTypesCountsQuery);

    //default facet for document type that will always return the counts regardless of filter queries applied
    params.add(FacetParams.FACET_FIELD, "{!ex=test}nyp:DocumentType_facet");
    //allow this facet to always display all values, even when there are 0 results for the type
    params.add("f.nyp:DocumentType_facet.facet.mincount", 0);

    if (doctype.equalsIgnoreCase("program")) {
        //set the document type restriction
        params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Program");

        if (generateFacets) {
            params.add(FacetParams.FACET_FIELD, "npp:ConductorName_facet");
            params.add(FacetParams.FACET_FIELD, "npp:SoloistsNames_facet");
            params.add(FacetParams.FACET_FIELD, "npp:WorksComposerNames_facet");
            params.add(FacetParams.FACET_FIELD, "npp:LocationName_facet");
            params.add(FacetParams.FACET_FIELD, "npp:VenueName_facet");
            params.add(FacetParams.FACET_FIELD, "npp:EventTypeName_facet");
            params.add(FacetParams.FACET_FIELD, "npp:Season_facet");
        }
    } else if (doctype.equalsIgnoreCase("printedMusic")) {
        //set the document type restriction
        params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Printed Music");

        if (generateFacets) {
            params.add(FacetParams.FACET_FIELD, "npm:ScoreMarkingArtist_facet");
            params.add(FacetParams.FACET_FIELD, "npm:ComposerName_facet");
        }

    } else if (doctype.equalsIgnoreCase("part")) {
        //set the document type restriction
        params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Part");

        if (generateFacets) {
            params.add(FacetParams.FACET_FIELD, "npm:ComposerName_facet");
            params.add(FacetParams.FACET_FIELD, "npm:UsedByArtistName_facet");
            params.add(FacetParams.FACET_FIELD, "npm:PartMarkingArtist_facet");
            params.add(FacetParams.FACET_FIELD, "npm:PartTypeDesc_facet");
        }

        // if sort parameter has been supplied (e.g. non-facet search) - apply additional part sorting
        if (sortColumn != null && sortOrder != null) {
            logger.debug("Addition additional sort parameter for PART type...");
            String prevParams = (String) params.get(CommonParams.SORT);
            String newParams = prevParams + ", npm:PartID ASC";
            params.add(CommonParams.SORT, newParams);
        }

    } else if (doctype.equalsIgnoreCase("businessRecord")) {
        //set the document type restriction
        params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Business Record");

        if (generateFacets) {
            params.add(FacetParams.FACET_FIELD, "npb:Names_facet");
            params.add(FacetParams.FACET_FIELD, "npb:Subject_facet");
            params.add(FacetParams.FACET_FIELD, "npb:RecordGroup_facet");
            params.add(FacetParams.FACET_FIELD, "npb:Series_facet");
            params.add(FacetParams.FACET_FIELD, "npb:SubSeries_facet");
        }

    } else if (doctype.equalsIgnoreCase("visual")) {
        //set the document type restriction
        params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Visual");

        if (generateFacets) {
            params.add(FacetParams.FACET_FIELD, "npv:Photographer_facet");
            params.add(FacetParams.FACET_FIELD, "npv:CopyrightHolder_facet");
            params.add(FacetParams.FACET_FIELD, "npv:ImageType_facet");
            params.add(FacetParams.FACET_FIELD, "npv:PlaceOfImage_facet");
            params.add(FacetParams.FACET_FIELD, "npv:Event_facet");
            params.add(FacetParams.FACET_FIELD, "npv:PersonalNames_facet");
            params.add(FacetParams.FACET_FIELD, "npv:LocationName_facet");
            params.add(FacetParams.FACET_FIELD, "npv:VenueName_facet");
        }

    } else if (doctype.equalsIgnoreCase("audio")) {
        //set the document type restriction
        params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Audio");

        //no facets being generated
    } else if (doctype.equalsIgnoreCase("video")) {
        //set the document type restriction
        params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Video");

        //no facets being generated
    } else {
        logger.error("Invalid document type: " + doctype);
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid document type: " + doctype);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Params: " + params);
    }

    //set the new request parameters, then call the default handler behavior
    req.setParams(SolrParams.toSolrParams(params));

    super.handleRequestBody(req, rsp);
}

From source file:edu.toronto.cs.cidb.solr.SolrScriptService.java

License:Open Source License

/**
 * Perform a search, falling back on the suggested spellchecked query if the original query fails to return any
 * results./*from  w  w  w. j ava2s  .  co m*/
 * 
 * @param params the Solr parameters to use, should contain at least a value for the "q" parameter; use
 *        {@link #getSolrQuery(String, int, int)} to get the proper parameter expected by this method
 * @return the list of matching documents, empty if there are no matching terms
 */
private SolrDocumentList search(MapSolrParams params) {
    try {
        QueryResponse response = this.server.query(params);
        SolrDocumentList results = response.getResults();
        if (results.size() == 0 && !response.getSpellCheckResponse().isCorrectlySpelled()) {
            String suggestedQuery = response.getSpellCheckResponse().getCollatedResult();
            // The spellcheck doesn't preserve the identifiers, manually
            // correct this
            suggestedQuery = suggestedQuery.replaceAll("term_category:hip", "term_category:HP");
            MapSolrParams newParams = new MapSolrParams(
                    getSolrQuery(suggestedQuery, params.get(CommonParams.SORT),
                            params.getInt(CommonParams.ROWS, -1), params.getInt(CommonParams.START, 0)));
            return this.server.query(newParams).getResults();
        } else {
            return results;
        }
    } catch (SolrServerException ex) {
        this.logger.error("Failed to search: {}", ex.getMessage(), ex);
    }
    return null;
}

From source file:edu.toronto.cs.cidb.solr.SolrScriptService.java

License:Open Source License

/**
 * Convert a Lucene query string into a map of Solr parameters. More specifically, places the input query under the
 * "q" parameter, and adds parameters for requesting a spellcheck result.
 *
 * @param query the lucene query string to use
 * @param sort the sort criteria ("fiel_name order')
 * @param rows the number of items to return, or -1 to use the default number of results
 * @param start the number of items to skip, i.e. the index of the first hit to return, 0-based
 * @return a map of Solr query parameter ready to be used for constructing a {@link MapSolrParams} object
 *//*from w w  w.j  ava2 s  .c  o  m*/
private Map<String, String> getSolrQuery(String query, String sort, int rows, int start) {
    Map<String, String> result = new HashMap<String, String>();
    result.put(CommonParams.START, start + "");
    if (rows > 0) {
        result.put(CommonParams.ROWS, rows + "");
    }
    result.put(CommonParams.Q, query);
    if (!StringUtils.isBlank(sort)) {
        result.put(CommonParams.SORT, sort);
    }
    result.put("spellcheck", Boolean.toString(true));
    result.put("spellcheck.collate", Boolean.toString(true));
    result.put("spellcheck.onlyMorePopular", Boolean.toString(true));
    return result;
}

From source file:edu.toronto.cs.phenotips.solr.AbstractSolrScriptService.java

License:Open Source License

/**
 * Convert a Lucene query string into a map of Solr parameters. More specifically, places the input query under the
 * "q" parameter, and adds parameters for requesting a spellcheck result.
 * /*from ww  w  .  j  a  va  2  s . co m*/
 * @param query the lucene query string to use
 * @param sort the sort criteria ("fiel_name order')
 * @param rows the number of items to return, or -1 to use the default number of results
 * @param start the number of items to skip, i.e. the index of the first hit to return, 0-based
 * @return a map of Solr query parameter ready to be used for constructing a {@link MapSolrParams} object
 */
private Map<String, String> getSolrQuery(String query, String sort, int rows, int start) {
    Map<String, String> result = new HashMap<String, String>();
    result.put(CommonParams.START, start + "");
    if (rows > 0) {
        result.put(CommonParams.ROWS, rows + "");
    }
    result.put(CommonParams.Q, query);
    if (StringUtils.isNotBlank(sort)) {
        result.put(CommonParams.SORT, sort);
    }
    result.put("spellcheck", Boolean.toString(true));
    result.put("spellcheck.collate", Boolean.toString(true));
    return result;
}

From source file:edu.toronto.cs.phenotips.solr.OmimScriptService.java

License:Open Source License

/**
 * Prepare the map of parameters that can be passed to a Solr query, in order to get a list of diseases matching the
 * selected positive and negative phenotypes.
 *
 * @param phenotypes the list of already selected phenotypes
 * @param nphenotypes phenotypes that are not observed in the patient
 * @return the computed Solr query parameters
 *///w  ww. ja  v  a2s .  co  m
private MapSolrParams prepareParams(Collection<String> phenotypes, Collection<String> nphenotypes) {
    Map<String, String> params = new HashMap<String, String>();
    String q = "symptom:" + StringUtils.join(phenotypes, " symptom:");
    if (nphenotypes.size() > 0) {
        q += "  not_symptom:" + StringUtils.join(nphenotypes, " not_symptom:");
    }
    params.put(CommonParams.Q, q.replaceAll("HP:", "HP\\\\:"));
    params.put(CommonParams.ROWS, "100");
    params.put(CommonParams.START, "0");
    params.put(CommonParams.DEBUG_QUERY, Boolean.toString(true));
    params.put(CommonParams.EXPLAIN_STRUCT, Boolean.toString(true));

    return new MapSolrParams(params);
}

From source file:jp.aegif.nemaki.cmis.aspect.query.solr.SolrQueryProcessor.java

License:Open Source License

@Override
public ObjectList query(CallContext callContext, String repositoryId, String statement,
        Boolean searchAllVersions, Boolean includeAllowableActions, IncludeRelationships includeRelationships,
        String renditionFilter, BigInteger maxItems, BigInteger skipCount, ExtensionsData extension) {

    SolrServer solrServer = solrUtil.getSolrServer();
    // replacing backslashed for TIMESTAMP only
    Pattern time_p = Pattern.compile("(TIMESTAMP\\s?'[\\-\\d]*T\\d{2})\\\\:(\\d{2})\\\\:([\\.\\d]*Z')",
            Pattern.CASE_INSENSITIVE);
    Matcher time_m = time_p.matcher(statement);
    statement = time_m.replaceAll("$1:$2:$3");

    // TODO walker is required?

    QueryUtilStrict util = new QueryUtilStrict(statement, new CmisTypeManager(repositoryId, typeManager), null);
    QueryObject queryObject = util.getQueryObject();
    // Get where caluse as Tree
    Tree whereTree = null;/* w  w w  .j a v  a2s  . c  o  m*/
    try {
        util.processStatement();
        Tree tree = util.parseStatement();
        whereTree = extractWhereTree(tree);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // Build solr statement of WHERE
    String whereQueryString = "";
    if (whereTree == null || whereTree.isNil()) {
        whereQueryString = "*:*";
    } else {
        try {
            SolrPredicateWalker solrPredicateWalker = new SolrPredicateWalker(repositoryId, queryObject,
                    solrUtil, contentService);
            Query whereQuery = solrPredicateWalker.walkPredicate(whereTree);
            whereQueryString = whereQuery.toString();
        } catch (Exception e) {
            e.printStackTrace();
            // TODO Output more detailed exception
            exceptionService.invalidArgument("Invalid CMIS SQL statement!");
        }
    }

    // Build solr query of FROM
    String fromQueryString = "";

    String repositoryQuery = "repository_id:" + repositoryId;

    fromQueryString += repositoryQuery + " AND ";
    TypeDefinition td = null;

    td = queryObject.getMainFromName();

    // includedInSupertypeQuery
    List<TypeDefinitionContainer> typeDescendants = typeManager.getTypesDescendants(repositoryId, td.getId(),
            BigInteger.valueOf(-1), false);
    Iterator<TypeDefinitionContainer> iterator = typeDescendants.iterator();
    List<String> tables = new ArrayList<String>();
    while (iterator.hasNext()) {
        TypeDefinition descendant = iterator.next().getTypeDefinition();
        if (td.getId() != descendant.getId()) {
            boolean isq = (descendant.isIncludedInSupertypeQuery() == null) ? false
                    : descendant.isIncludedInSupertypeQuery();
            if (!isq)
                continue;
        }
        String table = descendant.getQueryName();
        tables.add(table.replaceAll(":", "\\\\:"));
    }

    //      Term t = new Term(
    //            solrUtil.getPropertyNameInSolr(PropertyIds.OBJECT_TYPE_ID),
    //            StringUtils.join(tables, " "));
    //      fromQueryString += new TermQuery(t).toString();
    fromQueryString += "(" + solrUtil.getPropertyNameInSolr(repositoryId, PropertyIds.OBJECT_TYPE_ID) + ":"
            + StringUtils.join(tables,
                    " " + solrUtil.getPropertyNameInSolr(repositoryId, PropertyIds.OBJECT_TYPE_ID) + ":")
            + ")";

    // Execute query
    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQuery(whereQueryString);
    solrQuery.setFilterQueries(fromQueryString);

    logger.info(solrQuery.toString());
    logger.info("statement: " + statement);
    logger.info("skipCount: " + skipCount);
    logger.info("maxItems: " + maxItems);
    if (skipCount == null) {
        solrQuery.set(CommonParams.START, 0);
    } else {
        solrQuery.set(CommonParams.START, skipCount.intValue());
    }
    if (maxItems == null) {
        solrQuery.set(CommonParams.ROWS, 50);
    } else {
        solrQuery.set(CommonParams.ROWS, maxItems.intValue());
    }

    QueryResponse resp = null;
    try {
        resp = solrServer.query(solrQuery);
    } catch (SolrServerException e) {
        e.printStackTrace();
    }

    long numFound = 0;
    // Output search results to ObjectList
    if (resp != null && resp.getResults() != null && resp.getResults().getNumFound() != 0) {
        SolrDocumentList docs = resp.getResults();
        numFound = docs.getNumFound();

        List<Content> contents = new ArrayList<Content>();
        for (SolrDocument doc : docs) {
            String docId = (String) doc.getFieldValue("object_id");
            Content c = contentService.getContent(repositoryId, docId);

            // When for some reason the content is missed, pass through
            if (c == null) {
                logger.warn("[objectId=" + docId + "]It is missed in DB but still rests in Solr.");
            } else {
                contents.add(c);
            }

        }

        List<Lock> locks = threadLockService.readLocks(repositoryId, contents);
        try {
            threadLockService.bulkLock(locks);

            // Filter out by permissions
            List<Content> permitted = permissionService.getFiltered(callContext, repositoryId, contents);

            // Filter return value with SELECT clause
            Map<String, String> requestedWithAliasKey = queryObject.getRequestedPropertiesByAlias();
            String filter = null;
            if (!requestedWithAliasKey.keySet().contains("*")) {
                // Create filter(queryNames) from query aliases
                filter = StringUtils.join(requestedWithAliasKey.values(), ",");
            }

            // Build ObjectList
            String orderBy = orderBy(queryObject);
            ObjectList result = compileService.compileObjectDataListForSearchResult(callContext, repositoryId,
                    permitted, filter, includeAllowableActions, includeRelationships, renditionFilter, false,
                    maxItems, skipCount, false, orderBy, numFound);

            return result;

        } finally {
            threadLockService.bulkUnlock(locks);
        }
    } else {
        ObjectListImpl nullList = new ObjectListImpl();
        nullList.setHasMoreItems(false);
        nullList.setNumItems(BigInteger.ZERO);
        return nullList;
    }
}

From source file:lux.solr.XQueryComponent.java

License:Mozilla Public License

@Override
public void process(ResponseBuilder rb) throws IOException {
    if (rb.grouping()) {
        throw new SolrException(ErrorCode.BAD_REQUEST, "grouping not supported for XQuery");
    }//w  w w .j a v a2 s  .  c  o  m
    SolrQueryRequest req = rb.req;
    SolrParams params = req.getParams();
    if (!params.getBool(XQUERY_COMPONENT_NAME, true)) {
        // TODO -- what is this for? who would pass xquery=false??
        return;
    }
    int start = params.getInt(CommonParams.START, 1);
    int len = params.getInt(CommonParams.ROWS, -1);
    try {
        evaluateQuery(rb, start, len);
    } finally {
        solrIndexConfig.returnSerializer(serializer);
    }
}

From source file:net.yacy.cora.federate.solr.connector.MirrorSolrConnector.java

License:Open Source License

@Override
public QueryResponse getResponseByParams(ModifiableSolrParams query) throws IOException, SolrException {
    Integer count0 = query.getInt(CommonParams.ROWS);
    int count = count0 == null ? 10 : count0.intValue();
    Integer start0 = query.getInt(CommonParams.START);
    int start = start0 == null ? 0 : start0.intValue();
    if (this.solr0 == null && this.solr1 == null)
        return new QueryResponse();

    if (this.solr0 != null && this.solr1 == null) {
        QueryResponse list = this.solr0.getResponseByParams(query);
        return list;
    }/*  ww  w .  j a v  a2  s  .c  o  m*/
    if (this.solr1 != null && this.solr0 == null) {
        QueryResponse list = this.solr1.getResponseByParams(query);
        return list;
    }

    // combine both lists
    QueryResponse rsp = this.solr0.getResponseByParams(query);
    final SolrDocumentList l = rsp.getResults();
    if (l.size() >= count)
        return rsp;

    // at this point we need to know how many results are in solr0
    // compute this with a very bad hack; replace with better method later
    int size0 = 0;
    { //bad hack - TODO: replace
        query.set(CommonParams.START, 0);
        query.set(CommonParams.ROWS, Integer.MAX_VALUE);
        QueryResponse lHack = this.solr0.getResponseByParams(query);
        query.set(CommonParams.START, start);
        query.set(CommonParams.ROWS, count);
        size0 = lHack.getResults().size();
    }

    // now use the size of the first query to do a second query
    query.set(CommonParams.START, start + l.size() - size0);
    query.set(CommonParams.ROWS, count - l.size());
    QueryResponse rsp1 = this.solr1.getResponseByParams(query);
    query.set(CommonParams.START, start);
    query.set(CommonParams.ROWS, count);
    // TODO: combine both
    return rsp1;
}

From source file:net.yacy.cora.federate.solr.connector.MirrorSolrConnector.java

License:Open Source License

@Override
public SolrDocumentList getDocumentListByParams(ModifiableSolrParams query) throws IOException, SolrException {
    Integer count0 = query.getInt(CommonParams.ROWS);
    int count = count0 == null ? 10 : count0.intValue();
    Integer start0 = query.getInt(CommonParams.START);
    int start = start0 == null ? 0 : start0.intValue();
    if (this.solr0 == null && this.solr1 == null)
        return new SolrDocumentList();

    if (this.solr0 != null && this.solr1 == null) {
        SolrDocumentList list = this.solr0.getDocumentListByParams(query);
        return list;
    }//from  w ww .jav  a2s.  com
    if (this.solr1 != null && this.solr0 == null) {
        SolrDocumentList list = this.solr1.getDocumentListByParams(query);
        return list;
    }

    // combine both lists
    final SolrDocumentList l = this.solr0.getDocumentListByParams(query);
    if (l.size() >= count)
        return l;

    // at this point we need to know how many results are in solr0
    // compute this with a very bad hack; replace with better method later
    int size0 = 0;
    { //bad hack - TODO: replace
        query.set(CommonParams.START, 0);
        query.set(CommonParams.ROWS, Integer.MAX_VALUE);
        final SolrDocumentList lHack = this.solr0.getDocumentListByParams(query);
        query.set(CommonParams.START, start);
        query.set(CommonParams.ROWS, count);
        size0 = lHack.size();
    }

    // now use the size of the first query to do a second query
    query.set(CommonParams.START, start + l.size() - size0);
    query.set(CommonParams.ROWS, count - l.size());
    final SolrDocumentList l1 = this.solr1.getDocumentListByParams(query);
    query.set(CommonParams.START, start);
    query.set(CommonParams.ROWS, count);
    // TODO: combine both
    return l1;
}

From source file:net.yacy.http.servlets.SolrSelectServlet.java

License:Open Source License

@Override
public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    HttpServletRequest hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = (HttpServletResponse) response;
    SolrQueryRequest req = null;//w  w w. ja v  a 2  s . c o m

    final Method reqMethod = Method.getMethod(hrequest.getMethod());

    Writer out = null;
    try {
        // prepare request to solr
        MultiMapSolrParams mmsp = SolrRequestParsers.parseQueryString(hrequest.getQueryString());

        Switchboard sb = Switchboard.getSwitchboard();
        boolean authenticated = true;

        // count remote searches if this was part of a p2p search
        if (mmsp.getMap().containsKey("partitions")) {
            final int partitions = mmsp.getInt("partitions", 30);
            sb.searchQueriesGlobal += 1.0f / partitions; // increase query counter
        }

        // get the ranking profile id
        int profileNr = mmsp.getInt("profileNr", 0);

        // rename post fields according to result style
        String querystring = "";
        if (!mmsp.getMap().containsKey(CommonParams.Q) && mmsp.getMap().containsKey(CommonParams.QUERY)) {
            querystring = mmsp.get(CommonParams.QUERY, "");
            mmsp.getMap().remove(CommonParams.QUERY);
            QueryModifier modifier = new QueryModifier(0);
            querystring = modifier.parse(querystring);
            modifier.apply(mmsp);
            QueryGoal qg = new QueryGoal(querystring);
            StringBuilder solrQ = qg.collectionTextQuery();
            mmsp.getMap().put(CommonParams.Q, new String[] { solrQ.toString() }); // sru patch
        }
        String q = mmsp.get(CommonParams.Q, "");
        if (querystring.length() == 0)
            querystring = q;
        if (!mmsp.getMap().containsKey(CommonParams.START)) {
            int startRecord = mmsp.getFieldInt("startRecord", null, 0);
            mmsp.getMap().remove("startRecord");
            mmsp.getMap().put(CommonParams.START, new String[] { Integer.toString(startRecord) }); // sru patch
        }
        if (!mmsp.getMap().containsKey(CommonParams.ROWS)) {
            int maximumRecords = mmsp.getFieldInt("maximumRecords", null, 10);
            mmsp.getMap().remove("maximumRecords");
            mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer.toString(maximumRecords) }); // sru patch
        }
        mmsp.getMap().put(CommonParams.ROWS, new String[] { Integer
                .toString(Math.min(mmsp.getInt(CommonParams.ROWS, 10), (authenticated) ? 100000000 : 100)) });

        // set ranking according to profile number if ranking attributes are not given in the request
        Ranking ranking = sb.index.fulltext().getDefaultConfiguration().getRanking(profileNr);
        if (!mmsp.getMap().containsKey(CommonParams.SORT) && !mmsp.getMap().containsKey(DisMaxParams.BQ)
                && !mmsp.getMap().containsKey(DisMaxParams.BF) && !mmsp.getMap().containsKey("boost")) {
            if (!mmsp.getMap().containsKey("defType"))
                mmsp.getMap().put("defType", new String[] { "edismax" });
            String fq = ranking.getFilterQuery();
            String bq = ranking.getBoostQuery();
            String bf = ranking.getBoostFunction();
            if (fq.length() > 0)
                mmsp.getMap().put(CommonParams.FQ, new String[] { fq });
            if (bq.length() > 0)
                mmsp.getMap().put(DisMaxParams.BQ, new String[] { bq });
            if (bf.length() > 0)
                mmsp.getMap().put("boost", new String[] { bf }); // a boost function extension, see http://wiki.apache.org/solr/ExtendedDisMax#bf_.28Boost_Function.2C_additive.29
        }

        // get a response writer for the result
        String wt = mmsp.get(CommonParams.WT, "xml"); // maybe use /solr/select?q=*:*&start=0&rows=10&wt=exml
        QueryResponseWriter responseWriter = RESPONSE_WRITER.get(wt);
        if (responseWriter == null)
            throw new ServletException("no response writer");
        if (responseWriter instanceof OpensearchResponseWriter) {
            // set the title every time, it is possible that it has changed
            final String promoteSearchPageGreeting = (sb
                    .getConfigBool(SwitchboardConstants.GREETING_NETWORK_NAME, false))
                            ? sb.getConfig("network.unit.description", "")
                            : sb.getConfig(SwitchboardConstants.GREETING, "");
            ((OpensearchResponseWriter) responseWriter).setTitle(promoteSearchPageGreeting);
        }

        // if this is a call to YaCys special search formats, enhance the query with field assignments
        if ((responseWriter instanceof YJsonResponseWriter
                || responseWriter instanceof OpensearchResponseWriter)
                && "true".equals(mmsp.get("hl", "true"))) {
            // add options for snippet generation
            if (!mmsp.getMap().containsKey("hl.q"))
                mmsp.getMap().put("hl.q", new String[] { q });
            if (!mmsp.getMap().containsKey("hl.fl"))
                mmsp.getMap().put("hl.fl",
                        new String[] { CollectionSchema.description_txt + ","
                                + CollectionSchema.h4_txt.getSolrFieldName() + ","
                                + CollectionSchema.h3_txt.getSolrFieldName() + ","
                                + CollectionSchema.h2_txt.getSolrFieldName() + ","
                                + CollectionSchema.h1_txt.getSolrFieldName() + ","
                                + CollectionSchema.text_t.getSolrFieldName() });
            if (!mmsp.getMap().containsKey("hl.alternateField"))
                mmsp.getMap().put("hl.alternateField",
                        new String[] { CollectionSchema.description_txt.getSolrFieldName() });
            if (!mmsp.getMap().containsKey("hl.simple.pre"))
                mmsp.getMap().put("hl.simple.pre", new String[] { "<b>" });
            if (!mmsp.getMap().containsKey("hl.simple.post"))
                mmsp.getMap().put("hl.simple.post", new String[] { "</b>" });
            if (!mmsp.getMap().containsKey("hl.fragsize"))
                mmsp.getMap().put("hl.fragsize",
                        new String[] { Integer.toString(SearchEvent.SNIPPET_MAX_LENGTH) });
        }

        // get the embedded connector
        String requestURI = hrequest.getRequestURI();
        boolean defaultConnector = (requestURI.startsWith("/solr/" + WebgraphSchema.CORE_NAME)) ? false
                : requestURI.startsWith("/solr/" + CollectionSchema.CORE_NAME)
                        || mmsp.get("core", CollectionSchema.CORE_NAME).equals(CollectionSchema.CORE_NAME);
        mmsp.getMap().remove("core");
        SolrConnector connector = defaultConnector ? sb.index.fulltext().getDefaultEmbeddedConnector()
                : sb.index.fulltext().getEmbeddedConnector(WebgraphSchema.CORE_NAME);
        if (connector == null) {
            connector = defaultConnector ? sb.index.fulltext().getDefaultConnector()
                    : sb.index.fulltext().getConnectorForRead(WebgraphSchema.CORE_NAME);
        }
        if (connector == null)
            throw new ServletException("no core");

        // add default queryfield parameter according to local ranking config (or defaultfield)
        if (ranking != null) { // ranking normally never null
            final String qf = ranking.getQueryFields();
            if (qf.length() > 4) { // make sure qf has content (else use df)
                addParam(DisMaxParams.QF, qf, mmsp.getMap()); // add QF that we set to be best suited for our index
                // TODO: if every peer applies a decent QF itself, this can be reverted to getMap().put()
            } else {
                mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() });
            }
        } else {
            mmsp.getMap().put(CommonParams.DF, new String[] { CollectionSchema.text_t.getSolrFieldName() });
        }

        // do the solr request, generate facets if we use a special YaCy format
        final SolrQueryResponse rsp;
        if (connector instanceof EmbeddedSolrConnector) {
            req = ((EmbeddedSolrConnector) connector).request(mmsp);
            rsp = ((EmbeddedSolrConnector) connector).query(req);

            // prepare response
            hresponse.setHeader("Cache-Control", "no-cache, no-store");
            HttpCacheHeaderUtil.checkHttpCachingVeto(rsp, hresponse, reqMethod);

            // check error
            if (rsp.getException() != null) {
                AccessTracker.addToDump(querystring, "0", new Date());
                sendError(hresponse, rsp.getException());
                return;
            }

            NamedList<?> values = rsp.getValues();
            DocList r = ((ResultContext) values.get("response")).docs;
            int numFound = r.matches();
            AccessTracker.addToDump(querystring, Integer.toString(numFound), new Date());

            // write response header
            final String contentType = responseWriter.getContentType(req, rsp);
            if (null != contentType)
                response.setContentType(contentType);

            if (Method.HEAD == reqMethod) {
                return;
            }

            // write response body
            if (responseWriter instanceof BinaryResponseWriter) {
                ((BinaryResponseWriter) responseWriter).write(response.getOutputStream(), req, rsp);
            } else {
                out = new FastWriter(new OutputStreamWriter(response.getOutputStream(), UTF8.charset));
                responseWriter.write(out, req, rsp);
                out.flush();
            }
        } else {
            // write a 'faked' response using a call to the backend
            SolrDocumentList sdl = connector.getDocumentListByQuery(mmsp.getMap().get(CommonParams.Q)[0],
                    mmsp.getMap().get(CommonParams.SORT) == null ? null
                            : mmsp.getMap().get(CommonParams.SORT)[0],
                    Integer.parseInt(mmsp.getMap().get(CommonParams.START)[0]),
                    Integer.parseInt(mmsp.getMap().get(CommonParams.ROWS)[0]),
                    mmsp.getMap().get(CommonParams.FL));
            OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream());
            EnhancedXMLResponseWriter.write(osw, req, sdl);
            osw.close();
        }
    } catch (final Throwable ex) {
        sendError(hresponse, ex);
    } finally {
        if (req != null) {
            req.close();
        }
        SolrRequestInfo.clearRequestInfo();
        if (out != null)
            try {
                out.close();
            } catch (final IOException e1) {
            }
    }
}