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

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

Introduction

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

Prototype

public SolrQuery setFields(String... fields) 

Source Link

Usage

From source file:com.odoko.solrcli.actions.CrawlPostAction.java

License:Apache License

  @Override
public void go() {
  SolrServer server = new HttpSolrServer("http://localhost:8983/solr");

  try {//from  ww  w.  jav a2 s. co m
    SolrQuery query = new SolrQuery();
    query.setQuery(querystring);
    query.setFields(StringUtils.join(fieldlist, ","));
    for (String name : params.keySet()) {
      query.add(name, params.get(name));
    }
    QueryResponse response = server.query(query);
    if (!omitHeader) {
      printHeader(query, response);
    }
    query.add("fl", "id");
      for (SolrDocument doc : response.getResults()) {
        List<String>values = new ArrayList<String>();
        for (String fieldname : parseFieldList(query.get("fl"))) {
          values.add(toString(doc.getFieldValue(fieldname)));
        }
          System.out.println(StringUtils.join(values, "\t"));
      }
  } catch (SolrServerException e) {
    throw new RuntimeException(e);
  }
}

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

License:Open Source License

/**
 * Check that a UUID is generated for JSON documents with no 'id' attribute.
 *//*from ww w .j  av a 2s.  c o  m*/
@Test
public void testJsonWithNoId() throws IOException, SolrServerException {
    String input = "{ \"aaa\" :  \"bbb\" }";
    this.sendUpdateRequest(input);
    this.commit();

    SolrQuery query = new SolrQuery();
    query.setParam("nested", "{!lucene} *:*");
    query.setRequestHandler("tree");
    query.setFields(IdFieldMapper.INPUT_FIELD);

    SolrDocumentList results = this.search(query);
    assertEquals(1, results.getNumFound());
    assertNotNull(results.get(0).getFieldValue(IdFieldMapper.INPUT_FIELD));
}

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.
 *//*from   w  w w. ja  va 2s . c  om*/
@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.yahoo.ycsb.db.solr.SolrClient.java

License:Open Source License

/**
 * Read a record from the database. Each field/value pair from the result will be stored in a
 * HashMap.//from  w w w.j  a v a 2  s .co m
 *
 * @param table
 *          The name of the table
 * @param key
 *          The record key of the record to read.
 * @param fields
 *          The list of fields to read, or null for all of them
 * @param result
 *          A HashMap of field/value pairs for the result
 * @return Zero on success, a non-zero error code on error or "not found".
 */
@Override
public Status read(String table, String key, Set<String> fields, HashMap<String, ByteIterator> result) {
    try {
        Boolean returnFields = false;
        String[] fieldList = null;
        if (fields != null) {
            returnFields = true;
            fieldList = fields.toArray(new String[fields.size()]);
        }
        SolrQuery query = new SolrQuery();
        query.setQuery("id:" + key);
        if (returnFields) {
            query.setFields(fieldList);
        }
        final QueryResponse response = client.query(table, query);
        SolrDocumentList results = response.getResults();
        if ((results != null) && (results.getNumFound() > 0)) {
            for (String field : results.get(0).getFieldNames()) {
                result.put(field, new StringByteIterator(String.valueOf(results.get(0).getFirstValue(field))));
            }
        }
        return checkStatus(response.getStatus());
    } catch (IOException | SolrServerException e) {
        e.printStackTrace();
    }
    return Status.ERROR;
}

From source file:com.yahoo.ycsb.db.solr.SolrClient.java

License:Open Source License

/**
 * Perform a range scan for a set of records in the database. Each field/value pair from the
 * result will be stored in a HashMap.//from   www.  ja v  a2s.  c  o m
 *
 * @param table
 *          The name of the table
 * @param startkey
 *          The record key of the first record to read.
 * @param recordcount
 *          The number of records to read
 * @param fields
 *          The list of fields to read, or null for all of them
 * @param result
 *          A Vector of HashMaps, where each HashMap is a set field/value pairs for one record
 * @return Zero on success, a non-zero error code on error. See this class's description for a
 *         discussion of error codes.
 */
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
        Vector<HashMap<String, ByteIterator>> result) {
    try {
        Boolean returnFields = false;
        String[] fieldList = null;
        if (fields != null) {
            returnFields = true;
            fieldList = fields.toArray(new String[fields.size()]);
        }
        SolrQuery query = new SolrQuery();
        query.setQuery("*:*");
        query.setParam("fq", "id:[ " + startkey + " TO * ]");
        if (returnFields) {
            query.setFields(fieldList);
        }
        query.setRows(recordcount);
        final QueryResponse response = client.query(table, query);
        SolrDocumentList results = response.getResults();

        HashMap<String, ByteIterator> entry;

        for (SolrDocument hit : results) {
            entry = new HashMap<String, ByteIterator>((int) results.getNumFound());
            for (String field : hit.getFieldNames()) {
                entry.put(field, new StringByteIterator(String.valueOf(hit.getFirstValue(field))));
            }
            result.add(entry);
        }
        return checkStatus(response.getStatus());
    } catch (IOException | SolrServerException e) {
        e.printStackTrace();
    }
    return Status.ERROR;
}

From source file:com.yahoo.ycsb.db.solr6.SolrClient.java

License:Open Source License

/**
 * Perform a range scan for a set of records in the database. Each field/value pair from the
 * result will be stored in a HashMap.//from  www.  j a  va  2  s. co  m
 *
 * @param table
 *          The name of the table
 * @param startkey
 *          The record key of the first record to read.
 * @param recordcount
 *          The number of records to read
 * @param fields
 *          The list of fields to read, or null for all of them
 * @param result
 *          A Vector of HashMaps, where each HashMap is a set field/value pairs for one record
 * @return Zero on success, a non-zero error code on error. See this class's description for a
 *         discussion of error codes.
 */
@Override
public Status scan(String table, String startkey, int recordcount, Set<String> fields,
        Vector<HashMap<String, ByteIterator>> result) {
    try {
        Boolean returnFields = false;
        String[] fieldList = null;
        if (fields != null) {
            returnFields = true;
            fieldList = fields.toArray(new String[fields.size()]);
        }
        SolrQuery query = new SolrQuery();
        query.setQuery("*:*");
        query.setParam("fq", "id:[ " + startkey + " TO * ]");
        if (returnFields) {
            query.setFields(fieldList);
        }
        query.setRows(recordcount);
        final QueryResponse response = client.query(table, query);
        SolrDocumentList results = response.getResults();

        HashMap<String, ByteIterator> entry;

        for (SolrDocument hit : results) {
            entry = new HashMap<>((int) results.getNumFound());
            for (String field : hit.getFieldNames()) {
                entry.put(field, new StringByteIterator(String.valueOf(hit.getFirstValue(field))));
            }
            result.add(entry);
        }
        return checkStatus(response.getStatus());
    } catch (IOException | SolrServerException e) {
        e.printStackTrace();
    }
    return Status.ERROR;
}

From source file:cz.brmlab.yodaqa.provider.solr.Solr.java

License:Apache License

public String getDocText(String id) throws SolrServerException {
    String q = "id:" + id;
    SolrQuery query = new SolrQuery();
    query.setQuery(q);/*from  ww  w .  ja  v  a2  s  .  c o  m*/
    query.setFields("text");
    QueryResponse rsp;
    while (true) {
        try {
            rsp = server.query(query);
            break; // Success!
        } catch (SolrServerException e) {
            if (e.getRootCause() instanceof IOException)
                notifyRetry(e);
            else
                throw e;
        }
    }

    String docText = "";
    if (rsp.getResults().getNumFound() > 0) {
        @SuppressWarnings({ "unchecked", "rawtypes" })
        ArrayList<String> results = (ArrayList) rsp.getResults().get(0).getFieldValues("text");
        docText = results.get(0);
    }
    return docText;
}

From source file:cz.zcu.kiv.eegdatabase.logic.indexing.AutocompleteIndexer.java

License:Apache License

/**
 * Transforms the searched phrase to a Solr document.
 * @param phrase The input searched phrase.
 * @return The Solr document representing the searched phrase.
 * @throws IllegalAccessException//from  w  w  w .j  av a2  s. com
 * @throws IOException
 * @throws SolrServerException
 */
@Override
public SolrInputDocument prepareForIndexing(String phrase)
        throws IllegalAccessException, IOException, SolrServerException {

    SolrInputDocument document = new SolrInputDocument();

    SolrQuery query = new SolrQuery();
    query.setFields(IndexField.AUTOCOMPLETE.getValue());

    query.setQuery("uuid:autocomplete#" + phrase);
    QueryResponse response = solrServer.query(query);

    int count;
    // the phrase is not indexed yet
    if (response.getResults().size() == 0) {
        count = 0;
    }
    // already indexed
    else {
        String foundPhrase = ((List<String>) response.getResults().get(0)
                .getFieldValue(IndexField.AUTOCOMPLETE.getValue())).get(0);
        int delimiterPosition = foundPhrase.lastIndexOf('#');
        // the phrase was originally retrieved by indexing a document
        if (delimiterPosition == -1) {
            count = 0;
        }
        // the phrase was indexed after performing a search query
        else {
            count = Integer
                    .valueOf(foundPhrase.substring(foundPhrase.lastIndexOf('#') + 1, foundPhrase.length()));
        }
        count++;
    }

    document.addField(IndexField.UUID.getValue(), "autocomplete#" + phrase);
    document.addField(IndexField.ID.getValue(), 0);
    document.addField(IndexField.AUTOCOMPLETE.getValue(), phrase + "#" + count);

    return document;
}

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

License:Apache License

/**
 * Gets values to autocomplete for the input string.
 * The autocomplete feature works for multivalued fields and is based on a highlighting trick.
 * See http://solr.pl/en/2013/02/25/autocomplete-on-multivalued-fields-using-highlighting/
 * @param keywordStart//w  ww .  j av  a 2  s  .  c  o m
 * @return Autocomplete values.
 * @throws SolrServerException
 */
public Set<String> getTextToAutocomplete(String keywordStart) throws SolrServerException {
    SolrQuery query = new SolrQuery();
    query.setQuery(IndexField.AUTOCOMPLETE.getValue() + ":" + keywordStart);
    query.setFields(IndexField.AUTOCOMPLETE.getValue());
    query.setHighlight(true);
    query.setParam("hl.fl", IndexField.AUTOCOMPLETE.getValue());
    query.setHighlightSimplePre("");
    query.setHighlightSimplePost("");
    query.setRows(FullTextSearchUtils.AUTOCOMPLETE_ROWS);

    Map<String, Integer> map = new TreeMap<String, Integer>();
    QueryResponse response = solrServer.query(query);

    Set<String> foundIds = response.getHighlighting().keySet();
    for (String id : foundIds) {

        List<String> resultsPerDocument = response.getHighlighting().get(id)
                .get(IndexField.AUTOCOMPLETE.getValue());
        if (resultsPerDocument != null) {
            for (String result : resultsPerDocument) {
                String resultValue;
                int resultFrequency;
                int delimiterPosition = result.lastIndexOf('#');
                if (delimiterPosition == -1) { // autocomplete phrase was copied from title
                    resultValue = result;
                    resultFrequency = 0;
                } else {
                    resultValue = result.substring(0, delimiterPosition);
                    try {
                        resultFrequency = Integer
                                .valueOf(result.substring(delimiterPosition + 1, result.length()));
                    } catch (NumberFormatException e) {
                        resultFrequency = 0;
                    }
                }

                map.put(resultValue.toLowerCase(), resultFrequency);
            }
        }

        if (map.size() == FullTextSearchUtils.AUTOCOMPLETE_ROWS) {
            break;
        }
    }

    map = sortByValue(map);
    return map.keySet();
}

From source file:de.fatalix.bookery.bl.solr.SolrHandler.java

License:Open Source License

public QueryResponse searchSolrIndex(String queryString, String fields, int rows, int startOffset)
        throws SolrServerException {
    SolrServer solr = null;/*www  . j  a  va2s  . c o  m*/
    try {
        solr = bookeryService.getSolrConnection();
    } catch (IOException ex) {
        throw new SolrServerException(ex.getMessage());
    }
    SolrQuery query = new SolrQuery();
    query.setQuery(queryString);
    query.setRows(rows);
    query.setStart(startOffset);

    query.setFields(fields);
    QueryResponse rsp = solr.query(query);
    return rsp;
}