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

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

Introduction

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

Prototype

public SolrQuery setFacet(boolean b) 

Source Link

Document

enable/disable faceting.

Usage

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 ww  .  j a v a  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.villemos.ispace.solr.SolrProducer.java

License:Open Source License

/**
 * Retrieves a number of entries from the repository, based on the configured
 * query. //  w  w w.j a  va2  s  .c o m
 * 
 * @param exchange
 * @throws SolrServerException 
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 * @throws RemoteException 
 */
protected void retrieve(Exchange exchange) throws SolrServerException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException, RemoteException {

    /** Configure the request. 
     * 
     * One keywords are supported 
     *   FROMLAST. Will be replaced with the timestamp of the last retrieval (initial is 0). 
     */
    String queryString = endpoint.getQuery();
    queryString = queryString.replaceAll("FROMLAST", Long.toString(lastRetrievalTime));
    SolrQuery query = new SolrQuery(queryString);
    configureQuery(query);

    if (queryString.equals("*:*")) {
        query.setQueryType("basic");
    }

    /** If we are asked for facets, then add the facets. */
    if (endpoint.getFacets()) {
        query.setFacet(true);
        query.addFacetField(endpoint.getFacetField());
    }

    /** Search and set result set. Notice that this will return the results upto the 
     * configured number of rows. More results may thus be in the repository. */

    /** Data is either returned as a batch contained in the body of the exchange, or as
     * a stream send to the callback object in the body. The exchange header field 
     * 'solr.stream' is used to indicate which delivery mode is used. */
    if (endpoint.isStream() == false) {

        QueryResponse response = endpoint.getServer().query(query);
        if (response.getStatus() != 0) {
            log.error(
                    "Failed to execute retrieval request. Failed with status '" + response.getStatus() + "'.");
        }

        exchange.getOut().getHeaders().put(SolrOptions.count, (int) response.getResults().getNumFound());
        if (endpoint.isCount() == false) {
            ResultSet results;
            try {
                results = Utilities.getResultSet(response, query.getRows(), queryString);
                exchange.getOut().setBody(results);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    } else {
        /***/
        Statistics statistics = new Statistics();

        int maxNumberOfHits = query.getRows();

        /** When streaming, we retrieve in chunks. */
        int streamBatchSize = 100 > maxNumberOfHits ? maxNumberOfHits : 100;
        query.setRows(streamBatchSize);
        Integer index = query.getStart() == null ? 0 : query.getStart();

        QueryResponse response = endpoint.getServer().query(query);
        if (response.getStatus() != 0) {
            log.error(
                    "Failed to execute retrieval request. Failed with status '" + response.getStatus() + "'.");
        }

        int numberOfHits = (int) response.getResults().getNumFound();
        if (numberOfHits > maxNumberOfHits) {
            numberOfHits = maxNumberOfHits;
        }

        boolean deliverOnes = false;

        do {
            ResultSet set;
            try {
                set = Utilities.getResultSet(response, maxNumberOfHits, queryString);

                /** Update the statistics. */
                statistics.maxScore = statistics.maxScore > set.statistics.maxScore ? statistics.maxScore
                        : set.statistics.maxScore;
                statistics.totalFound = set.statistics.totalFound;
                statistics.totalRequested = set.statistics.totalRequested;
                statistics.queryTime += set.statistics.queryTime;
                statistics.totalReturned += set.statistics.totalReturned;

                /** Deliver latest statistics. */
                Exchange newExchange = new DefaultExchange(endpoint.getCamelContext());
                newExchange.getIn().setBody(statistics);
                endpoint.getCamelContext().createProducerTemplate().send("direct:results", newExchange);

                /** Deliver the data that is the same for each sequential query, i.e. facets and suggestions. */
                if (deliverOnes == false) {
                    for (Facet facet : set.facets) {
                        newExchange = new DefaultExchange(endpoint.getCamelContext());
                        newExchange.getIn().setBody(facet);
                        endpoint.getCamelContext().createProducerTemplate().send("direct:results", newExchange);
                    }
                    for (Suggestion suggestion : set.suggestions) {
                        newExchange = new DefaultExchange(endpoint.getCamelContext());
                        newExchange.getIn().setBody(suggestion);
                        endpoint.getCamelContext().createProducerTemplate().send("direct:results", newExchange);
                    }

                    deliverOnes = true;
                }

                /** Deliver the found information objects. */
                for (Object document : set.informationobjects) {
                    newExchange = new DefaultExchange(endpoint.getCamelContext());
                    newExchange.getIn().setBody(document);
                    endpoint.getCamelContext().createProducerTemplate().send("direct:results", newExchange);
                }
                index += streamBatchSize;

                if (numberOfHits > index && statistics.totalReturned < statistics.totalFound) {
                    query.setStart(index);

                    long numberMissing = numberOfHits - statistics.totalReturned;
                    if (numberMissing < streamBatchSize) {
                        query.setRows((int) numberMissing);
                    }

                    response = endpoint.getServer().query(query);
                } else {
                    break;
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

        } while (true);
    }
}

From source file:com.villemos.ispace.solr.SolrProducer.java

License:Open Source License

private void configureQuery(SolrQuery query)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    /** Set the default values. May be overridden by later settings. */
    query.setRows(endpoint.getRows());/* w  ww.j ava2  s .  c o m*/
    query.setSortField(endpoint.getSortField(), endpoint.getSortOrder());

    /** We per default always set highlighting. */
    query.setHighlight(true).setHighlightSnippets(1);
    query.setParam("hl.fl", "withRawText");

    /** Configure facets. */
    query.setFacet(endpoint.getFacets());
    if (endpoint.getFacets() == true) {
        query.setQuery(endpoint.getQuery());
        query.setFacetSort(endpoint.getFacetsort());
        query.setFacetLimit(endpoint.getFacetlimit());
        query.setFacetPrefix(endpoint.getFacetprefix());
        query.setFacetMinCount(endpoint.getMinCount());
        query.setFacetMissing(endpoint.isFacetMissing());
    }

    query.addFacetField(endpoint.getFacetField());
}

From source file:com.yaotrue.learn.solr.SolrjTest.java

License:Apache License

@Test
public void testFacet() throws SolrServerException, IOException {
    SolrQuery solrQuery = new SolrQuery("*:*");
    solrQuery.setFacet(true);
    solrQuery.addFacetQuery("sale_price:[0 TO 200]");
    solrQuery.addFacetQuery("sale_price:[201 TO 300]");
    solrQuery.addFacetQuery("sale_price:[300 TO 400]");
    solrQuery.setFacetSort("count");

    solrQuery.addFacetField("code");
    solrQuery.setFacetMinCount(0);/*w  ww . java 2s  .  com*/
    solrQuery.setFacetLimit(-1);

    QueryResponse response = solrClient.query(solrQuery);
    if (response != null) {
        List<FacetField> facetFields = response.getFacetFields();
        for (FacetField facetField : facetFields) {
            List<Count> countList = null;
            if (facetField != null) {
                countList = facetField.getValues();
                if (countList != null) {
                    for (Count count : countList) {
                        System.out.println(count.getName() + count.getCount());
                    }
                }
            }
        }

        Map<String, Integer> map = response.getFacetQuery();
        for (String key : map.keySet()) {
            System.out.println(key + ":" + map.get(key));
        }
    }
}

From source file:cz.incad.vdk.client.tools.Search.java

License:Open Source License

public String getAsXML() throws JSONException {

    try {//from  w w  w. ja  v a  2  s . c o m

        String q = req.getParameter("q");
        SolrQuery query = new SolrQuery();
        if (q == null || q.equals("")) {
            q = "*:*";
            query.setSort("_version_", SolrQuery.ORDER.desc);
        }
        query.setQuery(q);
        query.set("q.op", "AND");
        query.setFacet(true);
        query.setStart(getStart());
        query.setRows(getRows());

        if (LoggedController.isLogged(req)) {
            query.addFacetField(opts.getStrings("user_facets"));
        }
        query.addFacetField(opts.getStrings("facets"));

        query.setFacetMinCount(1);

        JSONObject others = opts.getJSONObject("otherParams");
        Iterator keys = others.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            Object val = others.get(key);
            if (val instanceof Integer) {
                query.set(key, (Integer) val);
            } else if (val instanceof String) {
                query.set(key, (String) val);
            } else if (val instanceof Boolean) {
                query.set(key, (Boolean) val);
            }

        }
        addFilters(query);

        return IndexerQuery.xml(query);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:cz.zcu.kiv.eegdatabase.logic.search.FulltextSearchService.java

License:Apache License

/**
 * Given the input query, finds out the total count of full text results for each full text result type.
 * @param solrQuery The search query.//from  w w  w .java  2  s .  co  m
 * @return Map containg category-count pairs.
 */
public Map<String, Long> getCategoryFacets(String solrQuery) {
    SolrQuery query = new SolrQuery(solrQuery);
    query.setParam("fl", IndexField.UUID.getValue());
    query.setHighlight(false);
    query.setFacet(true);
    query.addFacetField(IndexField.CLASS.getValue());

    Map<String, Long> results = new HashMap<String, Long>();
    QueryResponse response = null;
    try {
        response = solrServer.query(query);
    } catch (SolrServerException e) {
        log.error(e);
    }
    long totalCount = 0;
    List<FacetField> facets = response.getFacetFields();
    for (FacetField field : facets) {
        log.info("count: " + field.getValueCount());
        List<FacetField.Count> facetEntries = field.getValues();
        for (FacetField.Count count : facetEntries) {
            long countValue = count.getCount();
            results.put(count.getName(), countValue);
            log.info(count.getName() + ", " + countValue);
            totalCount += countValue;
        }
    }

    // add a "facet" for all results
    results.put(ResultCategory.ALL.getValue(), totalCount);

    return results;
}

From source file:datacite.oai.provider.service.MDSSearchServiceSolrImpl.java

License:Open Source License

@Override
public Pair<List<SetRecordBean>, Integer> getSets() throws ServiceException {
    SolrQuery query = new SolrQuery();
    query.setQuery("*:*");
    query.setRows(0);/*from  w w w  . ja v  a 2  s.  c o  m*/
    query.setFacet(true);
    query.setFacetLimit(-1);
    query.addFacetField("allocator_facet", "datacentre_facet");

    try {
        QueryResponse response = solrServer.query(query);

        SortedSet<String> facetValues = new TreeSet<String>();
        for (FacetField facet : response.getFacetFields()) {
            for (Count count : facet.getValues()) {
                facetValues.add(count.getName());
            }
        }

        ArrayList<SetRecordBean> sets = new ArrayList<SetRecordBean>();
        for (String facetValue : facetValues) {
            String[] parts = facetValue.split(" - ", 2);
            String symbol = parts[0];
            String name = parts[1];
            sets.add(new SetRecordBean(symbol, name));
        }

        return new Pair<List<SetRecordBean>, Integer>(sets, sets.size());

    } catch (Exception e) {
        throw new ServiceException(e);
    }

}

From source file:ddf.catalog.source.solr.SolrCatalogProvider.java

License:Open Source License

@Override
public Set<ContentType> getContentTypes() {

    Set<ContentType> finalSet = new HashSet<>();

    String contentTypeField = resolver.getField(Metacard.CONTENT_TYPE, AttributeFormat.STRING, true);
    String contentTypeVersionField = resolver.getField(Metacard.CONTENT_TYPE_VERSION, AttributeFormat.STRING,
            true);//  w  ww. j  ava 2  s.co  m

    /*
     * If we didn't find the field, it most likely means it does not exist. If it does not
     * exist, then we can safely say that no content types are in this catalog provider
     */
    if (contentTypeField == null || contentTypeVersionField == null) {
        return finalSet;
    }

    SolrQuery query = new SolrQuery(contentTypeField + ":[* TO *]");
    query.setFacet(true);
    query.addFacetField(contentTypeField);
    query.addFacetPivotField(contentTypeField + "," + contentTypeVersionField);

    try {
        QueryResponse solrResponse = server.query(query, METHOD.POST);
        List<FacetField> facetFields = solrResponse.getFacetFields();
        for (Entry<String, List<PivotField>> entry : solrResponse.getFacetPivot()) {

            // if no content types have an associated version, the list of pivot fields will be
            // empty.
            // however, the content type names can still be obtained via the facet fields.
            if (CollectionUtils.isEmpty(entry.getValue())) {
                LOGGER.debug("No content type versions found associated with any available content types.");

                if (CollectionUtils.isNotEmpty(facetFields)) {
                    // Only one facet field was added. That facet field may contain multiple
                    // values (content type names).
                    for (FacetField.Count currContentType : facetFields.get(0).getValues()) {
                        // unknown version, so setting it to null
                        ContentTypeImpl contentType = new ContentTypeImpl(currContentType.getName(), null);

                        finalSet.add(contentType);
                    }
                }
            } else {
                for (PivotField pf : entry.getValue()) {

                    String contentTypeName = pf.getValue().toString();
                    LOGGER.debug("contentTypeName:{}", contentTypeName);

                    if (CollectionUtils.isEmpty(pf.getPivot())) {
                        // if there are no sub-pivots, that means that there are no content type
                        // versions
                        // associated with this content type name
                        LOGGER.debug("Content type does not have associated contentTypeVersion: {}",
                                contentTypeName);
                        ContentTypeImpl contentType = new ContentTypeImpl(contentTypeName, null);

                        finalSet.add(contentType);

                    } else {
                        for (PivotField innerPf : pf.getPivot()) {

                            LOGGER.debug("contentTypeVersion:{}. For contentTypeName: {}", innerPf.getValue(),
                                    contentTypeName);

                            ContentTypeImpl contentType = new ContentTypeImpl(contentTypeName,
                                    innerPf.getValue().toString());

                            finalSet.add(contentType);
                        }
                    }
                }
            }
        }

    } catch (SolrServerException e) {
        LOGGER.info("SOLR server exception getting content types", e);
    }

    return finalSet;
}

From source file:ddf.catalog.source.solr.SolrMetacardClientImpl.java

License:Open Source License

@Override
public Set<ContentType> getContentTypes() {
    Set<ContentType> finalSet = new HashSet<>();

    String contentTypeField = resolver.getField(Metacard.CONTENT_TYPE, AttributeType.AttributeFormat.STRING,
            true);/*from  w  w w.j a va 2  s  . c  o  m*/
    String contentTypeVersionField = resolver.getField(Metacard.CONTENT_TYPE_VERSION,
            AttributeType.AttributeFormat.STRING, true);

    /*
     * If we didn't find the field, it most likely means it does not exist. If it does not
     * exist, then we can safely say that no content types are in this catalog provider
     */
    if (contentTypeField == null || contentTypeVersionField == null) {
        return finalSet;
    }

    SolrQuery query = new SolrQuery(contentTypeField + ":[* TO *]");
    query.setFacet(true);
    query.addFacetField(contentTypeField);
    query.addFacetPivotField(contentTypeField + "," + contentTypeVersionField);

    try {
        QueryResponse solrResponse = client.query(query, SolrRequest.METHOD.POST);
        List<FacetField> facetFields = solrResponse.getFacetFields();
        for (Map.Entry<String, List<PivotField>> entry : solrResponse.getFacetPivot()) {

            // if no content types have an associated version, the list of pivot fields will be
            // empty.
            // however, the content type names can still be obtained via the facet fields.
            if (CollectionUtils.isEmpty(entry.getValue())) {
                LOGGER.debug("No content type versions found associated with any available content types.");

                if (CollectionUtils.isNotEmpty(facetFields)) {
                    // Only one facet field was added. That facet field may contain multiple
                    // values (content type names).
                    for (FacetField.Count currContentType : facetFields.get(0).getValues()) {
                        // unknown version, so setting it to null
                        ContentType contentType = new ContentTypeImpl(currContentType.getName(), null);

                        finalSet.add(contentType);
                    }
                }
            } else {
                for (PivotField pf : entry.getValue()) {

                    String contentTypeName = pf.getValue().toString();
                    LOGGER.debug("contentTypeName: {}", contentTypeName);

                    if (CollectionUtils.isEmpty(pf.getPivot())) {
                        // if there are no sub-pivots, that means that there are no content type
                        // versions
                        // associated with this content type name
                        LOGGER.debug("Content type does not have associated contentTypeVersion: {}",
                                contentTypeName);
                        ContentType contentType = new ContentTypeImpl(contentTypeName, null);

                        finalSet.add(contentType);

                    } else {
                        for (PivotField innerPf : pf.getPivot()) {

                            LOGGER.debug("contentTypeVersion: {}. For contentTypeName: {}", innerPf.getValue(),
                                    contentTypeName);

                            ContentType contentType = new ContentTypeImpl(contentTypeName,
                                    innerPf.getValue().toString());

                            finalSet.add(contentType);
                        }
                    }
                }
            }
        }

    } catch (SolrServerException | IOException e) {
        LOGGER.info("Solr exception getting content types", e);
    }

    return finalSet;
}

From source file:edu.cornell.mannlib.vitro.webapp.searchengine.solr.SolrConversionUtils.java

License:Open Source License

/**
 * Convert from a SearchQuery to a SolrQuery, so the Solr server may execute
 * it./*from   www  .  java2s  . co  m*/
 */
@SuppressWarnings("deprecation")
static SolrQuery convertToSolrQuery(SearchQuery query) {
    SolrQuery solrQuery = new SolrQuery(query.getQuery());
    solrQuery.setStart(query.getStart());

    int rows = query.getRows();
    if (rows >= 0) {
        solrQuery.setRows(rows);
    }

    for (String fieldToReturn : query.getFieldsToReturn()) {
        solrQuery.addField(fieldToReturn);
    }

    Map<String, Order> sortFields = query.getSortFields();
    for (String sortField : sortFields.keySet()) {
        solrQuery.addSortField(sortField, convertToSolrOrder(sortFields.get(sortField)));
    }

    for (String filter : query.getFilters()) {
        solrQuery.addFilterQuery(filter);
    }

    if (!query.getFacetFields().isEmpty()) {
        solrQuery.setFacet(true);
    }

    for (String facetField : query.getFacetFields()) {
        solrQuery.addFacetField(facetField);
    }

    int facetLimit = query.getFacetLimit();
    if (facetLimit >= 0) {
        solrQuery.setFacetLimit(facetLimit);
    }

    int minCount = query.getFacetMinCount();
    if (minCount >= 0) {
        solrQuery.setFacetMinCount(minCount);
    }

    return solrQuery;
}