Example usage for org.apache.solr.search QParser parse

List of usage examples for org.apache.solr.search QParser parse

Introduction

In this page you can find the example usage for org.apache.solr.search QParser parse.

Prototype

public abstract Query parse() throws SyntaxError;

Source Link

Document

Create and return the Query object represented by qstr.

Usage

From source file:ch.sentric.hbase.coprocessor.ProspectiveSearchRegionObserver.java

License:Apache License

private Map<String, Query> parseQueries(final Map<String, String> queries) throws ParseException {
    QParser parser;
    final Map<String, Query> parsedQueries = new HashMap<String, Query>(0);
    final SolrQueryRequest request = new LocalSolrQueryRequest(getSolrCore(StringUtils.EMPTY),
            new HashMap<String, String[]>());

    for (final Map.Entry<String, String> entry : queries.entrySet()) {
        parser = QParser.getParser(entry.getValue(), QParserPlugin.DEFAULT_QTYPE, request);
        try {//from ww w . jav  a  2s . c o  m
            parsedQueries.put(entry.getKey(), parser.parse());
        } catch (final ParseException e) {
            LOG.warn("Failed to parse query." + e.getMessage());
        }
    }
    return parsedQueries;
}

From source file:com.github.le11.nls.solr.SolrNLSQParserPluginTest.java

License:Apache License

@Test
public void testSimple() {
    try {/*from   w  w w.j  av  a 2 s.co m*/
        SolrNLSQParserPlugin solrNLSQParserPlugin = new SolrNLSQParserPlugin();
        LocalSolrQueryRequest request = testHarness.getRequestFactory("standard", 0, 10).makeRequest("q",
                "\"people working at Google Amsterdam office\"", "debugQuery", "true");
        QParser nlsQParser = solrNLSQParserPlugin.createParser("people working at Google Amsterdam office",
                new MapSolrParams(new HashMap<String, String>()),
                new MapSolrParams(new HashMap<String, String>()), request);
        Query q = nlsQParser.parse();
        assertNotNull(q);
        System.out.println(q.toString());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getLocalizedMessage());
    }
}

From source file:com.memonews.solr.search.HighlightQParserPluginTest.java

License:Apache License

@Test
public void testHighlightQueryParser() throws Exception {
    ModifiableSolrParams local = new ModifiableSolrParams();
    ModifiableSolrParams params = new ModifiableSolrParams();
    HighlightQParserPlugin parserPlugin = new HighlightQParserPlugin();

    String qstr = "title:\"Apache Lucene\" AND solr OR name:123 NOT \"Apache Hadoop\"";
    SolrQueryRequest req = req("q", qstr);
    QParser parser = parserPlugin.createParser(qstr, local, params, req);
    Query query = parser.parse();
    assertEquals("+title:\"apache lucene\" text:solr name:123 -text:\"apache hadoop\"", query.toString());
}

From source file:com.mwired.grid.commons.commons.solr.custom.NewsDateInfluenceCustomeScoreQParsePlugin.java

@Override
public QParser createParser(String query, SolrParams sp, SolrParams sp1, SolrQueryRequest sqr) {
    return new QParser(query, sp, sp1, sqr) {
        @Override/*from  w w w .  ja v a 2s  .c  o m*/
        public Query parse() throws SyntaxError {
            QParser parser = getParser(this.qstr, "lucene", this.req);
            Query inner = parser.parse();
            SchemaField createDate = getReq().getSchema().getField(PostPropAndColMap.CREATE_DATE);
            SchemaField influence = getReq().getSchema().getField(PostPropAndColMap.INFLUENCE_SCORE);
            ValueSource influence_source = influence.getType().getValueSource(influence, parser);
            ValueSource createDate_source = createDate.getType().getValueSource(createDate, parser);

            return new NewsDateInfluenceCustomQuery(inner, new FunctionQuery(influence_source),
                    new FunctionQuery(createDate_source));
        }
    };
}

From source file:com.plugtree.solradvert.core.AdvertQueryImpl.java

License:Apache License

@Override
public void boost(String qstr) {
    logger.debug("Adding boost query: " + qstr);
    try {/*from  www.  j  a v a2 s  .c  om*/
        QParser qparser = QParser.getParser(qstr, FunctionQParserPlugin.NAME, rb.req);
        Query qq = qparser.parse();

        BooleanQuery newq = new BooleanQuery();
        newq.add(new BooleanClause(q, Occur.MUST));
        newq.add(new BooleanClause(qq, Occur.SHOULD));

        rb.setQuery(newq);
    } catch (ParseException ex) {
        logger.error("Error while adding boost query: " + ex);
    }
}

From source file:com.plugtree.solradvert.core.AdvertQueryImpl.java

License:Apache License

@Override
public void addFilter(String qstr) {
    logger.debug("Adding filter: " + qstr);
    try {//from  w w w  . j  a  v a  2s .c o m
        QParser qparser = QParser.getParser(qstr, null, rb.req);
        Query q = qparser.parse();

        List<Query> fqs = rb.getFilters();
        if (fqs == null) {
            fqs = new ArrayList<Query>();
            rb.setFilters(fqs);
        }

        fqs.add(q);
    } catch (ParseException ex) {
        logger.error("Error while adding filter query", ex);
    }
}

From source file:eu.europeana.assets.service.ir.text.bm25f.parser.BM25FQParser.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from ww  w.  ja  v a  2s  .c  om
public Query parse() throws ParseException {

    /*
     * SolrParams solrParams = localParams == null ? params : new
     * DefaultSolrParams(localParams, params);
     */

    /* Main User Query */
    String userQuery = getString();
    /* String parsedUserQuery = null; */

    /* 27/03/2012 current version of the plugin does not manage Boolean queries */
    if (userQuery.contains(" AND ") || userQuery.contains(" OR ")) {
        QParser p = new LuceneQParserPlugin().createParser(qstr, localParams, params, req);
        return p.parse();

    }

    String k1s = this.getParam("k1");
    if (k1s != null) {
        float k1 = Float.parseFloat(k1s);
        bmParams.setK1(k1);
    }

    String boostss = this.getParam("boosts");
    if (boostss != null) {
        float[] boosts = gson.fromJson(boostss, float[].class);
        bmParams.setBoosts(boosts);
    }

    String bParamss = this.getParam("b");
    if (bParamss != null) {
        float[] bParams = gson.fromJson(bParamss, float[].class);
        bmParams.setbParams(bParams);
    }

    SolrQueryParser sqp = new SolrQueryParser(req.getSchema(), bmParams.getMainField());

    Query q = sqp.parse(userQuery);

    if (q instanceof BooleanQuery) {
        List<BooleanClause> clauses = ((BooleanQuery) q).clauses();
        if (clauses.isEmpty())
            return q;
        for (BooleanClause c : clauses) {
            Set<Term> terms = new HashSet<Term>();
            c.getQuery().extractTerms(terms);
            for (Term t : terms) {
                if (!t.field().equals(bmParams.getMainField())) {
                    /* TODO manage different fields with bm25f */
                    /*
                     * if the query is on fields different from the main, we
                     * process it as a standard solr query
                     */
                    return q;
                }
            }
        }
        /*
         * if I'm here, the query is a BooleanQuery on the default field, so
         * I can use bm25f
         */

        BM25FBooleanQuery bm25fQuery;
        try {
            bm25fQuery = new BM25FBooleanQuery(userQuery, req.getSchema().getQueryAnalyzer(), bmParams);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            log.info("Error during the parsing of the BM25F-query " + userQuery);
            System.err.println("Error during the parsing of the query " + userQuery);
            /* we manage the error returning a standard solr query */
            return q;
        }
        return bm25fQuery;
    }
    if (q instanceof TermQuery) {
        TermQuery tq = (TermQuery) q;

        if (tq.getTerm().field().equals(bmParams.getMainField())) {
            try {
                return new BM25FBooleanQuery(tq.getTerm().text(), req.getSchema().getQueryAnalyzer(), bmParams);
            } catch (IOException e) {
                log.info("Error during the parsing of the BM25F-query " + userQuery);
                log.error("Error during the parsing of the query " + userQuery);
                return tq;
            }
        }
        return tq;
    }

    return q;

}

From source file:net.yacy.search.index.SingleDocumentMatcher.java

License:Open Source License

/**
 * @param query a Solr query string to parse
 * @param targetCore an open Solr index core that is the target of the query
 * @return a lucene Query instance parsed from the given Solr query string on the provided Solr core.
 * @throws SyntaxError when the query syntax is not valid
 * @throws SolrException when a query required element is missing, or when a problem occurred when accessing the target core
 *//* w  w w.  j a  va  2s .c  om*/
public static Query toLuceneQuery(final String query, final SolrCore targetCore)
        throws SyntaxError, SolrException {
    if (query == null || targetCore == null) {
        throw new IllegalArgumentException("All parameters must be non null");
    }

    final SolrQuery solrQuery = new SolrQuery(query);
    solrQuery.setParam(CommonParams.DF, CollectionSchema.text_t.getSolrFieldName());

    final SolrQueryRequestBase solrRequest = new SolrQueryRequestBase(targetCore, solrQuery) {
    };

    final LuceneQParserPlugin luceneParserPlugin = new LuceneQParserPlugin();
    final QParser solrParser = luceneParserPlugin.createParser(query, null, solrRequest.getParams(),
            solrRequest);
    return solrParser.parse();
}

From source file:org.opensextant.solrtexttagger.TaggerRequestHandler.java

License:Open Source License

/**
 * The set of documents matching the provided 'fq' (filter query). Don't include deleted docs
 * either. If null is returned, then all docs are available.
 *///from w  ww  .jav a  2  s . c  om
private Bits computeDocCorpus(SolrQueryRequest req) throws SyntaxError, IOException {
    final String[] corpusFilterQueries = req.getParams().getParams("fq");
    final SolrIndexSearcher searcher = req.getSearcher();
    final Bits docBits;
    if (corpusFilterQueries != null && corpusFilterQueries.length > 0) {
        List<Query> filterQueries = new ArrayList<Query>(corpusFilterQueries.length);
        for (String corpusFilterQuery : corpusFilterQueries) {
            QParser qParser = QParser.getParser(corpusFilterQuery, null, req);
            try {
                filterQueries.add(qParser.parse());
            } catch (SyntaxError e) {
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
            }
        }

        final DocSet docSet = searcher.getDocSet(filterQueries);//hopefully in the cache
        //note: before Solr 4.7 we could call docSet.getBits() but no longer.
        if (docSet instanceof BitDocSet) {
            docBits = ((BitDocSet) docSet).getBits();
        } else {
            docBits = new Bits() {

                @Override
                public boolean get(int index) {
                    return docSet.exists(index);
                }

                @Override
                public int length() {
                    return searcher.maxDoc();
                }
            };
        }
    } else {
        docBits = searcher.getSlowAtomicReader().getLiveDocs();
    }
    return docBits;
}