Example usage for org.apache.lucene.spatial SpatialStrategy getSpatialContext

List of usage examples for org.apache.lucene.spatial SpatialStrategy getSpatialContext

Introduction

In this page you can find the example usage for org.apache.lucene.spatial SpatialStrategy getSpatialContext.

Prototype

public SpatialContext getSpatialContext() 

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 www. ja  va2 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:org.apache.solr.response.transform.GeoTransformerFactory.java

License:Apache License

@Override
public DocTransformer create(String display, SolrParams params, SolrQueryRequest req) {

    String fname = params.get("f", display);
    if (fname.startsWith("[") && fname.endsWith("]")) {
        fname = display.substring(1, display.length() - 1);
    }/*ww w .  jav a  2  s. c o  m*/
    SchemaField sf = req.getSchema().getFieldOrNull(fname);
    if (sf == null) {
        throw new SolrException(ErrorCode.BAD_REQUEST,
                this.getClass().getSimpleName() + " using unknown field: " + fname);
    }
    if (!(sf.getType() instanceof AbstractSpatialFieldType)) {
        throw new SolrException(ErrorCode.BAD_REQUEST, "GeoTransformer requested non-spatial field: " + fname
                + " (" + sf.getType().getClass().getSimpleName() + ")");
    }

    final GeoFieldUpdater updater = new GeoFieldUpdater();
    updater.field = fname;
    updater.display = display;
    updater.display_error = display + "_error";

    ValueSource shapes = null;
    AbstractSpatialFieldType<?> sdv = (AbstractSpatialFieldType<?>) sf.getType();
    SpatialStrategy strategy = sdv.getStrategy(fname);
    if (strategy instanceof CompositeSpatialStrategy) {
        shapes = ((CompositeSpatialStrategy) strategy).getGeometryStrategy().makeShapeValueSource();
    } else if (strategy instanceof SerializedDVStrategy) {
        shapes = ((SerializedDVStrategy) strategy).makeShapeValueSource();
    }

    String writerName = params.get("w", "GeoJSON");
    updater.formats = strategy.getSpatialContext().getFormats();
    updater.writer = updater.formats.getWriter(writerName);
    if (updater.writer == null) {
        StringBuilder str = new StringBuilder();
        str.append("Unknown Spatial Writer: ").append(writerName);
        str.append(" [");
        for (ShapeWriter w : updater.formats.getWriters()) {
            str.append(w.getFormatName()).append(' ');
        }
        str.append("]");
        throw new SolrException(ErrorCode.BAD_REQUEST, str.toString());
    }

    QueryResponseWriter qw = req.getCore().getQueryResponseWriter(req);
    updater.isJSON = (qw.getClass() == JSONResponseWriter.class) && (updater.writer instanceof GeoJSONWriter);

    // Using ValueSource
    if (shapes != null) {
        // we don't really need the qparser... just so we can reuse valueSource
        QParser parser = new QParser(null, null, params, req) {
            @Override
            public Query parse() throws SyntaxError {
                return new MatchAllDocsQuery();
            }
        };

        return new ValueSourceAugmenter(display, parser, shapes) {
            @Override
            protected void setValue(SolrDocument doc, Object val) {
                updater.setValue(doc, val);
            }
        };
    }

    // Using the raw stored values
    return new DocTransformer() {

        @Override
        public void transform(SolrDocument doc, int docid, float score) throws IOException {
            Object val = doc.remove(updater.field);
            if (val != null) {
                updater.setValue(doc, val);
            }
        }

        @Override
        public String getName() {
            return updater.display;
        }

        @Override
        public String[] getExtraRequestFields() {
            return new String[] { updater.field };
        }
    };
}

From source file:org.apache.solr.search.function.distance.GeoDistValueSourceParser.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  a  va 2s. co 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 HaversineConstFunction(constants[0], constants[1], (VectorValueSource) other);
    }

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

From source file:org.eclipse.rdf4j.sail.lucene.LuceneDocument.java

License:Open Source License

@Override
public void addGeoProperty(String field, String value) {
    LuceneIndex.addStoredOnlyPredicateField(field, value, doc);
    try {/*from  w  ww .  j a v a2 s.  c  o m*/
        SpatialStrategy geoStrategy = geoStrategyMapper.apply(field);
        Shape shape = geoStrategy.getSpatialContext().readShapeFromWkt(value);
        for (IndexableField f : geoStrategy.createIndexableFields(shape)) {
            doc.add(f);
        }
    } catch (ParseException e) {
        // ignore
    }
}

From source file:org.eclipse.rdf4j.sail.lucene.LuceneIndex.java

License:Open Source License

@Override
protected Iterable<? extends DocumentDistance> geoQuery(final URI geoProperty, Point p, final URI units,
        double distance, String distanceVar, Var contextVar) throws MalformedQueryException, IOException {
    double degs = GeoUnits.toDegrees(distance, units);
    final String geoField = SearchFields.getPropertyField(geoProperty);
    SpatialStrategy strategy = getSpatialStrategyMapper().apply(geoField);
    final Shape boundingCircle = strategy.getSpatialContext().makeCircle(p, degs);
    Query q = strategy.makeQuery(new SpatialArgs(SpatialOperation.Intersects, boundingCircle));
    if (contextVar != null) {
        q = addContextTerm(q, (Resource) contextVar.getValue());
    }//  w w  w.j a  v a2s . c om

    TopDocs docs = search(
            new CustomScoreQuery(q, new FunctionQuery(strategy.makeRecipDistanceValueSource(boundingCircle))));
    final boolean requireContext = (contextVar != null && !contextVar.hasValue());
    return Iterables.transform(Arrays.asList(docs.scoreDocs), new Function<ScoreDoc, DocumentDistance>() {

        @Override
        public DocumentDistance apply(ScoreDoc doc) {
            return new LuceneDocumentDistance(doc, geoField, units, boundingCircle.getCenter(), requireContext,
                    LuceneIndex.this);
        }
    });
}