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

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

Introduction

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

Prototype

String FL

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

Click Source Link

Document

query and init param for field list

Usage

From source file:at.pagu.soldockr.core.QueryParser.java

License:Apache License

private void appendProjectionOnFields(SolrQuery solrQuery, List<Field> fields) {
    if (CollectionUtils.isEmpty(fields)) {
        return;/*from w  ww. j  av a2  s . co m*/
    }
    solrQuery.setParam(CommonParams.FL, StringUtils.join(fields, ","));
}

From source file:at.pagu.soldockr.core.QueryParserTest.java

License:Apache License

private void assertProjectionPresent(SolrQuery solrQuery, String expected) {
    Assert.assertNotNull(solrQuery.get(CommonParams.FL));
    Assert.assertEquals(expected, solrQuery.get(CommonParams.FL));
}

From source file:com.doculibre.constellio.services.IndexFieldServicesImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*w w  w  .ja  v  a 2s  .  c o m*/
public List<String> suggestValues(IndexField indexField, String text) {
    List<String> values = new ArrayList<String>();
    RecordCollection collection = indexField.getRecordCollection();
    SolrServices solrServices = ConstellioSpringUtils.getSolrServices();
    SolrServer solrServer = solrServices.getSolrServer(collection);
    if (solrServer != null) {
        SolrQuery query = new SolrQuery();
        query.setRequestHandler("/admin/luke");
        query.setParam(CommonParams.FL, indexField.getName());
        query.setParam(LukeRequestHandler.NUMTERMS, "" + 100);

        if (text != null) {
            query.setQuery(indexField.getName() + ":" + text + "*");
        }
        if (collection.isOpenSearch()) {
            query.setParam("openSearchURL", collection.getOpenSearchURL());
        }

        try {
            QueryResponse queryResponse = solrServer.query(query);
            NamedList<Object> fields = (NamedList<Object>) queryResponse.getResponse().get("fields");
            if (fields != null) {
                NamedList<Object> field = (NamedList<Object>) fields.get(indexField.getName());
                if (field != null) {
                    NamedList<Object> topTerms = (NamedList<Object>) field.get("topTerms");
                    if (topTerms != null) {
                        for (Map.Entry<String, Object> topTerm : topTerms) {
                            String topTermKey = topTerm.getKey();
                            if (text == null || topTermKey.toLowerCase().startsWith(text.toLowerCase())) {
                                values.add(topTerm.getKey());
                            }
                        }
                    }
                }
            }
        } catch (SolrServerException e) {
            throw new RuntimeException(e);
        }
    }
    return values;
}

From source file:com.frank.search.solr.core.QueryParserBase.java

License:Apache License

/**
 * Append field list to {@link org.apache.solr.client.solrj.SolrQuery}
 *
 * @param solrQuery/*  w  w  w. ja v a2  s . com*/
 * @param fields
 */
protected void appendProjectionOnFields(SolrQuery solrQuery, List<Field> fields) {
    if (CollectionUtils.isEmpty(fields)) {
        return;
    }
    List<String> solrReadableFields = new ArrayList<String>();
    for (Field field : fields) {
        if (field instanceof CalculatedField) {
            solrReadableFields.add(createCalculatedFieldFragment((CalculatedField) field));
        } else {
            solrReadableFields.add(field.getName());
        }
    }
    solrQuery.setParam(CommonParams.FL, StringUtils.join(solrReadableFields, ","));
}

From source file:com.search.MySearchHandler.java

License:Apache License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    // int sleep = req.getParams().getInt("sleep",0);
    // if (sleep > 0) {log.error("SLEEPING for " + sleep);
    // Thread.sleep(sleep);}

    /*** Pre-processing of the Query by REGEX starts here -------------- ***/
    SolrParams originalParams = req.getOriginalParams();
    SolrParams psuedoParams = req.getParams(); // These psuedoParams keep
    // changing/*  w ww.j  a  v a 2s.c  o  m*/
    if (originalParams.get(CommonParams.Q) != null) {
        String finalQuery;
        String originalQuery = originalParams.get(CommonParams.Q);
        rsp.add("Original query", originalQuery);
        SchemaField keyField = null;
        keyField = req.getCore().getLatestSchema().getUniqueKeyField();
        if (keyField != null) {
            fieldSet.add(keyField.getName());
        }
        /***
         * START CODE TO PARSE QUERY
         * 
         * Arafath's code to prepare query starts here The query should be
         * in the following format ->
         * 
         * 
         * 
         * Example : Original Query:
         * "Which musical object did russ conway play" Temporary Query :
         * "relations:instrument AND entity:enty" // Generate the relation
         * Final Query : "name:"russ conway" AND occupation:musician"
         */
        ParsedQuestion parsedq = new ParsedQuestion();
        parsedq = parseQues(originalQuery);
        if (parsedq != null) {
            System.out.println(parsedq);
            Map<Integer, String> relationstr = getRelation(parsedq.getRelationKeyWord(), parsedq.getWhtype(),
                    req);

            /**
             * END CODE TO PARSE QUERY
             */

            /*** Final Phase starts here ***/
            finalQuery = "title:\"" + parsedq.getSearchName() + "\"";
            NamedList finalparamsList = req.getParams().toNamedList();
            finalparamsList.setVal(finalparamsList.indexOf(CommonParams.Q, 0), finalQuery);
            psuedoParams = SolrParams.toSolrParams(finalparamsList);
            if (psuedoParams.get(CommonParams.SORT) == null) {
                finalparamsList.add(CommonParams.SORT, "score desc");
            } else {
                finalparamsList.setVal(finalparamsList.indexOf(CommonParams.SORT, 0), "score desc");
            }
            int documentsRetrieved = 0;
            if (relationstr != null) {
                rsp.add("total relations retrieved", relationstr.size());
                rsp.add("relations", relationstr);
                NamedList finaldocresults = new NamedList();
                NamedList forwarddocresults = new NamedList();
                Set<String> checkDocuments = new HashSet<String>();

                for (int i = 0; i < relationstr.size() && (documentsRetrieved < 10); i++) {
                    NamedList relationdocresults = new NamedList();
                    String desiredField = relationstr.get(i);
                    Set<String> tempFieldSet = new HashSet<String>();
                    int docsRetrievedforThisRelation = 0;
                    tempFieldSet.add(desiredField);
                    psuedoParams = SolrParams.toSolrParams(finalparamsList);
                    if (psuedoParams.get(CommonParams.FL) == null) {
                        finalparamsList.add(CommonParams.FL, desiredField);
                    } else {
                        finalparamsList.setVal(finalparamsList.indexOf(CommonParams.FL, 0), desiredField);
                    }
                    SolrQueryRequest finalreq = new LocalSolrQueryRequest(req.getCore(), finalparamsList);
                    rsp.add("Final Query", finalreq.getParams().get(CommonParams.Q));

                    SolrQueryResponse finalrsp = new SolrQueryResponse();

                    ResponseBuilder finalrb = new ResponseBuilder(finalreq, finalrsp, components);
                    for (SearchComponent c : components) {
                        c.prepare(finalrb);
                        c.process(finalrb);
                    }

                    DocList finaldocs = finalrb.getResults().docList;
                    if (finaldocs == null || finaldocs.size() == 0) {
                        log.debug("No results");
                        // support for reverse query
                    } else {
                        DocIterator finaliterator = finaldocs.iterator();
                        Document finaldoc;
                        for (int j = 0; j < finaldocs.size(); j++) {
                            try {
                                if (finaliterator.hasNext()) {
                                    int finaldocid = finaliterator.nextDoc();
                                    finaldoc = finalrb.req.getSearcher().doc(finaldocid, tempFieldSet);
                                    if (!checkDocuments.contains(finaldoc.get("id"))) {
                                        if (finaldoc.get(desiredField) != null) {
                                            checkDocuments.add(finaldoc.get("id"));
                                            docsRetrievedforThisRelation++;
                                            documentsRetrieved++;
                                            relationdocresults.add(finaldoc.get("title"), finaldoc);
                                            if (documentsRetrieved >= 10) {
                                                break;
                                            }
                                        }
                                    }
                                }
                            } catch (IOException ex) {
                                java.util.logging.Logger.getLogger(MySearchHandler.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                        }
                        if (docsRetrievedforThisRelation > 0) {
                            rsp.add("docs retrieved for : " + desiredField, docsRetrievedforThisRelation);
                            forwarddocresults.add(desiredField, relationdocresults);
                        }
                    }
                    finalreq.close();
                    if (documentsRetrieved > 0) {
                        rsp.add("type", "forward");
                        rsp.add("final results", forwarddocresults);
                    }
                }
                if (documentsRetrieved == 0) {
                    NamedList reversedocresults = new NamedList();
                    relationstr = getRelationReverse(parsedq.getRelationKeyWord(), req);
                    System.out.println(relationstr);
                    StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_46);
                    String reversequery = "";
                    for (int i = 0; i < relationstr.size(); i++) {
                        QueryParser relationsparser = new QueryParser(Version.LUCENE_46, relationstr.get(i),
                                analyzer);
                        try {
                            reversequery += relationsparser.parse(parsedq.getSearchName()).toString() + " ";
                        } catch (ParseException e) {

                            e.printStackTrace();
                        }
                    }
                    QueryParser relationsparser = new QueryParser(Version.LUCENE_46, "infotype", analyzer);
                    reversequery += relationsparser.parse(parsedq.getWhtype().firstKey().toLowerCase());

                    NamedList reverseList = req.getParams().toNamedList();
                    psuedoParams = SolrParams.toSolrParams(reverseList);
                    reverseList.setVal(reverseList.indexOf(CommonParams.Q, 0), reversequery);
                    SolrQueryRequest reversereq = new LocalSolrQueryRequest(req.getCore(), reverseList);
                    SolrQueryResponse reversersp = new SolrQueryResponse();
                    ResponseBuilder reverserb = new ResponseBuilder(reversereq, reversersp, components);
                    for (SearchComponent c : components) {
                        try {
                            c.prepare(reverserb);
                            c.process(reverserb);
                        } catch (IOException ex) {

                            java.util.logging.Logger.getLogger(MySearchHandler.class.getName())
                                    .log(Level.SEVERE, null, ex);
                        }
                    }
                    DocList reversedocs = reverserb.getResults().docList;
                    if (reversedocs == null || reversedocs.size() == 0) {
                        log.debug("No results");
                        // GET SECOND entry from WHTYPE .. search with that ..
                    } else {
                        //   NamedList docresults = new NamedList();
                        DocIterator reverseiterator = reversedocs.iterator();
                        Document reversedoc;
                        int docScore = 0;
                        for (int m = 0; m < reversedocs.size(); m++) {
                            try {
                                int reversedocid = reverseiterator.nextDoc();
                                reversedoc = reverserb.req.getSearcher().doc(reversedocid, fieldSet);
                                if (reversedoc.get("title") != null) {
                                    documentsRetrieved++;
                                    reversedocresults.add(reversedoc.get("title"), reversedoc);
                                    if (documentsRetrieved >= 10) {
                                        break;
                                    }
                                }
                            } catch (IOException ex) {
                                java.util.logging.Logger.getLogger(MySearchHandler.class.getName())
                                        .log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                    if (documentsRetrieved == 0) {
                        rsp.add("message", "No Results found. Try another query!");
                    } else {
                        rsp.add("type", "reverse");
                        rsp.add("final results", reversedocresults);
                    }
                    reversereq.close();
                }
            } else {
                if (documentsRetrieved == 0) {
                    rsp.add("message", "No Results found. Please rephrase the query!");
                }
            }
        } else {
            rsp.add("message", "This is not a valid query!");
        }
    } else {
        rsp.add("message", "User should provide at least one word as a query!");
    }
}

From source file:com.sn.solr.plugin.common.SolrHelper.java

License:Apache License

/**
 * Util method to return a list of fields. 
 * /*  w w  w . j a  v a  2s  .c om*/
 * @param req {@link SolrQueryRequest}
 * @return {@link Set} Returns set of {@link String} field names.
 */
public static Set<String> getReturnFields(SolrQueryRequest req) {
    Set<String> fields = new HashSet<String>();
    String fl = req.getParams().get(CommonParams.FL);
    if (fl == null || fl.equals("")) {
        return fields;
    }
    String[] fls = fl.split(",");
    IndexSchema schema = req.getSchema();
    for (String f : fls) {
        if ("*".equals(f)) {
            Map<String, SchemaField> fm = schema.getFields();
            for (String fieldname : fm.keySet()) {
                SchemaField sf = fm.get(fieldname);
                if (sf.stored()) {
                    fields.add(fieldname);
                }
            }
        } else {
            fields.add(f);
        }
    }
    return fields;
}

From source file:com.zemanta.solrcassandrabridge.CassandraBridgeComponent.java

License:Apache License

@Override
public void process(ResponseBuilder rb) throws IOException {

    // First we need to get Documents, so we get the "id" of the field
    Set<String> fields = new HashSet<String>();
    fields.add(key_field_name);//ww  w  .j  a  va 2s  .  c o  m
    SolrDocumentList docs = SolrPluginUtils.docListToSolrDocumentList(rb.getResults().docList,
            rb.req.getSearcher(), fields, null);

    // Docid_list is an array of ids to be retrieved
    List<BigInteger> docid_list = new ArrayList<BigInteger>();
    // We'll be putting things into output map in the form of {id: {field_name: value, ...}, ...}
    HashMap<BigInteger, HashMap<String, String>> output_map = new HashMap<BigInteger, HashMap<String, String>>();

    // Iterate through documents and get values of their id field
    for (SolrDocument doc : docs) {
        int docid = (Integer) doc.getFieldValue(key_field_name);
        docid_list.add(BigInteger.valueOf(docid));
        // prepare an output map for this id - empty hashmaps to be filled
        output_map.put(BigInteger.valueOf(docid), new HashMap<String, String>());
    }

    // Intersection of requested fields and bridged fields is what we will ask cassandra for
    ReturnFields returnFields = new SolrReturnFields(rb.req.getParams().getParams(CommonParams.FL), rb.req);
    Set<String> cassandra_fields;
    if (returnFields.wantsAllFields()) {
        cassandra_fields = bridged_fields;
    } else {
        cassandra_fields = returnFields.getLuceneFieldNames();
        cassandra_fields.retainAll(bridged_fields);
    }
    log.warn("Fields." + String.valueOf(cassandra_fields));

    // Get specific fields from cassandra to output_map
    cassandraConnector.getFieldsFromCassandra(docid_list, output_map, new ArrayList<String>(cassandra_fields));

    // Iterate through documents for the second time
    // Add the fields that cassandra returned
    // We could skip intermediate map, but we prefer separation of code messing with cassandra from code messing with solr structures
    for (SolrDocument doc : docs) {
        int docid = (Integer) doc.getFieldValue(key_field_name);
        for (Map.Entry<String, String> entry : output_map.get(BigInteger.valueOf(docid)).entrySet()) {
            doc.setField(entry.getKey(), entry.getValue());
        }
    }

    /// We replace the current response
    @SuppressWarnings("unchecked")
    NamedList<SolrDocumentList> vals = rb.rsp.getValues();
    int idx = vals.indexOf("response", 0);
    if (idx >= 0) {
        // I am pretty sure we always take this code path
        log.debug("Replacing DocList with SolrDocumentList " + docs.size());
        vals.setVal(idx, docs);
    } else {
        log.debug("Adding SolrDocumentList response" + docs.size());
        vals.add("response", docs);
    }

}

From source file:de.qaware.chronix.solr.query.analysis.AnalysisHandler.java

License:Apache License

private Map<String, List<SolrDocument>> findDocuments(SolrQueryRequest req,
        Function<SolrDocument, String> collectionKey) throws IOException {
    String query = req.getParams().get(CommonParams.Q);
    Set<String> fields = getFields(req.getParams().get(CommonParams.FL));

    //query and collect all documents
    DocList result = docListProvider.doSimpleQuery(query, req, 0, Integer.MAX_VALUE);
    SolrDocumentList docs = docListProvider.docListToSolrDocumentList(result, req.getSearcher(), fields, null);
    return AnalysisDocumentBuilder.collect(docs, collectionKey);
}

From source file:de.qaware.chronix.solr.query.ChronixQueryHandler.java

License:Apache License

@Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception {
    ModifiableSolrParams modifiableSolrParams = new ModifiableSolrParams(req.getParams());

    String originQuery = modifiableSolrParams.get(CommonParams.Q);

    long[] startAndEnd = dateRangeParser.getNumericQueryTerms(originQuery);
    long queryStart = or(startAndEnd[0], -1, 0);
    long queryEnd = or(startAndEnd[1], -1, Long.MAX_VALUE);

    modifiableSolrParams.set(ChronixQueryParams.QUERY_START_LONG, String.valueOf(queryStart));
    modifiableSolrParams.set(ChronixQueryParams.QUERY_END_LONG, String.valueOf(queryEnd));

    String query = dateRangeParser.replaceRangeQueryTerms(originQuery);

    modifiableSolrParams.set(CommonParams.Q, query);

    //Set the min required fields if the user define a sub set of fields
    modifiableSolrParams.set(CommonParams.FL, minRequiredFields(modifiableSolrParams.get(CommonParams.FL)));
    //Set the updated query
    req.setParams(modifiableSolrParams);

    //check the filter queries
    String[] filterQueries = modifiableSolrParams.getParams(CommonParams.FQ);

    //if we have an isAggregation
    if (contains(filterQueries, ChronixQueryParams.AGGREGATION_PARAM)
            || contains(filterQueries, ChronixQueryParams.ANALYSIS_PARAM)) {
        analysisHandler.handleRequestBody(req, rsp);

    } else {/*from w w w. j av a2s. c  om*/
        //let the default search handler do its work
        searchHandler.handleRequestBody(req, rsp);
    }

    //add the converted start and end to the response
    rsp.getResponseHeader().add(ChronixQueryParams.QUERY_START_LONG, queryStart);
    rsp.getResponseHeader().add(ChronixQueryParams.QUERY_END_LONG, queryEnd);
}

From source file:edu.toronto.cs.phenotips.solr.AbstractSolrScriptService.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  . jav a2  s . c  om*/
 * 
 * @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 {
        NamedList<Object> newParams = params.toNamedList();
        if (newParams.get(CommonParams.FL) == null) {
            newParams.add(CommonParams.FL, "* score");
        }
        QueryResponse response = this.server.query(MapSolrParams.toSolrParams(newParams));
        SolrDocumentList results = response.getResults();
        if (response.getSpellCheckResponse() != null
                && !response.getSpellCheckResponse().isCorrectlySpelled()) {
            String suggestedQuery = response.getSpellCheckResponse().getCollatedResult();
            if (StringUtils.isEmpty(suggestedQuery)) {
                return results;
            }
            Pattern p = Pattern.compile("(\\w++):(\\w++)\\*$", Pattern.CASE_INSENSITIVE);
            Matcher originalStub = p.matcher((String) newParams.get(CommonParams.Q));
            newParams.remove(CommonParams.Q);
            Matcher newStub = p.matcher(suggestedQuery);
            if (originalStub.find() && newStub.find()) {
                suggestedQuery += ' ' + originalStub.group() + "^1.5 " + originalStub.group(2) + "^1.5";
                String boostQuery = (String) newParams.get(DisMaxParams.BQ);
                if (boostQuery != null) {
                    boostQuery += ' ' + boostQuery.replace(originalStub.group(2), newStub.group(2));
                    newParams.remove(DisMaxParams.BQ);
                    newParams.add(DisMaxParams.BQ, boostQuery);
                }
            }
            newParams.add(CommonParams.Q, suggestedQuery);
            SolrDocumentList spellcheckResults = this.server.query(MapSolrParams.toSolrParams(newParams))
                    .getResults();
            if (results.getMaxScore() < spellcheckResults.getMaxScore()) {
                results = spellcheckResults;
            }
        }
        return results;
    } catch (SolrServerException ex) {
        this.logger.error("Failed to search: {}", ex.getMessage(), ex);
    }
    return null;
}