Example usage for org.apache.solr.search SyntaxError SyntaxError

List of usage examples for org.apache.solr.search SyntaxError SyntaxError

Introduction

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

Prototype

public SyntaxError(Throwable cause) 

Source Link

Usage

From source file:com.gogobot.DistanceParser.java

License:Apache License

@Override
public ValueSource parse(FunctionQParser fp) throws SyntaxError {
    // TODO: dispatch through SpatialQueryable in the future?

    //note: parseValueSourceList can't handle a field reference to an AbstractSpatialFieldType,
    // so those fields are expressly handled via sfield=
    List<ValueSource> sources = fp.parseValueSourceList();

    // "m" is a multi-value source, "x" is a single-value source
    // allow (m,m) (m,x,x) (x,x,m) (x,x,x,x)
    // if not enough points are present, "pt" will be checked first, followed by "sfield".

    MultiValueSource mv1 = null;/*from  w ww.  j  av  a 2 s  . c o m*/
    MultiValueSource mv2 = null;

    if (sources.size() == 0) {
        // nothing to do now
    } else if (sources.size() == 1) {
        ValueSource vs = sources.get(0);
        if (!(vs instanceof MultiValueSource)) {
            throw new SyntaxError("geodist - invalid parameters:" + sources);
        }
        mv1 = (MultiValueSource) vs;
    } else if (sources.size() == 2) {
        ValueSource vs1 = sources.get(0);
        ValueSource vs2 = sources.get(1);

        if (vs1 instanceof MultiValueSource && vs2 instanceof MultiValueSource) {
            mv1 = (MultiValueSource) vs1;
            mv2 = (MultiValueSource) vs2;
        } else {
            mv1 = makeMV(sources, sources);
        }
    } else if (sources.size() == 3) {
        ValueSource vs1 = sources.get(0);
        ValueSource vs2 = sources.get(1);
        if (vs1 instanceof MultiValueSource) { // (m,x,x)
            mv1 = (MultiValueSource) vs1;
            mv2 = makeMV(sources.subList(1, 3), sources);
        } else { // (x,x,m)
            mv1 = makeMV(sources.subList(0, 2), sources);
            vs1 = sources.get(2);
            if (!(vs1 instanceof MultiValueSource)) {
                throw new SyntaxError("geodist - invalid parameters:" + sources);
            }
            mv2 = (MultiValueSource) vs1;
        }
    } else if (sources.size() == 4) {
        mv1 = makeMV(sources.subList(0, 2), sources);
        mv2 = makeMV(sources.subList(2, 4), sources);
    } else if (sources.size() > 4) {
        throw new SyntaxError("geodist - invalid parameters:" + sources);
    }

    if (mv1 == null) {
        mv1 = parsePoint(fp);
        mv2 = parseSfield(fp);
    } else if (mv2 == null) {
        mv2 = parsePoint(fp);
        if (mv2 == null)
            mv2 = parseSfield(fp);
    }

    if (mv1 == null || mv2 == null) {
        throw new SyntaxError("geodist - not enough parameters:" + sources);
    }

    // We have all the parameters at this point, now check if one of the points is constant
    double[] constants;//latLon
    constants = getConstants(mv1);
    MultiValueSource other = mv2;
    if (constants == null) {
        constants = getConstants(mv2);
        other = mv1;
    }

    // At this point we dispatch to one of:
    // * SpatialStrategy.makeDistanceValueSource
    // * HaversineConstFunction
    // * HaversineFunction

    // sfield can only be in mv2, according to the logic above
    if (mv2 instanceof SpatialStrategyMultiValueSource) {
        if (constants == null)
            throw new SyntaxError("When using AbstractSpatialFieldType (e.g. RPT not LatLonType),"
                    + " the point must be supplied as constants");
        // note: uses Haversine by default but can be changed via distCalc=...
        SpatialStrategy strategy = ((SpatialStrategyMultiValueSource) mv2).strategy;
        Point queryPoint = strategy.getSpatialContext().makePoint(constants[1], constants[0]);
        //TODO Spatial4j 0.4 will have a direct constant
        double multiplier = DistanceUtils.degrees2Dist(1, DistanceUtils.EARTH_MEAN_RADIUS_KM);
        return strategy.makeDistanceValueSource(queryPoint, multiplier);
    }

    if (constants != null && other instanceof VectorValueSource) {
        return new GogobotHaversineConstFunction(constants[0], constants[1], (VectorValueSource) other);
    }

    return new HaversineFunction(mv1, mv2, DistanceUtils.EARTH_MEAN_RADIUS_KM, true);
}

From source file:com.gogobot.DistanceParser.java

License:Apache License

/** make a MultiValueSource from two non MultiValueSources */
private VectorValueSource makeMV(List<ValueSource> sources, List<ValueSource> orig) throws SyntaxError {
    ValueSource vs1 = sources.get(0);//w  ww  . ja  v a 2 s .  co m
    ValueSource vs2 = sources.get(1);

    if (vs1 instanceof MultiValueSource || vs2 instanceof MultiValueSource) {
        throw new SyntaxError("geodist - invalid parameters:" + orig);
    }
    return new VectorValueSource(sources);
}

From source file:com.gogobot.DistanceParser.java

License:Apache License

private MultiValueSource parsePoint(FunctionQParser fp) throws SyntaxError {
    String pt = fp.getParam(SpatialParams.POINT);
    if (pt == null)
        return null;
    double[] point = null;
    try {//ww  w.jav  a2  s .  co m
        point = ParseUtils.parseLatitudeLongitude(pt);
    } catch (InvalidShapeException e) {
        throw new SyntaxError("Bad spatial pt:" + pt);
    }
    return new VectorValueSource(Arrays.<ValueSource>asList(new DoubleConstValueSource(point[0]),
            new DoubleConstValueSource(point[1])));
}

From source file:com.gogobot.DistanceParser.java

License:Apache License

private MultiValueSource parseSfield(FunctionQParser fp) throws SyntaxError {
    String sfield = fp.getParam(SpatialParams.FIELD);
    if (sfield == null)
        return null;
    SchemaField sf = fp.getReq().getSchema().getField(sfield);
    FieldType type = sf.getType();//from w  ww. ja v  a  2 s . c om
    if (type instanceof AbstractSpatialFieldType) {
        AbstractSpatialFieldType asft = (AbstractSpatialFieldType) type;
        return new SpatialStrategyMultiValueSource(asft.getStrategy(sfield));
    }
    ValueSource vs = type.getValueSource(sf, fp);
    if (vs instanceof MultiValueSource) {
        return (MultiValueSource) vs;
    }
    throw new SyntaxError(
            "Spatial field must implement MultiValueSource or extend AbstractSpatialFieldType:" + sf);
}

From source file:com.ifactory.press.db.solr.search.ScoringParentQParser.java

License:Apache License

@Override
public Query parse() throws SyntaxError {
    if (localParams == null) {
        throw new SyntaxError("join query parser must be invoked using localParams");
    }/*w w  w . java  2s  .  co  m*/
    String filter = localParams.get(getParentFilterLocalParamName());
    QParser parentParser = subQuery(filter, null);
    Query parentQ = parentParser.getQuery();

    String queryText = localParams.get(QueryParsing.V);
    // there is no child query, return parent filter from cache
    if (queryText == null || queryText.length() == 0) {
        SolrConstantScoreQuery wrapped = new SolrConstantScoreQuery(getFilter(parentQ));
        wrapped.setCache(false);
        return wrapped;
    }
    QParser childrenParser = subQuery(queryText, null);
    Query childrenQuery = childrenParser.getQuery();
    return createQuery(parentQ, childrenQuery);
}

From source file:com.indoqa.solr.spatial.corridor.query.route.LineStringUtils.java

License:Apache License

@SuppressWarnings("unchecked")
public static LineString parse(String corridorLineString, SolrIndexSearcher indexSearcher) throws SyntaxError {
    if (corridorLineString == null) {
        throw new SyntaxError("Parameter corridor.route must be set and a valid LineString!");
    }//  w  w  w.j  ava2s.com

    SolrCache<String, LineString> lineStringCache = indexSearcher.getCache("corridorLineStrings");

    LineString lineString = lineStringCache.get(corridorLineString);

    if (lineString == null) {
        lineString = parseWkt(corridorLineString);
        lineStringCache.put(corridorLineString, lineString);
    }

    return lineString;
}

From source file:com.indoqa.solr.spatial.corridor.query.route.LineStringUtils.java

License:Apache License

private static LineString parseWkt(String corridorLineString) throws SyntaxError {
    try {/*from   www  .jav a2 s  .  c o  m*/
        return (LineString) wktReader.read(corridorLineString);
    } catch (ParseException e) {
        throw new SyntaxError("corridor.route is no valid WKT LineString!");
    }
}

From source file:com.sindicetech.siren.solr.qparser.SirenQParser.java

License:Open Source License

/**
 * Uses {@link SolrPluginUtils#parseFieldBoosts(String)} with the 'qf'
 * parameter. Falls back to the 'df' parameter or
 * {@link org.apache.solr.schema.IndexSchema#getDefaultSearchFieldName()}.
 *//*w w w .j av a  2  s . co  m*/
public static Map<String, Float> parseQueryFields(final IndexSchema indexSchema, final SolrParams solrParams)
        throws SyntaxError {
    final Map<String, Float> queryFields = SolrPluginUtils
            .parseFieldBoosts(solrParams.getParams(SirenParams.QF));
    if (queryFields.isEmpty()) {
        final String df = QueryParsing.getDefaultField(indexSchema, solrParams.get(CommonParams.DF));
        if (df == null) {
            throw new SyntaxError("Neither " + SirenParams.QF + ", " + CommonParams.DF
                    + ", nor the default search field are present.");
        }
        queryFields.put(df, 1.0f);
    }
    checkFieldTypes(indexSchema, queryFields);
    return queryFields;
}

From source file:com.wiseowl.WiseOwl.query.WiseOwlQParser.java

License:Apache License

@Override
public Query parse() throws SyntaxError {

    //<start id="qqp.parse"/>
    Parse parse = ParserTool.parseLine(qstr, parser, 1)[0];//<co id="qqp.parseLine"/>
    /*/*from   w w w.  j ava2s .co m*/
    <calloutlist>
        <callout arearefs="qqp.parseLine"><para>Parse the question using the <classname>TreebankParser</classname>.  The resulting <classname>Parse</classname> object can then be utilized by the classifier to determine the Answer Type.</para></callout>
    </calloutlist>
    */
    //<end id="qqp.parse"/>
    //<start id="qqp.answerType"/>
    // String type = "P";
    String type = atc.computeAnswerType(parse);
    String mt = atm.get(type);
    if (mt.equals("DESCRIPTION")) {
        BooleanQuery bq;
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        //BooleanQuery bq=new BooleanQuery(false, 0);
        String field = "text";
        SchemaField sf = req.getSchema().getFieldOrNull(field);
        try {
            Analyzer analyzer = sf.getType().getQueryAnalyzer();
            TokenStream ts = analyzer.tokenStream(field, new StringReader(qstr));
            ts.reset();
            CharTermAttribute tok = null;
            while (ts.incrementToken()) {//<co id="qqp.addTerms"/>
                tok = ts.getAttribute(CharTermAttribute.class);
                String term = tok.toString();
                //ts.reset();
                //log.warn("terms {} ",term);
                builder.add(new TermQuery(new Term(field, term)), BooleanClause.Occur.SHOULD);
            }
            ts.close();
        } catch (IOException e) {
            throw new SyntaxError(e.getLocalizedMessage());
        }
        bq = builder.build();
        return bq;
        //return new TermQuery(new Term("title", "she"));

    } else {
        //<end id="qqp.answerType"/>
        String field = "text";
        //params.get(QUERY_FIELD);
        //String field="text";
        SchemaField sp = req.getSchema().getFieldOrNull(field);
        if (sp == null) {
            throw new SolrException(ErrorCode.SERVER_ERROR, "Undefined field: " + field);
        }
        //<start id="qqp.query"/>
        List<SpanQuery> sql = new ArrayList<SpanQuery>();
        if (mt != null) {//<co id="qqp.handleAT"/>
            String[] parts = mt.split("\\|");
            if (parts.length == 1) {
                sql.add(new SpanTermQuery(new Term(field, mt.toLowerCase())));
            } else {
                for (int pi = 0; pi < parts.length; pi++) {
                    sql.add(new SpanTermQuery(new Term(field, parts[pi].toLowerCase())));
                }
            }
        }
        log.warn("answer type mt : {} {} ", mt, type);
        FocusNoun fn = new FocusNoun();
        String fnn[] = null;
        try {
            fnn = fn.getFocusNoun(qstr);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            Analyzer analyzer = sp.getType().getQueryAnalyzer();
            TokenStream ts = analyzer.tokenStream(field, new StringReader(qstr));
            ts.reset();
            CharTermAttribute tok = null;

            while (ts.incrementToken()) {//<co id="qqp.addTerms"/>
                tok = ts.getAttribute(CharTermAttribute.class);
                String term = tok.toString();
                log.warn("terms boosted {} ", term);
                if (fnn != null)
                    if (term.equals(fnn[0]) || term.equals(fnn[1])) {
                        SpanQuery sq = new SpanTermQuery(new Term(field, term));
                        sql.add(new SpanBoostQuery(sq, 100f));
                    } else {
                        SpanQuery sq = new SpanTermQuery(new Term(field, term));
                        sql.add(new SpanBoostQuery(sq, 5f));
                    }

                // sql.add(new SpanTermQuery(new Term(field, term)));
            }
            ts.close();
        } catch (IOException e) {
            throw new SyntaxError(e.getLocalizedMessage());
        }
        return new SpanOrQuery(sql.toArray(new SpanQuery[sql.size()]));
        // return new SpanNearQuery(sql.toArray(new SpanQuery[sql.size()]), params.getInt(OWLParams.SLOP, 10), true);//<co id="qqp.spanNear"/>
        /*
        <calloutlist>
            <callout arearefs="qqp.handleAT"><para>Add the AnswerType to the query</para></callout>
            <callout arearefs="qqp.addTerms"><para>Add the original query terms to the query</para></callout>
            <callout arearefs="qqp.spanNear"><para>Query the index looking for all of the parts near each other</para></callout>
        </calloutlist>
        */
        //<end id="qqp.query"/>

    }
}

From source file:edu.cmu.lti.oaqa.annographix.solr.StructQueryParseVer3.java

License:Apache License

/**
 * // ww  w.ja  va 2 s.  c o m
 * The constructor parses queries.
 * 
 * @param     query a query to parse
 * @throws    SyntaxError
 */
public StructQueryParseVer3(String query) throws SyntaxError {
    /*
     *  All white-spaces should become spaces
     *  TODO: can this replacement be problematic, i.e., 
     *        are there any languages/locales
     *        where white-spaces are valuable, 
     *        i.e., we want to keep them 
     *        rather than replacing by regular spaces?
     */
    query = query.replaceAll("\\s+", " ");
    ArrayList<String> allConstr = new ArrayList<String>();
    for (String tok : query.trim().split("\\s+")) {
        if (tok.charAt(0) == PREFIX_OP) {
            // we will process all the constraints after we are done with lexical entries
            allConstr.add(tok);
        } else {
            // a text/annotation field
            FieldType type = FieldType.FIELD_TEXT;
            LexicalEntryParse e = null;
            if (tok.startsWith(PREFIX_TEXT)) {
                e = procLexicalEntry(PREFIX_TEXT, tok);
            } else if (tok.startsWith(PREFIX_ANNOT)) {
                type = FieldType.FIELD_ANNOTATION;
                e = procLexicalEntry(PREFIX_ANNOT, tok);
            } else {
                throw new SyntaxError(String.format("Bad token '%s', should start with %c, %s, or %s", tok,
                        PREFIX_OP, PREFIX_TEXT, PREFIX_ANNOT));
            }
            addOneElement(e, type);
        }
    }

    for (int i = 0; i < mTokens.size(); ++i)
        mEdges.put(i, new ArrayList<Integer>());

    /*
     * Now all lexical entries are added (and we fully established
     * the mappings from text/annotation labels to IDs). Thus, we can process
     * constraints.
     */
    for (String tok : allConstr)
        addConstraint(tok);

    /*
     *  Finally, let's compute a number of edges with which 
     *  each node is connected via the query graph and assign
     *  unique IDs to connected subgraphs.
     */
    compConnectInfo();

}