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

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

Introduction

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

Prototype

public QParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) 

Source Link

Document

Constructor for the QParser

Usage

From source file:GeonamesQParserPlugin.java

License:Apache License

public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
    return new QParser(qstr, localParams, params, req) {
        @Override// w  ww  . j  a v a  2 s .  c  om
        public Query parse() throws ParseException {
            final int rows = localParams.getInt("rows", 1);
            final int start = localParams.getInt("start", 0);
            String topo = localParams.get("topo");
            String distFunc = localParams.get("dist");
            String latFieldName = localParams.get("lat");
            String lonFieldName = localParams.get("lon");
            String ghFieldName = localParams.get("gh");
            String units = localParams.get("unit", "M");
            float boost = localParams.getFloat("boost", 1.0f);
            double radius = Constants.EARTH_RADIUS_MI;
            if (units.equalsIgnoreCase("KM")) {
                radius = Constants.EARTH_RADIUS_KM;
            }
            ValueSource vs = null, latVS = null, lonVS = null, ghVS = null;
            IndexSchema schema = req.getSchema();
            DistType distType = DistType.NORM;
            float power = 2;
            List<ValueSource> latLon = new ArrayList<ValueSource>(2);
            if (ghFieldName != null && ghFieldName.equals("") == false) {
                FieldType ft = schema.getFieldType(ghFieldName);
                SchemaField sf = schema.getField(ghFieldName);
                ghVS = ft.getValueSource(sf, this);//Should we pass this here?
                distType = DistType.GHHSIN;
            } else if (latFieldName != null && latFieldName.equals("") == false && lonFieldName != null
                    && lonFieldName.equals("") == false) {
                FieldType ftLat = schema.getFieldType(latFieldName);
                FieldType ftLon = schema.getFieldType(lonFieldName);
                SchemaField sfLat = schema.getField(latFieldName);
                SchemaField sfLon = schema.getField(lonFieldName);
                latVS = ftLat.getValueSource(sfLat, this);
                lonVS = ftLon.getValueSource(sfLon, this);
                latLon.add(latVS);
                latLon.add(lonVS);
                try {
                    power = Float.parseFloat(distFunc);
                    distType = DistType.NORM;
                } catch (NumberFormatException e) {
                    if (distFunc.equals("hsin")) {
                        distType = DistType.HSIN;
                    } else if (distFunc.equals("ghsin")) {
                        distType = DistType.GHHSIN;
                    }
                }
            } else {
                throw new ParseException("Either gh or both lat and lon must be specified.");
            }

            ToponymSearchCriteria searchCriteria = new ToponymSearchCriteria();
            searchCriteria.setQ(topo);
            searchCriteria.setMaxRows(rows);
            searchCriteria.setStartRow(start);
            Query query = null;
            try {
                ToponymSearchResult searchResult = WebService.search(searchCriteria);

                List<Toponym> topos = searchResult.getToponyms();
                if (topos.size() > 1) {
                    BooleanQuery tmp = new BooleanQuery();
                    for (Toponym toponym : topos) {
                        double lat = toponym.getLatitude();
                        double lon = toponym.getLongitude();
                        FunctionQuery fq = getFunction(distType, ghVS, power, latLon, lat, lon, radius);
                        tmp.add(fq, BooleanClause.Occur.SHOULD);
                    }
                    query = tmp;
                } else if (topos.size() == 1) {
                    Toponym curr = topos.get(0);
                    query = getFunction(distType, ghVS, power, latLon, curr.getLatitude(), curr.getLongitude(),
                            radius);
                }
            } catch (Exception e) {
                //TODO: deal with errors
            }
            query.setBoost(boost);
            return query;
        }

    };
}

From source file:CartesianTierQParserPlugin.java

License:Apache License

public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
    return new QParser(qstr, localParams, params, req) {

        public Query parse() throws ParseException {
            final Double x = localParams.getDouble("x");
            final Double y = localParams.getDouble("y");

            final String fieldPrefix = localParams.get("prefix", tierPrefix);
            final Double distance = localParams.getDouble("dist");
            //GSI: kind of funky passing in an empty string, but AFAICT, it is safe b/c we don't want to assume tier prefix stuff
            CartesianPolyFilterBuilder cpfb = new CartesianPolyFilterBuilder(fieldPrefix);
            //Get the box based on this point and our distance
            final Shape shape = cpfb.getBoxShape(x, y, distance);
            final List<Double> boxIds = shape.getArea();

            //Sort them, so they are in order, which will be faster for termdocs in the tier filter
            Collections.sort(boxIds);
            //Get the field type so we can properly encode the data
            IndexSchema schema = req.getSchema();
            FieldType ft = schema.getFieldTypeNoEx(shape.getTierId());

            //Create the Filter and wrap it in a constant score query
            Filter filter = new TierFilter(shape.getTierId(), ft, boxIds);
            return new SolrConstantScoreQuery(filter);
        }//from   w ww  . j  a va  2 s  .c o m
    };
}

From source file:alba.solr.core.DynamicQueryParser.java

License:Apache License

@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {

    postFilters = (Map<String, CallableFunction>) req.getContext().get(Loader.POSTFILTERS);

    cachedResults = (Map<Object, CachedResult>) req.getContext().get(Loader.CACHEDRESULTS);

    CallableFunction function = postFilters.get(localParams.get("name"));

    return new QParser(qstr, localParams, params, req) {

        private ValueSource functionParamValueSource;

        @Override/*  w  w w  . j a va 2  s  .  c o m*/
        public Query parse() throws SyntaxError {

            ValueSource vs = null;

            Map<String, Object> params = new HashMap<String, Object>();

            String funcStr = localParams.get(QueryParsing.V, null);

            int nParams = 1;

            if ((function != null) && (function.getMethod() != null)) {
                nParams = function.getMethod().getParameterCount();
            }

            boolean cache = false;

            Object functionParams[] = new Object[nParams];

            int i = 1; //in the 0th positions there's the parametric function result (as ValueSource)
            Iterator<String> it = localParams.getParameterNamesIterator();
            while (it.hasNext()) {
                String p = it.next();

                /* does it make sense to be able to switch on/off the cache? what would it imply? 
                if ("cache".equals(p)) {
                   cache = ("1".equals(localParams.get(p)));
                }
                */

                if (!"v".equals(p) && !"cache".equals(p) && !"type".equals(p) && !"name".equals(p)) {
                    params.put(p, localParams.get(p));

                    Class<?> expectedType = function.getMethod().getParameters()[i].getType();
                    if (expectedType == Integer.class) {
                        functionParams[i] = Integer.parseInt(localParams.get(p));
                    } else {
                        logger.error("param " + i + " should be of type " + expectedType
                                + " but I don't know how to parse it.");
                        // right place for magic params? like passing the request & so on.. ?
                    }

                    i++;
                }
            }

            if ((funcStr != null) && (funcStr != "")) {
                Query funcQ = subQuery(funcStr, FunctionQParserPlugin.NAME).getQuery();

                //if (funcQ instanceof FunctionQuery) {  //what else could be?
                vs = ((FunctionQuery) funcQ).getValueSource();
                functionParamValueSource = vs; //todo must call getValues when using it!

            } else {
                logger.error("!!!! no function defined for the postfilter???");
            }

            DynamicQuery dq = new DynamicQuery(vs, cache, function, functionParams, cachedResults);

            dq.setParams(params);

            return dq;
        }
    };
}

From source file:com.alipay.tiansuan.solrplugin.SelectInLocalFileQParserPlugin.java

License:Apache License

@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
    return new QParser(qstr, localParams, params, req) {
        @Override/*from w  w w. j a  v  a  2s . c o  m*/
        public Query parse() throws ParseException {
            try {
                String file = localParams.get(QueryParsing.V);
                String field = localParams.get(QueryParsing.F);

                SchemaField sf = req.getSchema().getField(field);
                FieldType ft = sf.getType();
                if (ft instanceof StrField) {
                    return new StringSelectInQuery<String>(file, field, new HdfsToSet.TransString());
                }
                if (ft instanceof TrieField) {
                    TrieField tft = (TrieField) ft;
                    TrieTypes cdt = tft.getType();
                    if (cdt.equals(TrieTypes.INTEGER)) {
                        return new NumericSelectInQuery<Integer>(field, tft.getPrecisionStep(), DataType.INT,
                                new HdfsToSet.TransInt(), file);
                    }
                    if (cdt.equals(TrieTypes.LONG)) {
                        return new NumericSelectInQuery<Long>(field, tft.getPrecisionStep(), DataType.LONG,
                                new HdfsToSet.TransLong(), file);
                    }

                    if (cdt.equals(TrieTypes.FLOAT)) {
                        return new NumericSelectInQuery<Float>(field, tft.getPrecisionStep(), DataType.FLOAT,
                                new HdfsToSet.TransFloat(), file);
                    }

                    if (cdt.equals(TrieTypes.DOUBLE)) {
                        return new NumericSelectInQuery<Double>(field, tft.getPrecisionStep(), DataType.DOUBLE,
                                new HdfsToSet.TransDouble(), file);
                    }

                    if (cdt.equals(TrieTypes.DATE)) {
                        return new NumericSelectInQuery<Long>(field, tft.getPrecisionStep(), DataType.LONG,
                                new HdfsToSet.TransDate(), file);
                    }
                }

                throw new ParseException("file type error");

            } catch (Exception e) {
                throw new ParseException(e.toString());
            }
        }
    };
}

From source file:com.alipay.tiansuan.solrplugin.StringCotainsQParserPlugin.java

License:Apache License

@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
    return new QParser(qstr, localParams, params, req) {
        @Override/*w w w.  j  ava  2 s.  c  om*/
        public Query parse() throws ParseException {
            try {
                String contains = localParams.get(QueryParsing.V);
                String field = localParams.get(QueryParsing.F);
                return new StringContainsQuery(contains.split(","), field);

            } catch (Exception e) {
                throw new ParseException(e.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//  w  w  w.  ja  va 2 s  . 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:fr.gael.dhus.search.plugins.DocAccessControl.java

License:Open Source License

@Override
public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
    SolrParams solrParams = SolrParams.wrapDefaults(localParams, params);
    final Long userId = Long.valueOf(solrParams.get(SolrUtils.CURRENT_USER_ID, "-1"));
    return new QParser(qstr, localParams, params, req) {
        @Override/*from w  w w.j  av a 2 s  . c om*/
        public Query parse() throws SyntaxError {
            return new DocAccess(userId);
        }
    };
}