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

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

Introduction

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

Prototype

String Q

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

Click Source Link

Document

query string

Usage

From source file:org.phenotips.vocabulary.internal.solr.AbstractSolrVocabulary.java

License:Open Source License

/**
 * Get the number of entries that match a specific Lucene query.
 *
 * @param query a valid the Lucene query as string
 * @return the number of entries matching the query
 *//* ww  w  . ja  va2  s.  c o m*/
protected long count(String query) {
    ModifiableSolrParams params = new ModifiableSolrParams();
    params.set(CommonParams.Q, query);
    params.set(CommonParams.START, "0");
    params.set(CommonParams.ROWS, "0");
    SolrDocumentList results;
    try {
        this.logger.debug("Counting terms matching [{}] in [{}]", query, getCoreName());
        results = this.externalServicesAccess.getSolrConnection().query(params).getResults();
        return results.getNumFound();
    } catch (Exception ex) {
        this.logger.error("Failed to count ontology terms: {}", ex.getMessage(), ex);
        return -1;
    }
}

From source file:org.phenotips.vocabulary.internal.solr.HumanPhenotypeOntology.java

License:Open Source License

private SolrParams produceDynamicSolrParams(String originalQuery, Integer rows, String sort, String customFq,
        boolean isId) {
    String query = originalQuery.trim();
    ModifiableSolrParams params = new ModifiableSolrParams();
    String escapedQuery = ClientUtils.escapeQueryChars(query);
    if (isId) {/*ww w  .  j  a v  a 2 s.  c  o  m*/
        params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFq,
                new MessageFormat("id:{0} alt_id:{0}").format(new String[] { escapedQuery })));
    } else {
        params.add(CommonParams.FQ, StringUtils.defaultIfBlank(customFq, "term_category:HP\\:0000118"));
    }
    params.add(CommonParams.Q, escapedQuery);
    params.add(SpellingParams.SPELLCHECK_Q, query);
    params.add(CommonParams.ROWS, rows.toString());
    if (StringUtils.isNotBlank(sort)) {
        params.add(CommonParams.SORT, sort);
    }
    return params;
}

From source file:org.phenotips.vocabulary.internal.solr.MendelianInheritanceInMan.java

License:Open Source License

private SolrParams produceDynamicSolrParams(String originalQuery, Integer rows, String sort, String customFq) {
    String query = originalQuery.trim();
    ModifiableSolrParams params = new ModifiableSolrParams();
    String escapedQuery = ClientUtils.escapeQueryChars(query);
    params.add(CommonParams.FQ,/*from  ww w  .  j a va 2  s  . c om*/
            StringUtils.defaultIfBlank(customFq, "-(nameSort:\\** nameSort:\\+* nameSort:\\^*)"));
    params.add(CommonParams.Q, escapedQuery);
    params.add(SpellingParams.SPELLCHECK_Q, query);
    String lastWord = StringUtils.substringAfterLast(escapedQuery, " ");
    if (StringUtils.isBlank(lastWord)) {
        lastWord = escapedQuery;
    }
    lastWord += "*";
    params.add(DisMaxParams.BQ,
            String.format("nameSpell:%1$s^20 keywords:%1$s^2 text:%1$s^1 textSpell:%1$s^2", lastWord));
    params.add(CommonParams.ROWS, rows.toString());
    if (StringUtils.isNotBlank(sort)) {
        params.add(CommonParams.SORT, sort);
    }
    return params;
}

From source file:org.phenotips.vocabulary.internal.solr.SolrQueryUtils.java

License:Open Source License

/**
 * Replaces the original query in the Solr parameters with the suggested spellchecked query. It also fixes the boost
 * query, if any.// w w  w. jav a2 s  .co  m
 *
 * @param originalParams the original Solr parameters to fix
 * @param suggestedQuery the suggested query
 * @return new Solr parameters with the query and boost query fixed
 */
public static SolrParams applySpellcheckSuggestion(SolrParams originalParams, String suggestedQuery) {
    if (originalParams == null) {
        return null;
    }
    if (StringUtils.isBlank(suggestedQuery)) {
        return originalParams;
    }
    ModifiableSolrParams newParams = new ModifiableSolrParams(originalParams);
    String newQuery = suggestedQuery;

    // Since the spelling suggestion might not be that good, also search for the original user input
    if (StringUtils.isNotEmpty(originalParams.get(SpellingParams.SPELLCHECK_Q))) {
        newQuery = originalParams.get(CommonParams.Q) + "^10 " + suggestedQuery;
    }

    // Check if the last term in the query is a word stub search which, in case the request comes from a
    // user-triggered search for terms from the UI, is a prefix search for the last typed word
    Matcher originalStub = WORD_STUB.matcher(newParams.get(CommonParams.Q));
    Matcher newStub = WORD_STUB.matcher(suggestedQuery);
    if (originalStub.find() && newStub.find() && !StringUtils.equals(originalStub.group(2), newStub.group(2))) {
        // Since word stubs aren't complete words, they may wrongly be "corrected" to a full word that doesn't match
        // what the user started typing; include both the original stub and the "corrected" stub in the query
        newQuery += ' ' + originalStub.group() + "^1.5";
        // Also fix the boost query
        String boostQuery = newParams.get(DisMaxParams.BQ);
        if (StringUtils.isNotEmpty(boostQuery)) {
            newParams.add(DisMaxParams.BQ, boostQuery.replace(originalStub.group(2), newStub.group(2)));
        }
    }
    // Replace the query
    newParams.set(CommonParams.Q, newQuery);

    return newParams;
}

From source file:org.springframework.data.solr.core.SolrTemplateTests.java

License:Apache License

@Test
public void testDifferentQueryParser() throws SolrServerException {
    QueryParser parser = new QueryParser() {

        @Override/*from w w w  . j a v a 2  s .  c om*/
        public void registerConverter(Converter<?, ?> converter) {
        }

        @Override
        public String getQueryString(SolrDataQuery query) {
            return "*:*";
        }

        @Override
        public SolrQuery constructSolrQuery(SolrDataQuery query) {
            return new SolrQuery(getQueryString(query));
        }

    };

    solrTemplate.registerQueryParser(SimpleQuery.class, parser);
    solrTemplate.query(new SimpleQuery(new SimpleStringCriteria("my:criteria")), null);

    ArgumentCaptor<SolrParams> captor = ArgumentCaptor.forClass(SolrParams.class);

    Mockito.verify(solrServerMock, Mockito.times(1)).query(captor.capture());
    Assert.assertEquals("*:*", captor.getValue().getParams(CommonParams.Q)[0]);
}

From source file:org.tallison.solr.search.concordance.KeywordCooccurRankHandler.java

License:Apache License

static public RequestThreads<CooccurConfig> initRequestPump(List<String> shards, SolrQueryRequest req,
        int maxThreads) {

    SolrParams params = req.getParams();
    String field = SolrConcordanceBase.getField(params, req.getSchema().getDefaultSearchFieldName());
    String q = params.get(CommonParams.Q);
    CooccurConfig config = configureParams(field, params);

    /**///from w  w  w . j  a  va  2 s .  c om
    RequestThreads<CooccurConfig> threads = RequestThreads
            .<CooccurConfig>newFixedThreadPool(Math.min(shards.size(), maxThreads)).setMetadata(config);

    String handler = getHandlerName(req, DefaultName, KeywordCooccurRankHandler.class);
    int partial = Math.round(config.getMaxWindows() / (float) shards.size());

    ModifiableSolrParams p = getWorkerParams(field, q, params, partial);

    int i = 0;
    for (String node : shards) {
        if (i++ > maxThreads)
            break;

        //could be https, no?
        String url = "http://" + node;

        RequestWorker worker = new RequestWorker(url, handler, p).setName(node);
        threads.addExecute(worker);
    }
    threads.seal(); //disallow future requests (& execute

    return threads;
}

From source file:org.tallison.solr.search.concordance.KeywordCooccurRankHandler.java

License:Apache License

public static NamedList doLocalSearch(Query filter, SolrQueryRequest req) throws Exception {
    SolrParams params = req.getParams();
    String field = getField(params);

    String fl = params.get(CommonParams.FL);
    DocMetadataExtractor metadataExtractor = (fl != null && fl.length() > 0)
            ? new SimpleDocMetadataExtractor(fl.split(","))
            : new SimpleDocMetadataExtractor();

    CooccurConfig config = configureParams(field, params);

    IndexSchema schema = req.getSchema();
    SchemaField sf = schema.getField(field);
    Analyzer analyzer = sf.getType().getIndexAnalyzer();
    Filter queryFilter = getFilterQuery(req);
    String q = params.get(CommonParams.Q);
    Query query = QParser.getParser(q, null, req).parse();
    String solrUniqueKeyField = req.getSchema().getUniqueKeyField().getName();

    SolrIndexSearcher solr = req.getSearcher();
    IndexReader reader = solr.getIndexReader();
    boolean allowDuplicates = false;
    boolean allowFieldSeparators = false;

    Grammer grammer = new WGrammer(config.getMinNGram(), config.getMaxNGram(), allowFieldSeparators);
    IDFCalc idfCalc = new IDFCalc(reader);

    CooccurVisitor visitor = new CooccurVisitor(field, config.getTokensBefore(), config.getTokensAfter(),
            grammer, idfCalc, config.getMaxWindows(), allowDuplicates);

    visitor.setMinTermFreq(config.getMinTermFreq());

    try {/* w  w  w . jav a 2s .com*/
        ConcordanceArrayWindowSearcher searcher = new ConcordanceArrayWindowSearcher();
        System.out.println("UNIQUE KEY FIELD: " + solrUniqueKeyField);
        DocIdBuilder docIdBuilder = new FieldBasedDocIdBuilder(solrUniqueKeyField);
        System.out.println("QUERY: " + query.toString());
        searcher.search(reader, field, query, queryFilter, analyzer, visitor, docIdBuilder);
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TargetTokenNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    List<TermIDF> overallResults = visitor.getResults();
    NamedList results = toNamedList(overallResults);
    //needed for cloud computations, merging cores

    results.add("collectionSize", reader.numDocs());
    results.add("numDocsVisited", visitor.getNumDocsVisited());
    results.add("numWindowsVisited", visitor.getNumWindowsVisited());
    results.add("numResults", overallResults.size());
    results.add("minTF", visitor.getMinTermFreq());

    return results;
}

From source file:org.tallison.solr.search.concordance.KWICRequestHandler.java

License:Apache License

public static NamedList doLocalSearch(Query filter, SolrQueryRequest req) throws Exception {
    SolrParams params = req.getParams();
    String field = getField(params, req.getSchema().getDefaultSearchFieldName());

    String q = params.get(CommonParams.Q);

    String fl = params.get(CommonParams.FL);
    String solrUniqueKeyField = req.getSchema().getUniqueKeyField().getName();
    DocMetadataExtractor metadataExtractor = (fl != null && fl.length() > 0)
            ? new SimpleDocMetadataExtractor(fl.split(","))
            : new SimpleDocMetadataExtractor();

    Filter queryFilter = getFilterQuery(req);

    //TODO remove and only use index
    String anType = params.get("anType", "query").toLowerCase();

    IndexSchema schema = req.getSchema();
    Analyzer analyzer = null;//w  w  w .java2s  . c  o m
    SchemaField sf = schema.getField(field);
    if (sf != null && sf.getType() != null) {
        if (anType.equals("query")) {
            analyzer = sf.getType().getQueryAnalyzer();
        } else {
            analyzer = sf.getType().getIndexAnalyzer();
        }
    } else {
        throw new RuntimeException("No analyzer found for field " + field);
    }

    Query query = QParser.getParser(q, null, req).parse();

    IndexReader reader = req.getSearcher().getIndexReader();
    ConcordanceConfig config = buildConcordanceConfig(field, solrUniqueKeyField, params);

    WindowBuilder windowBuilder = new WindowBuilder(config.getTokensBefore(), config.getTokensAfter(), 100,
            new DefaultSortKeyBuilder(config.getSortOrder()), metadataExtractor,
            new FieldBasedDocIdBuilder(solrUniqueKeyField));

    ConcordanceSearcher searcher = new ConcordanceSearcher(windowBuilder);

    AbstractConcordanceWindowCollector collector = new ConcordanceWindowCollector(config.getMaxWindows());

    searcher.search(reader, field, query, queryFilter, analyzer, collector);

    NamedList results = convertToList(solrUniqueKeyField, collector);

    return results;
}

From source file:org.tallison.solr.search.concordance.KWICRequestHandler.java

License:Apache License

static public RequestThreads<ConcordanceConfig> initRequestPump(List<String> shards, SolrQueryRequest req,
        int maxThreads) {
    SolrParams params = req.getParams();
    String field = SolrConcordanceBase.getField(params, req.getSchema().getDefaultSearchFieldName());
    String q = params.get(CommonParams.Q);
    ConcordanceConfig config = buildConcordanceConfig(field, req.getSchema().getUniqueKeyField().getName(),
            params);/*w w  w  .  j a v a2s .com*/

    /**/
    RequestThreads<ConcordanceConfig> threads = RequestThreads
            .<ConcordanceConfig>newFixedThreadPool(Math.min(shards.size(), maxThreads)).setMetadata(config);

    String handler = getHandlerName(req, DefaultName, KWICRequestHandler.class);
    int windowsForEach = config.getMaxWindows();//Math.round(config.getMaxWindows() / (float)shards.size()) ;

    ModifiableSolrParams p = getWorkerParams(field, q, params, windowsForEach);

    int i = 0;
    for (String node : shards) {
        if (i++ > maxThreads)
            break;

        //could be https, no?
        String url = "http://" + node;

        RequestWorker worker = new RequestWorker(url, handler, p).setName(node);
        threads.addExecute(worker);
    }
    threads.seal(); //disallow future requests (& execute

    return threads;
}

From source file:sample.solr.SampleSolrIntegrationTest.java

License:Apache License

@Test
public void testHome() throws Exception {

    ModifiableSolrParams solrParams = new ModifiableSolrParams();
    solrParams.add(CommonParams.Q, "*:*");
    QueryResponse queryResponse = server.query(solrParams);
    for (SolrDocument document : queryResponse.getResults()) {
        LOG.error("document" + document);
    }//from w  w w.  j  ava 2s .c o m
    LOG.error("queryResponse" + queryResponse);

}