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

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

Introduction

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

Prototype

public SolrQuery setQuery(String query) 

Source Link

Usage

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

License:Open Source License

/**
 * {@inheritDoc}//  w w w.  j  a  v  a 2 s.c  o  m
 */
@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.sindicetech.siren.demo.ncpr.NCPRQuery.java

License:Open Source License

/**
 * A query that shows how to use a custom datatype (uri)
 *///from   w  w w  .  ja v a2 s.  com
private SolrQuery getWebsiteQuery() throws QueryNodeException {
    ConciseQueryBuilder b = new ConciseQueryBuilder();
    String q = b.newTwig("DeviceOwner").with(b.newNode("uri(www.sourcelondon.net)").setAttribute("Website"))
            .toString();
    final SolrQuery query = new SolrQuery();
    query.setQuery(q);
    return query;
}

From source file:com.sindicetech.siren.demo.ncpr.NCPRQuery.java

License:Open Source License

/**
 * A query that shows how to use range query on geo-location data (double)
 *//*from   ww w  .ja  v  a2s.  c om*/
private SolrQuery getGeoQuery() throws QueryNodeException {
    ConciseQueryBuilder b = new ConciseQueryBuilder();
    String q = b.newTwig("ChargeDeviceLocation")
            .with(b.newNode("xsd:double([52 TO 53])").setAttribute("Latitude"))
            .with(b.newNode("xsd:double([-2 TO 2])").setAttribute("Longitude")).toString();
    final SolrQuery query = new SolrQuery();
    query.setQuery(q);
    return query;
}

From source file:com.sindicetech.siren.demo.ncpr.NCPRQuery.java

License:Open Source License

/**
 * A query that shows how to use range query on long numeric value
 *//* ww  w .  j  ava2s  .c  om*/
private SolrQuery getOutputCurrentQuery() throws QueryNodeException {
    ConciseQueryBuilder b = new ConciseQueryBuilder();
    TwigQuery twig1 = b.newTwig("ChargeDeviceLocation")
            .with(b.newNode("xsd:double([52 TO 53])").setAttribute("Latitude"))
            .with(b.newNode("xsd:double([-2 TO 2])").setAttribute("Longitude"));
    TwigQuery twig2 = b.newTwig("Connector")
            .with(b.newNode("xsd:long([32 TO *])").setAttribute("RatedOutputCurrent"));
    String q = b.newBoolean().with(twig1).with(twig2).toString();

    final SolrQuery query = new SolrQuery();
    query.setQuery(q);
    return query;
}

From source file:com.sindicetech.siren.demo.ncpr.NCPRQuery.java

License:Open Source License

/**
 * A query that shows how to combine SIREn query with the Solr's facet feature
 * on a Solr field./*from   w  ww  . j a  va2  s .  com*/
 */
private SolrQuery getDeviceControllerFacet() throws QueryNodeException {
    ConciseQueryBuilder b = new ConciseQueryBuilder();
    String q = b.newTwig("Connector").with(b.newNode("xsd:long([32 TO *])").setAttribute("RatedOutputCurrent"))
            .toString();
    final SolrQuery query = new SolrQuery();
    query.setQuery(q);
    query.addFacetField("DeviceController.OrganisationName");
    return query;
}

From source file:com.sindicetech.siren.demo.ncpr.NCPRQuery.java

License:Open Source License

/**
 * A query that shows how to use the nested query parameter to use Solr's
 * query parsers on Solr's fields.//  w  w w. j a va 2 s . c  om
 */
private SolrQuery getNestedQuery() throws QueryNodeException {
    ConciseQueryBuilder b = new ConciseQueryBuilder();
    String q = b.newTwig("DeviceOwner").with(b.newNode("uri(www.sourcelondon.net)").setAttribute("Website"))
            .toString();
    final SolrQuery query = new SolrQuery();
    query.setQuery(q);
    query.setParam("nested", "{!lucene} ChargeDeviceName:university");
    return query;
}

From source file:com.sindicetech.siren.solr.analysis.TestASCIIFoldingExpansionFilterFactory.java

License:Open Source License

/**
 * SRN-96/*from   w  ww .j ava  2 s  .  co  m*/
 */
@Test
public void testASCIIFoldingExpansion() throws IOException, SolrServerException {
    this.addJsonString("1", " { \"value\" : \"cafe\" } ");
    this.addJsonString("2", " { \"value\" : \"caf\" } ");
    SolrQuery query = new SolrQuery();
    query.setQuery("cafe");
    query.setRequestHandler("keyword");
    query.setIncludeScore(true);

    // should match the two documents, with same score
    QueryResponse response = getWrapper().getServer().query(query);
    SolrDocumentList docList = response.getResults();
    assertEquals(2, docList.getNumFound());
    float score1 = (Float) docList.get(0).getFieldValue("score");
    float score2 = (Float) docList.get(1).getFieldValue("score");
    Assert.assertTrue("Score should be identical", score1 == score2);

    // should match the two documents, but should assign different score
    // id2 should receive better score than id1
    query = new SolrQuery();
    query.setQuery("caf");
    query.setRequestHandler("keyword");
    query.setIncludeScore(true);

    response = getWrapper().getServer().query(query);
    docList = response.getResults();
    assertEquals(2, docList.getNumFound());
    if (docList.get(0).getFieldValue("url").equals("id1")) {
        score1 = (Float) docList.get(0).getFieldValue("score");
        score2 = (Float) docList.get(1).getFieldValue("score");
    } else {
        score2 = (Float) docList.get(0).getFieldValue("score");
        score1 = (Float) docList.get(1).getFieldValue("score");
    }
    Assert.assertTrue("id2 should get higher score than id1", score1 < score2);
}

From source file:com.sindicetech.siren.solr.handler.TestSirenUpdateRequestHandler.java

License:Open Source License

/**
 * Check that the JSON document is correctly indexed in a SIREn's json field.
 *///  w ww.  j  ava 2  s.  c  o m
@Test
public void testJsonField() throws QueryNodeException, IOException, SolrServerException {
    String input = "{ \"id\" : \"1\", \"aaa\" :  \"bbb\" }";

    this.sendUpdateRequest(input);
    this.commit();

    SolrQuery query = new SolrQuery();
    final ConciseQueryBuilder b = new ConciseQueryBuilder();
    query.setQuery(b.newNode("bbb").setAttribute("aaa").toString());
    query.setRequestHandler("tree");
    long found = this.search(query).getNumFound();
    assertEquals(1, found);
}

From source file:com.sindicetech.siren.solr.handler.TestSirenUpdateRequestHandler.java

License:Open Source License

/**
 * Check if the field is stored as indicated by the fieldtype of the associated path-based mapper.
 *///w w  w  .  j  av a  2s .  c  o  m
@Test
public void testStoredField() throws QueryNodeException, IOException, SolrServerException {
    String input = "{ \"id\" : \"1\", \"aaa\" :  \"bbb\" }";

    this.sendUpdateRequest(input);
    this.commit();

    SolrQuery query = new SolrQuery();
    final ConciseQueryBuilder b = new ConciseQueryBuilder();
    query.setQuery(b.newNode("bbb").setAttribute("aaa").toString());
    query.setRequestHandler("tree");
    query.setFields("aaa");

    SolrDocumentList result = this.search(query);
    assertEquals(1, result.getNumFound());
    assertNotNull(result.get(0).getFieldValue("aaa"));
    assertTrue(result.get(0).getFieldValue("aaa") instanceof ArrayList);
    assertEquals("bbb", ((ArrayList) result.get(0).getFieldValue("aaa")).get(0));
}

From source file:com.sindicetech.siren.solr.handler.TestSirenUpdateRequestHandler.java

License:Open Source License

/**
 * Check that the nested query and the main query are intersected, i.e., that each one is assigned a MUST operator.
 * See issue #60.//  w ww.  jav a  2s  .  co m
 */
@Test
public void testNestedQuery() throws IOException, SolrServerException, QueryNodeException {
    String input = "{ \"aaa\" : null, \"ChargeDeviceRef\" : \"CM765\", \"ChargeDeviceLocation\" : { \"Address\" : { \"PostTown\" : \"Peterborough\" } } }";
    this.sendUpdateRequest(input);
    input = "{ \"aaa\" : null, \"ChargeDeviceRef\" : \"CM556\", \"ChargeDeviceLocation\" : { \"Address\" : { \"PostTown\" : \"Peterborough\" } } }";
    this.sendUpdateRequest(input);
    input = "{ \"aaa\" : null, \"ChargeDeviceRef\" : \"CM779\", \"ChargeDeviceLocation\" : { \"Address\" : { \"PostTown\" : \"Peterborough\" } } }";
    this.sendUpdateRequest(input);

    this.commit();

    SolrQuery query = new SolrQuery();
    final ConciseQueryBuilder b = new ConciseQueryBuilder();
    query.setQuery(b.newNode("CM765").setAttribute("ChargeDeviceRef").toString());
    query.setParam("nested", "ChargeDeviceLocation.Address.PostTown:Peterborough");
    query.setRequestHandler("tree");

    long found = this.search(query).getNumFound();
    assertEquals(1, found);
}