org.apache.lucene.spatial.SpatialStrategy Java Examples

The following examples show how to use org.apache.lucene.spatial.SpatialStrategy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LuceneIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected Iterable<? extends DocumentDistance> geoQuery(final IRI geoProperty, Point p, final IRI 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().getShapeFactory().circle(p, degs);
	Query q = strategy.makeQuery(new SpatialArgs(SpatialOperation.Intersects, boundingCircle));
	if (contextVar != null) {
		q = addContextTerm(q, (Resource) contextVar.getValue());
	}

	TopDocs docs = search(new FunctionScoreQuery(q, 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);
		}
	});
}
 
Example #2
Source File: SpatialDocMaker.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a SpatialStrategy from configuration options.
 */
protected SpatialStrategy makeSpatialStrategy(final Config config) {
  //A Map view of Config that prefixes keys with "spatial."
  Map<String, String> configMap = new AbstractMap<String, String>() {
    @Override
    public Set<Entry<String, String>> entrySet() {
      throw new UnsupportedOperationException();
    }

    @Override
    public String get(Object key) {
      return config.get("spatial." + key, null);
    }
  };

  SpatialContext ctx = SpatialContextFactory.makeSpatialContext(configMap, null);

  return makeSpatialStrategy(config, configMap, ctx);
}
 
Example #3
Source File: LuceneDocument.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public LuceneDocument(String id, String resourceId, String context,
		Function<? super String, ? extends SpatialStrategy> geoStrategyMapper) {
	this(geoStrategyMapper);
	setId(id);
	setResource(resourceId);
	setContext(context);
}
 
Example #4
Source File: LuceneDocument.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void addGeoProperty(String field, String value) {
	LuceneIndex.addStoredOnlyPredicateField(field, value, doc);
	try {
		SpatialStrategy geoStrategy = geoStrategyMapper.apply(field);
		Shape shape = geoStrategy.getSpatialContext().readShapeFromWkt(value);
		for (IndexableField f : geoStrategy.createIndexableFields(shape)) {
			doc.add(f);
		}
	} catch (ParseException e) {
		// ignore
	}
}
 
Example #5
Source File: LuceneIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected Function<String, ? extends SpatialStrategy> createSpatialStrategyMapper(Map<String, String> parameters) {
	ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
	SpatialContext geoContext = SpatialContextFactory.makeSpatialContext(parameters, classLoader);
	final SpatialPrefixTree spt = SpatialPrefixTreeFactory.makeSPT(parameters, classLoader, geoContext);
	return new Function<String, SpatialStrategy>() {

		@Override
		public SpatialStrategy apply(String field) {
			return new RecursivePrefixTreeStrategy(spt, GEO_FIELD_PREFIX + field);
		}

	};
}
 
Example #6
Source File: LuceneIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Iterable<? extends DocumentResult> geoRelationQuery(String relation, IRI geoProperty, Shape shape,
		Var contextVar) throws MalformedQueryException, IOException {
	SpatialOperation op = toSpatialOp(relation);
	if (op == null) {
		return null;
	}

	final String geoField = SearchFields.getPropertyField(geoProperty);
	SpatialStrategy strategy = getSpatialStrategyMapper().apply(geoField);
	Query q = strategy.makeQuery(new SpatialArgs(op, shape));
	if (contextVar != null) {
		q = addContextTerm(q, (Resource) contextVar.getValue());
	}

	TopDocs docs = search(q);
	final Set<String> fields = Sets.newHashSet(SearchFields.URI_FIELD_NAME, geoField);
	if (contextVar != null && !contextVar.hasValue()) {
		fields.add(SearchFields.CONTEXT_FIELD_NAME);
	}
	return Iterables.transform(Arrays.asList(docs.scoreDocs), new Function<ScoreDoc, DocumentResult>() {

		@Override
		public DocumentResult apply(ScoreDoc doc) {
			return new LuceneDocumentResult(doc, LuceneIndex.this, fields);
		}
	});
}
 
Example #7
Source File: SpatialDocMaker.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Looks up the SpatialStrategy from the given round --
 * {@link org.apache.lucene.benchmark.byTask.utils.Config#getRoundNumber()}. It's an error
 * if it wasn't created already for this round -- when SpatialDocMaker is initialized.
 */
public static SpatialStrategy getSpatialStrategy(int roundNumber) {
  SpatialStrategy result = spatialStrategyCache.get(roundNumber);
  if (result == null) {
    throw new IllegalStateException("Strategy should have been init'ed by SpatialDocMaker by now");
  }
  return result;
}
 
Example #8
Source File: SpatialDocMaker.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected SpatialStrategy makeSpatialStrategy(final Config config, Map<String, String> configMap,
                                              SpatialContext ctx) {
  //TODO once strategies have factories, we could use them here.
  final String strategyName = config.get("spatial.strategy", "rpt");
  switch (strategyName) {
    case "rpt": return makeRPTStrategy(SPATIAL_FIELD, config, configMap, ctx);
    case "composite": return makeCompositeStrategy(config, configMap, ctx);
    //TODO add more as-needed
    default: throw new IllegalStateException("Unknown spatial.strategy: " + strategyName);
  }
}
 
Example #9
Source File: SpatialDocMaker.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected SpatialStrategy makeCompositeStrategy(Config config, Map<String, String> configMap, SpatialContext ctx) {
  final CompositeSpatialStrategy strategy = new CompositeSpatialStrategy(
      SPATIAL_FIELD, makeRPTStrategy(SPATIAL_FIELD + "_rpt", config, configMap, ctx),
      makeSerializedDVStrategy(SPATIAL_FIELD + "_sdv", config, configMap, ctx)
  );
  strategy.setOptimizePredicates(config.get("query.spatial.composite.optimizePredicates", true));
  return strategy;
}
 
Example #10
Source File: SpatialDocMaker.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void setConfig(Config config, ContentSource source) {
  super.setConfig(config, source);
  SpatialStrategy existing = spatialStrategyCache.get(config.getRoundNumber());
  if (existing == null) {
    //new round; we need to re-initialize
    strategy = makeSpatialStrategy(config);
    spatialStrategyCache.put(config.getRoundNumber(), strategy);
    //TODO remove previous round config?
    shapeConverter = makeShapeConverter(strategy, config, "doc.spatial.");
    System.out.println("Spatial Strategy: " + strategy);
  }
}
 
Example #11
Source File: SpatialDocMaker.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Optionally converts points to circles, and optionally bbox'es result.
 */
public static ShapeConverter makeShapeConverter(final SpatialStrategy spatialStrategy,
                                                Config config, String configKeyPrefix) {
  //by default does no conversion
  final double radiusDegrees = config.get(configKeyPrefix+"radiusDegrees", 0.0);
  final double plusMinus = config.get(configKeyPrefix+"radiusDegreesRandPlusMinus", 0.0);
  final boolean bbox = config.get(configKeyPrefix + "bbox", false);

  return new ShapeConverter() {
    @Override
    public Shape convert(Shape shape) {
      if (shape instanceof Point && (radiusDegrees != 0.0 || plusMinus != 0.0)) {
        Point point = (Point)shape;
        double radius = radiusDegrees;
        if (plusMinus > 0.0) {
          Random random = new Random(point.hashCode());//use hashCode so it's reproducibly random
          radius += random.nextDouble() * 2 * plusMinus - plusMinus;
          radius = Math.abs(radius);//can happen if configured plusMinus > radiusDegrees
        }
        shape = spatialStrategy.getSpatialContext().makeCircle(point, radius);
      }
      if (bbox)
        shape = shape.getBoundingBox();
      return shape;
    }
  };
}
 
Example #12
Source File: SpatialDocMaker.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static Shape makeShapeFromString(SpatialStrategy strategy, String name, String shapeStr) {
  if (shapeStr != null && shapeStr.length() > 0) {
    try {
      return strategy.getSpatialContext().readShapeFromWkt(shapeStr);
    } catch (Exception e) {//InvalidShapeException TODO
      System.err.println("Shape "+name+" wasn't parseable: "+e+"  (skipping it)");
      return null;
    }
  }
  return null;
}
 
Example #13
Source File: LatLonPointSpatialField.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
protected SpatialStrategy newSpatialStrategy(String fieldName) {
  SchemaField schemaField = schema.getField(fieldName); // TODO change AbstractSpatialFieldType so we get schemaField?
  return new LatLonPointSpatialStrategy(ctx, fieldName, schemaField.indexed(), schemaField.hasDocValues());
}
 
Example #14
Source File: LuceneDocument.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public LuceneDocument(Function<? super String, ? extends SpatialStrategy> geoStrategyMapper) {
	this(new Document(), geoStrategyMapper);
}
 
Example #15
Source File: GeoDistValueSourceParser.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"unchecked"})
public SpatialStrategyMultiValueSource(SpatialStrategy strategy, DistanceUnits distanceUnits) {
  super(Collections.EMPTY_LIST);
  this.strategy = strategy;
  this.distanceUnits = distanceUnits;
}
 
Example #16
Source File: LuceneIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Function<? super String, ? extends SpatialStrategy> getSpatialStrategyMapper() {
	return geoStrategyMapper;
}
 
Example #17
Source File: LuceneDocument.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public LuceneDocument(Document doc, Function<? super String, ? extends SpatialStrategy> geoStrategyMapper) {
	this.doc = doc;
	this.geoStrategyMapper = geoStrategyMapper;
}