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

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

Introduction

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

Prototype

public SolrQuery setRows(Integer rows) 

Source Link

Usage

From source file:com.seajas.search.attender.service.search.SolrSearchService.java

License:Open Source License

/**
 * {@inheritDoc}/*from   ww  w. j a va 2 s.c om*/
 */
@Override
public List<SearchResult> performSearch(final String query, final Date startDate, final Date endDate,
        final Map<String, String> parameters, final Integer maxResults, final String taxonomyLanguage) {
    List<SearchResult> results = new ArrayList<SearchResult>(maxResults);

    SolrQuery solrQuery = new SolrQuery();
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    // Combine the shards into a Solr-acceptable list

    String shardList = "";

    for (String shard : shards)
        shardList += (shardList.length() > 0 ? "," : "") + shard;

    solrQuery.setQuery(query);
    solrQuery.setRows(maxResults);
    solrQuery.setParam("shards", shardList);
    solrQuery.addFilterQuery("dcterms_created:[" + dateFormatter.format(startDate) + " TO "
            + dateFormatter.format(endDate) + "]");

    // Construct a field list for highlighting

    String[] fieldList = new String[(searchLanguages.size() * 2) + 2];

    fieldList[0] = "content";
    fieldList[1] = "title";

    for (int i = 2, j = 0; i < fieldList.length; i += 2, j++) {
        fieldList[i] = "content-" + searchLanguages.get(j);
        fieldList[i + 1] = "title-" + searchLanguages.get(j);
    }

    // Enable highlighting for the content (and leaving the title for now)

    solrQuery.setHighlight(true);
    solrQuery.setHighlightSnippets(2);
    solrQuery.setParam("hl.fl", fieldList);

    solrQuery.setParam("f.title.hl.fragsize", "0");
    solrQuery.setParam("f.content.hl.fragsize", "100");

    for (String language : searchLanguages) {
        solrQuery.setParam("f.title-" + language + ".hl.fragsize", "0");
        solrQuery.setParam("f.content-" + language + ".hl.fragsize", "100");
    }

    for (Entry<String, String> parameter : parameters.entrySet()) {
        if (parameter.getKey().equalsIgnoreCase("dcterms_coverage")
                || parameter.getKey().equalsIgnoreCase("dcterms_format"))
            solrQuery.addFilterQuery(parameter.getKey() + ":(" + parameter.getValue() + ")");
        else if (parameter.getKey().equalsIgnoreCase("dcterms_type"))
            solrQuery.addFilterQuery("-" + parameter.getKey() + ":(" + parameter.getValue() + ")");
        else
            solrQuery.addFilterQuery(parameter.getKey() + ":\"" + parameter.getValue() + "\"");
    }

    try {
        QueryResponse response = solrServer.query(solrQuery);
        Iterator<SolrDocument> iterator = response.getResults().iterator();

        for (int i = 0; i < maxResults && iterator.hasNext(); i++) {
            SolrDocument document = iterator.next();

            // Retrieve the (potentially) highlighted summary

            String id = (String) document.getFieldValue("id");
            String language = (String) document.getFieldValue("dcterms_language");
            String author = (String) document.getFieldValue("author");
            String sourceId = null;

            // Simply take the last source ID

            if (document.getFieldValues("dcterms_coverage") != null
                    && document.getFieldValues("dcterms_coverage").size() > 0)
                for (Object coverageId : document.getFieldValues("dcterms_coverage"))
                    sourceId = coverageId.toString();

            String contentField = StringUtils.hasText(language) ? "content-" + language : "content";
            String titleField = StringUtils.hasText(language) ? "title-" + language : "title";

            String summary = (String) document.getFieldValue(contentField);

            if (summary.length() > 300)
                summary = summary.substring(0, 300) + " &hellip;";

            if (response.getHighlighting().get(id) != null) {
                List<String> highlightSnippets = response.getHighlighting().get(id).get(contentField);

                if (highlightSnippets != null && highlightSnippets.size() > 0) {
                    String fragmentPrefixOne = highlightSnippets.get(0).length() > 99 ? " .. " : "";

                    summary = fragmentPrefixOne + highlightSnippets.get(0) + fragmentPrefixOne;

                    if (highlightSnippets.size() > 1) {
                        String fragmentSuffixTwo = highlightSnippets.get(1).length() > 99 ? " .. " : "";

                        summary += highlightSnippets.get(1) + fragmentSuffixTwo;
                    }
                }
            }

            results.add(new SearchResult((String) document.get("url"), (String) document.get(titleField),
                    author, sourceId, summary, (Date) document.get("dcterms_created"),
                    (String) document.get("dcterms_alternative")));
        }
    } catch (SolrServerException e) {
        logger.error("Could not retrieve Solr results for query '" + query + "'", e);
    }

    // Now collect and update the source IDs to their actual sources

    return adjustSourceIds(results, taxonomyLanguage);
}

From source file:com.smartitengineering.common.dao.search.solr.SolrFreeTextSearchDao.java

License:Open Source License

@Override
public SearchResult<T> detailedSearch(List<QueryParameter> parameters) {
    SolrQuery query = new SolrQuery();
    for (QueryParameter param : parameters) {
        switch (param.getParameterType()) {
        case PARAMETER_TYPE_PROPERTY:
            StringLikeQueryParameter queryParameter = QueryParameterCastHelper.STRING_PARAM_HELPER.cast(param);
            if (queryParameter.getPropertyName().equals("q")) {
                String queryString = queryParameter.getValue();
                query.setQuery(queryString);
            } else {
                query.add(queryParameter.getPropertyName(), queryParameter.getValue());
            }// w w w  . j  av a 2 s.  co m
            break;
        case PARAMETER_TYPE_ORDER_BY:
            SimpleNameValueQueryParameter<Order> parameter = QueryParameterCastHelper.SIMPLE_PARAM_HELPER
                    .cast(param);
            ORDER order = parameter.getValue().equals(Order.ASC) ? ORDER.asc : ORDER.desc;
            query.setSortField(parameter.getPropertyName(), order);
            break;
        case PARAMETER_TYPE_MAX_RESULT:
            ValueOnlyQueryParameter<Integer> valParam = QueryParameterCastHelper.VALUE_PARAM_HELPER.cast(param);
            Integer maxRows = valParam.getValue();
            query.setRows(maxRows);
            break;
        case PARAMETER_TYPE_FIRST_RESULT:
            ValueOnlyQueryParameter<Integer> firstParam = QueryParameterCastHelper.VALUE_PARAM_HELPER
                    .cast(param);
            Integer firstResult = firstParam.getValue();
            query.setStart(firstResult);
            break;
        default:
            throw new UnsupportedOperationException("Only property and order by query parameter is supported!");
        }
    }
    query.setIncludeScore(true);
    final SearchResult<MultivalueMap<String, Object>> mainResult = queryDao.getResult(query);
    final Collection<MultivalueMap<String, Object>> result = mainResult.getResult();
    final Collection<T> convertedResult = adapter
            .convertInversely(result.toArray(new MultivalueMap[result.size()]));
    Iterator<T> resultItr = convertedResult.iterator();
    while (resultItr.hasNext()) {
        T next = resultItr.next();
        if (next == null) {
            resultItr.remove();
        }
    }
    final SearchResult<T> actualResult = new SearchResult<T>(convertedResult, mainResult);
    return actualResult;
}

From source file:com.sp.Parser.Utils.java

License:Open Source License

public static SolrDocumentList getTop(SolrDocumentList docs, ArrayList<String> prices,
        ArrayList<String> filters) {
    SolrDocumentList SolrDocList = null;
    try {//w ww . ja va  2  s. co m

        SolrDocument PivotDoc = docs.get(0); //store pId book to put it in the index 0 of the final SolrDocList

        Collection<Object> Top20Product_ids = PivotDoc.getFieldValues("top20"); //store pId book to put it in the index 0 of the final SolrDocList

        PivotDoc.removeFields("top20"); // get current book top20 with products ids
        PivotDoc.removeFields("keywords");

        Collection<Object> BackupTop20Product_ids = Top20Product_ids;

        String QueryString = "product_id:(";
        ArrayList<String> TempQuery = new ArrayList<>();

        for (Object product_id : BackupTop20Product_ids) {
            QueryString += product_id.toString() + " ";
            TempQuery.add(product_id.toString());
        }
        QueryString += ")";

        String prices_fields = "";
        for (String string : prices) {
            prices_fields += string + " ";

        }

        SolrQuery Query = new SolrQuery(QueryString);
        Query.setRows(101);
        for (String filter : filters) {
            LOG.info("Top20 Filtering : " + filter);
            Query.addFilterQuery(filter);
        }
        Query.setParam("fl",
                "product_id book_id author_searchable author_id format_name description title author_firstname"
                        + " file_size publishing_date author_lastname author_rank publisher_id publisher_name"
                        + " permalink nb_pages isbn " + prices_fields);

        SolrServer solr = new HttpSolrServer(SearchHandler.solr_url);

        QueryResponse response = solr.query(Query);

        SolrDocList = response.getResults();

        if (!SolrDocList.isEmpty()) {

            SolrDocList = Utils.SortListByProductId(TempQuery, SolrDocList);

            if (!SolrDocList.isEmpty()) {
                SolrDocument temp = SolrDocList.get(0);

                SolrDocList.set(0, PivotDoc);
                SolrDocList.add(1, temp);
            }
        } else {
            SolrDocList.add(0, PivotDoc);
        }
    } catch (SolrServerException ex) {
        LOG.info("mmh : ", ex);
    }
    LOG.info("SolrDocList Size int getTop : " + SolrDocList.size());
    return SolrDocList;
}

From source file:com.ssavr.solr.service.impl.IceCreamLocalServiceImpl.java

License:Open Source License

/***************************************************************************
 ************************** GET ********************************************
 ***************************************************************************/

public IceCreamBean getIceCreamBean(IceCream iceCream) throws Exception {
    String uid = "iceCream_" + iceCream.getUuid();
    IceCreamBean bean = new IceCreamBean();
    bean.setUid(uid);/*ww w  .ja v a2  s . c om*/
    bean.setCompanyId(iceCream.getCompanyId());
    bean.setIceCreamId(iceCream.getIceCreamId());
    bean.setName(iceCream.getName());
    bean.setFlavor(iceCream.getFlavor());
    List<IceCreamDocuments> documents = iceCreamDocumentsLocalService
            .getIceCreamDocumentsByIceCreamId(iceCream.getIceCreamId());
    List<String> documentsContent = new ArrayList<String>();

    if (!documents.isEmpty()) {
        List<String> documentIds = new ArrayList<String>();
        for (IceCreamDocuments document : documents) {
            documentIds.add(String.valueOf(document.getDocumentId()));
        }
        String documentsStr = StringUtil.merge(documentIds, StringPool.SPACE);

        SolrQuery query = new SolrQuery();
        query.setQuery(Field.ENTRY_CLASS_PK + ":(" + documentsStr + ")");
        query.addFilterQuery(
                Field.ENTRY_CLASS_NAME + ":(com.liferay.portlet.documentlibrary.model.DLFileEntry)");
        query.setStart(0);
        query.setRows(10000000);

        String activeServerUrl = SolrUtil.getActiveSolrServer();
        CommonsHttpSolrServer server = new CommonsHttpSolrServer(activeServerUrl);

        QueryResponse qr = server.query(query);
        SolrDocumentList docs = qr.getResults();
        if (_log.isDebugEnabled()) {
            _log.debug("Found " + docs.size() + " Document(-s)");
        }

        for (int i = 0; i < docs.size(); ++i) {
            String docContent = (String) docs.get(i).getFieldValue("content");
            documentsContent.add(docContent);
        }
    }

    bean.setIceCreamRecipeContent(documentsContent);

    if (_log.isDebugEnabled()) {
        _log.debug(bean.toString());
    }

    return bean;
}

From source file:com.ssavr.solr.service.impl.IceCreamLocalServiceImpl.java

License:Open Source License

public List<IceCream> searchIceCreams(String name, String flavor, String text, int start, int rows,
        String orderByCol, String orderByType) throws PortalException, SystemException {
    if (_log.isDebugEnabled()) {
        _log.debug("searchIceCreams()");
    }/* w ww .j a v  a  2  s . c  o m*/
    List<IceCream> iceCreams = new ArrayList<IceCream>();
    String activeServerURL = SolrUtil.getActiveSolrServer();
    try {
        CommonsHttpSolrServer server = new CommonsHttpSolrServer(activeServerURL);
        SolrQuery query = new SolrQuery();

        query.setQuery(getQuery());
        List<String> filterQueries = getFilterQueries(name, flavor, text);
        for (String fq : filterQueries) {
            query.setFilterQueries(fq);
        }

        query.setStart(start);
        query.setRows(rows);

        QueryResponse response = server.query(query);

        List<SolrResponse> searchResults = response.getBeans(SolrResponse.class);
        for (SolrResponse result : searchResults) {
            String iceCreamId = result.getEntryClassPK();
            IceCream iceCream = iceCreamPersistence.findByPrimaryKey(Long.parseLong(iceCreamId));
            iceCreams.add(iceCream);
        }
    } catch (MalformedURLException e) {
        if (_log.isDebugEnabled()) {
            _log.debug(e.getMessage());
        }
        throw new SystemException(e);
    } catch (SolrServerException e) {
        if (_log.isDebugEnabled()) {
            _log.debug(e.getMessage());
        }
        throw new SystemException(e);
    }

    return iceCreams;
}

From source file:com.ssavr.solr.service.impl.IceCreamLocalServiceImpl.java

License:Open Source License

public List<IceCream> searchIceCreamsWithEDisMax(String name, String flavor, String text, String value,
        int start, int rows, String orderByCol, String orderByType) throws PortalException, SystemException {
    if (_log.isDebugEnabled()) {
        _log.debug("searchIceCreams()");
    }/*from   ww  w  . j a  v  a  2 s. c  o  m*/
    List<IceCream> iceCreams = new ArrayList<IceCream>();
    String activeServerURL = SolrUtil.getActiveSolrServer();
    try {
        CommonsHttpSolrServer server = new CommonsHttpSolrServer(activeServerURL);
        SolrQuery query = new SolrQuery();

        query.setQuery(getQuery(value));
        query.set("qf", "iceCreamName iceCreamFlavor");
        /*
         * List<String> filterQueries = getFilterQueries(name, flavor,
         * text); for (String fq : filterQueries) {
         * query.setFilterQueries(fq); }
         */

        query.setStart(start);
        query.setRows(rows);

        boolean enableFacet = true;
        query.setFacet(enableFacet);
        query.addFacetField("iceCreamName", "iceCreamFlavor");

        QueryResponse response = server.query(query);

        List<SolrResponse> searchResults = response.getBeans(SolrResponse.class);

        for (SolrResponse result : searchResults) {
            String iceCreamId = result.getEntryClassPK();
            IceCream iceCream = iceCreamPersistence.findByPrimaryKey(Long.parseLong(iceCreamId));
            iceCreams.add(iceCream);
        }
    } catch (MalformedURLException e) {
        if (_log.isDebugEnabled()) {
            _log.debug(e.getMessage());
        }
        throw new SystemException(e);
    } catch (SolrServerException e) {
        if (_log.isDebugEnabled()) {
            _log.debug(e.getMessage());
        }
        throw new SystemException(e);
    }

    return iceCreams;
}

From source file:com.tamingtext.solr.SolrJTest.java

License:Apache License

public void doTest() throws IOException, SolrServerException {
    log.info("--------------------test()---------------------");
    String description = "In a stunning defeat for rabbits "
            + "everywhere, Fred Q. Tortoise capitalized on John "
            + "Hare's brazen laziness to win the annual Tortoise-Hare 5K Road Race.  "
            + "The lazy Mr. Hare, in hopes of saving face, immediately "
            + "acccused Mr. Tortoise of doping, in what has become an "
            + "all too familiar scene in sporting events today.  "
            + "Fans everywhere were appalled by the revelations, with "
            + "allegiances falling roughly along species lines.";
    //<start id="solrj"/>
    SolrServer solr = new CommonsHttpSolrServer(new URL("http://localhost:" + port + "/solr"));//<co id="co.solrj.server"/>
    SolrInputDocument doc = new SolrInputDocument();
    doc.addField("id", "http://tortoisehare5k.tamingtext.com");//<co id="co.solrj.unique"/>
    doc.addField("mimeType", "text/plain");
    doc.addField("title", "Tortoise beats Hare!  Hare wants rematch.", 5);//<co id="co.solrj.title"/>
    Date now = new Date();
    doc.addField("date", DateUtil.getThreadLocalDateFormat().format(now));//<co id="co.solrj.date"/>
    doc.addField("description", description);
    doc.addField("categories_t", "Fairy Tale, Sports");//<co id="co.solrj.dynamic.field"/>
    solr.add(doc);//<co id="co.solrj.add"/>
    solr.commit();//<co id="co.solrj.commit"/>
    /*/*  w  w  w  . j  ava 2 s . c o  m*/
    <calloutlist>
    <callout arearefs="co.solrj.server"><para>Create a HTTP-based Solr Server connection.</para></callout>
      <callout arearefs="co.solrj.unique"><para>The schema used for this instance of Solr requires a unique field named "id"</para></callout>
      <callout arearefs="co.solrj.title"><para>Add a Title field to our document and boost it to be 5 times as important as the other fields</para></callout>
      <callout arearefs="co.solrj.date"><para>Dates must be formatted in a specific way for Solr.</para></callout>
      <callout arearefs="co.solrj.dynamic.field"><para>A dynamic field allows for the addition of unknown fields to Solr.  The "_t" tells Solr this should be treated as a text field.</para></callout>
      <callout arearefs="co.solrj.add"><para>Send the newly created document to Solr.  Solr takes care of creating a correctly formatted XML message and sending it to Solr using Apache Jakarta Commons HTTPClient.</para></callout>
      <callout arearefs="co.solrj.commit"><para>After you have added all your documents and wish to make them available for searching, send a commit message to Solr</para></callout>
    </calloutlist>
    */
    //<end id="solrj"/>
    //Add some more docs
    doc = new SolrInputDocument();//<co id="co.solrj.doc"/>
    doc.addField("id", "http://redfox.tamingtext.com");//<co id="co.solrj.unique"/>
    doc.addField("mimeType", "text/plain");//<co id="co.solrj.mime"/>
    doc.addField("title", "Red Fox mocks Lazy Brown Dogs!", 5);//<co id="co.solrj.title"/>
    now = new Date();
    doc.addField("date", DateUtil.getThreadLocalDateFormat().format(now));
    doc.addField("description",
            "Once again, the Red Fox outshined the"
                    + " lazy Brown Dogs to win the vaunted Tally Ho Cup, in what"
                    + " has become an annual ritual.  The lazy brown "
                    + "dogs just don't seem to have the drive that Red Fox does."
                    + "  The lazy Brown Dogs vow to avenge their latest defeat, "
                    + "but the group's supporters claim to have heard it all before.");
    doc.addField("categories_t", "Fairy Tale, Sports");
    solr.add(doc);//<co id="co.solrj.add"/>
    doc = new SolrInputDocument();//<co id="co.solrj.doc"/>
    doc.addField("id", "http://maryLambs.tamingtext.com");//<co id="co.solrj.unique"/>
    doc.addField("mimeType", "text/plain");//<co id="co.solrj.mime"/>

    now = new Date(10000);
    doc.addField("date", DateUtil.getThreadLocalDateFormat().format(now));
    doc.addField("title", "Mary's Little Lamb Stolen!.", 5);//<co id="co.solrj.title"/>
    doc.addField("description",
            "In an affront to all that is good and" + " decent in this world, criminals made off with Mary's "
                    + "little Lamb in a late night raid on Mary's farm."
                    + "  Early suspects include a Ms. Bo Peep who weeks earlier "
                    + "reported losing several sheep.  Police suspect Ms. Peep "
                    + "was going to use the lamb to bring her flock's numbers back up."
                    + "  The spokesman for Ms. Peep declined comment at this "
                    + "time.  Mary, however, was outraged and promises revenge "
                    + "on the insensitive clod who stole her precious animals.");
    doc.addField("categories_t", "Fairy Tale, crime, sheep");
    solr.add(doc);
    //add in some random other docs
    Collection<SolrInputDocument> docs = new HashSet<SolrInputDocument>();
    for (int i = 0; i < 100; i++) {
        doc = new SolrInputDocument();
        doc.addField("id", "http://www.tamingtext.com/" + i + ".html");
        doc.addField("mimeType", "text/html");
        doc.addField("title", "This is title " + i);
        now = new Date(150 * i + i + 20);//create some dates
        doc.addField("date", DateUtil.getThreadLocalDateFormat().format(now));
        doc.addField("description",
                "This is description number: " + i + " of something that is very important.");
        docs.add(doc);
    }

    solr.add(docs);
    solr.commit();
    solr.optimize();
    //<start id="solrj-search-1"/>
    SolrQuery queryParams = new SolrQuery();//<co id="solrj-search.co.query"/>
    queryParams.setFields("description", "title");//<co id="solrj-search.co.fields"/>
    queryParams.setQuery("description:win OR description:all");//<co id="solrj-search.co.terms"/>
    queryParams.setRows(10);
    QueryResponse response = solr.query(queryParams);//<co id="solrj-search.co.process"/>
    assertTrue("response is null and it shouldn't be", response != null);
    SolrDocumentList documentList = response.getResults();
    System.out.println("Docs: " + documentList);
    assertTrue("response.getResults() Size: " + documentList.size() + " is not: " + 3,
            documentList.size() == 3);
    /*
    <calloutlist>
    <callout arearefs="solrj-search.co.query"><para>A <classname>SolrQuery</classname> is a easy-to-use container for creating the most common types of queries.</para></callout>
    <callout arearefs="solrj-search.co.fields"><para>Set the names of the Fields to be returned in the documents.</para></callout>
    <callout arearefs="solrj-search.co.terms"><para>Set the terms to search.  The "OR" is a boolean operator which allows one or the other or both to be present in the query.</para></callout>
    <callout arearefs="solrj-search.co.process"><para>Submit the query to Solr and get back a <classname>QueryResponse</classname> which contains the results of the search.</para></callout>
            
    </calloutlist>
    */
    //<end id="solrj-search-1"/>

    //<start id="solrj-search-dismax"/>
    queryParams.setQuery("lazy");
    queryParams.setParam("defType", "dismax");//<co id="solrj-search.co.dismax"/>
    queryParams.set("qf", "title^3 description^10");//<co id="sorlj-search.co.qf"/>
    System.out.println("Query: " + queryParams);
    response = solr.query(queryParams);
    assertTrue("response is null and it shouldn't be", response != null);
    documentList = response.getResults();
    assertTrue("documentList Size: " + documentList.size() + " is not: " + 2, documentList.size() == 2);
    /*
    <calloutlist>
        <callout arearefs="solrj-search.co.dismax"><para>Tell Solr to use the <classname>DisMax</classname> Query Parser (named dismax in solrconfig.xml). </para></callout>
        <callout arearefs="sorlj-search.co.qf"><para>The DisMax parser will search across the fields given by the "qf" parameter and boosts the terms accordingly.</para></callout>
            
    </calloutlist>
    */
    //<end id="solrj-search-dismax"/>

    //<start id="solrj-search-facets"/>
    queryParams = new SolrQuery();
    queryParams.setQuery("description:number");
    queryParams.setRows(10);
    queryParams.setFacet(true);//<co id="solrj-search-facets-facetOn"/>
    queryParams.set("facet.field", "date");//<co id="solrj-search-facets-date"/>
    response = solr.query(queryParams);
    assertTrue("response is null and it shouldn't be", response != null);
    System.out.println("Query: " + queryParams);
    documentList = response.getResults();
    assertTrue("documentList Size: " + documentList.size() + " is not: " + 10, documentList.size() == 10);
    System.out.println("Facet Response: " + response.getResponse());//<co id="solrj-search-facets-print"/>
    /*
    <calloutlist>
    <callout arearefs="solrj-search-facets-facetOn"><para>Turn on faceting for this query</para></callout>
    <callout arearefs="solrj-search-facets-date"><para>Specify the Field to facet on</para></callout>
    <callout arearefs="solrj-search-facets-print"><para>Print out the facet information</para></callout>
            
    </calloutlist>
    */
    //<end id="solrj-search-facets"/>
    //<start id="solrj-search-more-like-this"/>
    queryParams = new SolrQuery();
    queryParams.setQueryType("/mlt");//<co id="solrj-search.co.mlt"/>
    queryParams.setQuery("description:number");
    queryParams.set("mlt.match.offset", "0");//<co id="solrj-search.co.mlt.off"/>
    queryParams.setRows(1);
    queryParams.set("mlt.fl", "description, title");//<co id="solrj-search.co.mlt.fl"/>
    response = solr.query(queryParams);
    assertTrue("response is null and it shouldn't be", response != null);
    SolrDocumentList results = (SolrDocumentList) response.getResponse().get("match");
    assertTrue("results Size: " + results.size() + " is not: " + 1, results.size() == 1);
    /*
    <calloutlist>
    <callout arearefs="solrj-search.co.mlt"><para>Create a "MoreLikeThis" search to find similar documents to the specified document.</para></callout>
    <callout arearefs="solrj-search.co.mlt.fl"><para>Specify the field to use to generate the "MoreLikeThis" query.</para></callout>
    <callout arearefs="solrj-search.co.mlt.off"><para>Specify which document in the original results to use as the "similar" document. </para></callout>
    </calloutlist>
    */
    //<end id="solrj-search-more-like-this"/>

    log.info("--------------------end test()---------------------");
}

From source file:com.temenos.interaction.commands.solr.SolrSearchCommand.java

License:Open Source License

/**
 * By default SolrQuery only returns 10 rows. This is true even if more
  * rows are available. This method will check if user has provided its preference
  * using $top, otherwise use Solr Default
 * @param query/*from  w w w . ja  v a 2s. co m*/
 * @param queryParams
 */
private void addNumOfRows(SolrQuery query, MultivaluedMap<String, String> queryParams) {
    int top = 0;
    try {
        String topStr = queryParams.getFirst("$top");
        top = topStr == null || topStr.isEmpty() ? 0 : Integer.parseInt(topStr);
    } catch (NumberFormatException nfe) {
        // Do nothing and ignore as we have default value to use

    }
    if (top > 0) {
        query.setRows(top);
    } else {
        query.setRows(MAX_ENTITIES_RETURNED);
    }
}

From source file:com.thinkaurelius.titan.diskstorage.solr.Solr5Index.java

License:Apache License

@Override
public List<String> query(IndexQuery query, KeyInformation.IndexRetriever informations, BaseTransaction tx)
        throws BackendException {
    List<String> result;
    String collection = query.getStore();
    String keyIdField = getKeyFieldId(collection);
    SolrQuery solrQuery = new SolrQuery("*:*");
    String queryFilter = buildQueryFilter(query.getCondition(), informations.get(collection));
    solrQuery.addFilterQuery(queryFilter);
    if (!query.getOrder().isEmpty()) {
        List<IndexQuery.OrderEntry> orders = query.getOrder();
        for (IndexQuery.OrderEntry order1 : orders) {
            String item = order1.getKey();
            SolrQuery.ORDER order = order1.getOrder() == Order.ASC ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc;
            solrQuery.addSort(new SolrQuery.SortClause(item, order));
        }//from   w ww  .ja  v a  2 s.co m
    }
    solrQuery.setStart(0);
    if (query.hasLimit()) {
        solrQuery.setRows(query.getLimit());
    } else {
        solrQuery.setRows(maxResults);
    }
    try {
        QueryResponse response = solrClient.query(collection, solrQuery);

        if (logger.isDebugEnabled())
            logger.debug("Executed query [{}] in {} ms", query.getCondition(), response.getElapsedTime());

        int totalHits = response.getResults().size();

        if (!query.hasLimit() && totalHits >= maxResults)
            logger.warn("Query result set truncated to first [{}] elements for query: {}", maxResults, query);

        result = new ArrayList<String>(totalHits);
        for (SolrDocument hit : response.getResults()) {
            result.add(hit.getFieldValue(keyIdField).toString());
        }
    } catch (IOException e) {
        logger.error("Query did not complete : ", e);
        throw new PermanentBackendException(e);
    } catch (SolrServerException e) {
        logger.error("Unable to query Solr index.", e);
        throw new PermanentBackendException(e);
    }
    return result;
}

From source file:com.thinkbiganalytics.search.SolrSearchService.java

License:Apache License

private QueryResponse executeSearch(String query, int size, int start) {
    final String COLLECTION_LIST = "kylo-data," + SearchIndex.DATASOURCES; //Solr admin to configure beforehand
    final String ALL_FIELDS = "*";
    final String BOLD_HIGHLIGHT_START = "<font style='font-weight:bold'>";
    final String BOLD_HIGHLIGHT_END = "</font>";

    SolrQuery solrQuery = new SolrQuery();
    solrQuery.set("q", query);
    solrQuery.setRows(size);
    solrQuery.setStart(start);//from ww w.j a  v a2s .  com
    solrQuery.setParam("collection", COLLECTION_LIST);
    solrQuery.setHighlight(true);
    solrQuery.set("hl.fl", ALL_FIELDS);
    solrQuery.setHighlightSimplePre(BOLD_HIGHLIGHT_START);
    solrQuery.setHighlightSimplePost(BOLD_HIGHLIGHT_END);
    solrQuery.setHighlightRequireFieldMatch(false);

    try {
        return client.query("kylo-data", solrQuery);
    } catch (SolrServerException | IOException e) {
        throw new RuntimeException("Error encountered during search.");
    }
}