org.geotools.data.Query类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(17.6k)|赞(0)|评价(0)|浏览(286)

本文整理了Java中org.geotools.data.Query类的一些代码示例,展示了Query类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Query类的具体详情如下:
包路径:org.geotools.data.Query
类名称:Query

Query介绍

[英]Encapsulates a request for data, typically as:

Query query = ... 
myFeatureSource.getFeatures(query);

The query class is based on the Web Feature Server specification and offers a few interesting capabilities such as the ability to sort results and use a filter (similar to the WHERE clause in SQL).

Additional capabilities:

  • #setMaxFeatures(int) and #setStartIndex(Integer) can be used implement 'paging' through the data source's content. This is useful if, for example, the FeatureSource has an upper limit on the number of features it can return in a single request or you are working with limited memory.

  • #setHandle(String) can be used to give the query a mnemonic name which will appear in error reporing and logs.

  • #setCoordinateSystem(CoordinateReferenceSystem) is used to to specify the coordinate system that retrieved features will be "forced" into. This is often used to correct a feature source when the application and the data format have different ideas about the coordinate system (for example, the "axis order" issue).

  • #setCoordinateSystemReproject(CoordinateReferenceSystem) is used to ask for the retrieved features to be reproejcted.
    Vendor specific:

  • setHints(Hints) is used to specify venfor specific capabilities provided by a feature source implementation.
    Joins:

The Query class supports the concepts of joins in that a query can result in a join of the feature type to other feature types in the same datastore. For example, the following would be a spatial join that selected the country that contain a particular city.

Query query = new Query("countries"); 
Join join = new Join("cities", CQL.toFilter("CONTAINS(geometry, b.geometry)")); 
join.setAlias("b"); 
join.setFilter(CQL.toFilter("CITY_NAME = 'Canmore'")) 
query.getJoins().add(join);

Example:

Filter filter = CQL.toFilter("NAME like '%land'"); 
Query query = new Query( "countries", filter ); 
FeatureCollection features = featureSource.getFeatures( query );

[中]封装数据请求,通常为:

Query query = ... 
myFeatureSource.getFeatures(query);

查询类基于Web Feature Server规范,并提供一些有趣的功能,例如对结果进行排序和使用筛选器的功能(类似于SQL中的WHERE子句)。
其他功能:
*#setMaxFeatures(int)和#setStartIndex(Integer)可用于实现对数据源内容的“分页”。例如,如果FeatureSource在单个请求中可以返回的功能数量有上限,或者您使用的是有限的内存,则此选项非常有用。
*#setHandle(String)可用于为查询提供一个助记符名称,该名称将出现在错误报告和日志中。
*#setCoordinateSystem(CoordinateReferenceSystem)用于指定检索到的要素将“强制”进入的坐标系。当应用程序和数据格式对坐标系有不同看法时(例如,“轴顺序”问题),这通常用于纠正特征源。
*#setCoordinateSystemReproject(CoordinateReferenceSystem)用于请求重新生成检索到的特征。
特定供应商:
*sethits(提示)用于指定功能源实现提供的特定功能。
加入:
查询类支持联接的概念,因为查询可以导致要素类型与同一数据存储中的其他要素类型联接。例如,下面是一个空间连接,它选择了包含特定城市的国家。

Query query = new Query("countries"); 
Join join = new Join("cities", CQL.toFilter("CONTAINS(geometry, b.geometry)")); 
join.setAlias("b"); 
join.setFilter(CQL.toFilter("CITY_NAME = 'Canmore'")) 
query.getJoins().add(join);

示例:

Filter filter = CQL.toFilter("NAME like '%land'"); 
Query query = new Query( "countries", filter ); 
FeatureCollection features = featureSource.getFeatures( query );

代码示例

代码示例来源:origin: geoserver/geoserver

@Test
public void testModify() throws Exception {
  final Query queryAll = new Query(RENAMED);
  SimpleFeatureStore store;
  store = (SimpleFeatureStore) rts.getFeatureSource(RENAMED);
  SimpleFeature original = store.getFeatures(fidFilter).features().next();
  String newAddress = ((String) original.getAttribute("ADDRESS")) + " xxx";
  store.modifyFeatures(
      original.getFeatureType().getDescriptor("ADDRESS"), newAddress, fidFilter);
  SimpleFeature modified = store.getFeatures(fidFilter).features().next();
  assertEquals(newAddress, modified.getAttribute("ADDRESS"));
}

代码示例来源:origin: geoserver/geoserver

if ((query == Query.ALL) || query.equals(Query.ALL)) {
  return query;
  Filter filter = query.getFilter();
  filter = makeDefinitionFilter(filter);
  Query defQuery = new Query(query);
  defQuery.setFilter(filter);
  defQuery.setPropertyNames(propNames);
  if (query.getSortBy() != null) {
    defQuery.setSortBy(query.getSortBy());
    query.getHints().put(Hints.LINEARIZATION_TOLERANCE, linearizationTolerance);

代码示例来源:origin: geoserver/geoserver

if (writeQuery == Query.ALL) {
  ((SimpleFeatureStore) storeDelegate).modifyFeatures(names, values, filter);
} else if (writeQuery.getFilter() == Filter.EXCLUDE
    || writeQuery.getPropertyNames() == Query.NO_NAMES) {
  throw unsupportedOperation();
final Query local = new Query(null, filter);
Query mixed = mixQueries(local, writeQuery);
if (writeQuery.getPropertyNames() == Query.ALL_NAMES) {
  ((SimpleFeatureStore) storeDelegate).modifyFeatures(names, values, mixed.getFilter());
} else {
      new HashSet<String>(Arrays.asList(writeQuery.getPropertyNames()));
      String typeName = getSchema().getName().getLocalPart();
      if (policy.getResponse() == org.geoserver.security.Response.CHALLENGE) {
        throw SecureCatalogImpl.unauthorizedAccess(typeName);
  ((SimpleFeatureStore) storeDelegate).modifyFeatures(names, values, mixed.getFilter());

代码示例来源:origin: geoserver/geoserver

/** Returns a GeoTools query build with the provided attributes and filters */
private Query buildQuery(List<PropertyName> attributes, Filter filter) {
  if (attributes == null && (filter == null || filter == Filter.INCLUDE)) {
    return Query.ALL;
  } else {
    Query q = new Query();
    q.setFilter(filter);
    // TODO: switch this to property names when possible
    q.setPropertyNames(flattenNames(attributes));
    return q;
  }
}

代码示例来源:origin: geoserver/geoserver

new Query(
        DataUtilities.mixQueries(userQuery, securityQuery, userQuery.getHandle()));
List<PropertyName> securityProperties = securityQuery.getProperties();
if (securityProperties != null && securityProperties.size() > 0) {
  List<PropertyName> userProperties = userQuery.getProperties();
  if (userProperties == null) {
    result.setProperties(securityProperties);
  } else {
    for (PropertyName pn : userProperties) {
    result.setProperties(userProperties);
if (userQuery.getHints() == null) {
  result.setHints(securityQuery.getHints());
} else if (securityQuery.getHints() == null) {
  result.setHints(userQuery.getHints());
} else {
  Hints mix = userQuery.getHints();
  mix.putAll(securityQuery.getHints());
  result.setHints(mix);
result.setCoordinateSystem(userQuery.getCoordinateSystem());
result.setCoordinateSystemReproject(userQuery.getCoordinateSystemReproject());
result.setStartIndex(userQuery.getStartIndex());
result.setSortBy(userQuery.getSortBy());

代码示例来源:origin: stackoverflow.com

Query query = new Query("__BlobInfo__"); 
query.addFilter("filename", FilterOperator.EQUAL, filename); 
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); 
PreparedQuery pq = datastore.prepare(query); 
List<Entity> entList = pq.asList(FetchOptions.Builder.withLimit(1)); 
String name = entList.get(0).getKey().getName();

代码示例来源:origin: geotools/geotools

public void testGetFeatureSourceRoad() throws Exception {
  SimpleFeatureSource road = dataStore.getFeatureSource(tname("road"));
  assertEquals(3, all.size());
  assertTrue(areReferencedEnvelopesEqual(td.roadBounds, all.getBounds()));
  assertTrue(areReferencedEnvelopesEqual(td.roadBounds, all.getBounds()));
  assertEquals(2, some.size());
  ReferencedEnvelope e = new ReferencedEnvelope(CRS.decode("EPSG:4326", forceLongitudeFirst));
  e.include(td.roadFeatures[0].getBounds());
  e.include(td.roadFeatures[1].getBounds());
  assertTrue(areReferencedEnvelopesEqual(e, some.getBounds()));
  assertEquals(some.getSchema(), road.getSchema());
  Query query = new Query(tname("road"), td.rd12Filter, new String[] {aname("name")});
  assertEquals(2, half.size());
  assertEquals(1, half.getSchema().getAttributeCount());
    assertEquals(type.getName(), actual.getName());
    assertEquals(type.getAttributeCount(), actual.getAttributeCount());

代码示例来源:origin: geotools/geotools

public void testGetFeaturesWithMax() throws Exception {
  Query q = new Query(featureSource.getSchema().getTypeName());
  q.setMaxFeatures(2);
  SimpleFeatureCollection features = featureSource.getFeatures(q);
  // check size
  assertEquals(2, features.size());
  // check actual iteration
  try (SimpleFeatureIterator it = features.features()) {
    int count = 0;
    ReferencedEnvelope env =
        new ReferencedEnvelope(features.getSchema().getCoordinateReferenceSystem());
    while (it.hasNext()) {
      SimpleFeature f = it.next();
      env.expandToInclude(ReferencedEnvelope.reference(f.getBounds()));
      count++;
    }
    assertEquals(2, count);
    assertTrue(areReferencedEnvelopesEqual(env, features.getBounds()));
  }
}

代码示例来源:origin: geotools/geotools

public void testGetFeaturesWithOffsetLimitAndPostFilter() throws Exception {
  Query q = new Query(featureSource.getSchema().getTypeName());
  // no sorting, let's see if the database can use native one
  FilterFactory ff = dataStore.getFilterFactory();
  PropertyIsEqualTo filter =
      ff.equal(
          ff.literal("one"),
          ff.function("strToLowerCase", ff.property(aname("stringProperty"))),
          true);
  q.setFilter(filter);
  q.setStartIndex(0);
  q.setMaxFeatures(1);
  SimpleFeatureCollection features = featureSource.getFeatures(q);
  // check size
  assertEquals(1, features.size());
  // check actual iteration
  try (SimpleFeatureIterator it = features.features()) {
    assertTrue(it.hasNext());
    SimpleFeature f = it.next();
    ReferencedEnvelope fe = ReferencedEnvelope.reference(f.getBounds());
    assertEquals(1, ((Number) f.getAttribute(aname("intProperty"))).intValue());
    assertFalse(it.hasNext());
    // assertEquals(fe, features.getBounds());
    assertTrue(areReferencedEnvelopesEqual(fe, features.getBounds()));
  }
}

代码示例来源:origin: geotools/geotools

assertSame(data, road.getDataStore());
assertEquals(3, road.getCount(Query.ALL));
assertEquals(new ReferencedEnvelope(1, 5, 0, 4, null), road.getBounds(Query.ALL));
assertEquals(3, all.size());
assertEquals(roadBounds, all.getBounds());
assertEquals(roadBounds, all.getBounds());
assertEquals(some.getSchema(), road.getSchema());
Query query = new Query("road", rd12Filter, new String[] {"name", "geom"});
assertEquals(2, half.size());
assertEquals(2, half.getSchema().getAttributeCount());
SimpleFeatureIterator reader = half.features();
SimpleFeatureType type = half.getSchema();
reader.close();
SimpleFeatureType actual = half.getSchema();
assertEquals(type.getTypeName(), actual.getTypeName());
assertEquals(type.getName(), actual.getName());
assertEquals(type.getAttributeCount(), actual.getAttributeCount());

代码示例来源:origin: geotools/geotools

public void testGetFeaturesWithOffset() throws Exception {
  Query q = new Query(featureSource.getSchema().getTypeName());
  q.setSortBy(
      new SortBy[] {
        dataStore.getFilterFactory().sort(aname("intProperty"), SortOrder.ASCENDING)
      });
  q.setStartIndex(2);
  SimpleFeatureCollection features = featureSource.getFeatures(q);
  // check size
  assertEquals(1, features.size());
  // check actual iteration
  try (SimpleFeatureIterator it = features.features()) {
    assertTrue(it.hasNext());
    SimpleFeature f = it.next();
    ReferencedEnvelope fe = ReferencedEnvelope.reference(f.getBounds());
    assertEquals(2, ((Number) f.getAttribute(aname("intProperty"))).intValue());
    assertFalse(it.hasNext());
    // assertEquals(fe, features.getBounds());
    assertTrue(areReferencedEnvelopesEqual(fe, features.getBounds()));
  }
}

代码示例来源:origin: geotools/geotools

void doTestSimpleJoinWithLimitOffset(boolean exposePrimaryKeys) throws Exception {
  dataStore.setExposePrimaryKeyColumns(exposePrimaryKeys);
  FilterFactory ff = dataStore.getFilterFactory();
  Filter j = ff.equal(ff.property(aname("stringProperty")), ff.property(aname("name")), true);
  Query q = new Query(tname("ft1"));
  q.getJoins().add(new Join(tname("ftjoin"), j));
  q.setFilter(ff.greater(ff.property(aname("intProperty")), ff.literal(0)));
  q.setStartIndex(1);
  q.setSortBy(new SortBy[] {ff.sort(aname("intProperty"), SortOrder.ASCENDING)});
  SimpleFeatureCollection features = dataStore.getFeatureSource(tname("ft1")).getFeatures(q);
  assertEquals(1, features.size());
  try (SimpleFeatureIterator it = features.features()) {
    assertTrue(it.hasNext());
    SimpleFeature f = it.next();
    assertEquals("two", f.getAttribute(aname("stringProperty")));
    SimpleFeature g = (SimpleFeature) f.getAttribute(aname("ftjoin"));
    assertEquals("two", g.getAttribute(aname("name")));
  }
}

代码示例来源:origin: geotools/geotools

public void testGetFeaturesWithOffsetLimit() throws Exception {
  Query q = new Query(featureSource.getSchema().getTypeName());
  // no sorting, let's see if the database can use native one
  q.setStartIndex(1);
  q.setMaxFeatures(1);
  SimpleFeatureCollection features = featureSource.getFeatures(q);
  // check size
  assertEquals(1, features.size());
  // check actual iteration
  try (SimpleFeatureIterator it = features.features()) {
    assertTrue(it.hasNext());
    SimpleFeature f = it.next();
    ReferencedEnvelope fe = ReferencedEnvelope.reference(f.getBounds());
    assertEquals(1, ((Number) f.getAttribute(aname("intProperty"))).intValue());
    assertFalse(it.hasNext());
    // assertEquals(fe, features.getBounds());
    assertTrue(areReferencedEnvelopesEqual(fe, features.getBounds()));
  }
}

代码示例来源:origin: geotools/geotools

public void testGetFeaturesWithQuery() throws Exception {
  FilterFactory ff = dataStore.getFilterFactory();
  PropertyIsEqualTo filter =
      ff.equals(ff.property(aname("stringProperty")), ff.literal("one"));
  Query query = new Query();
  query.setPropertyNames(new String[] {aname("doubleProperty"), aname("intProperty")});
  query.setFilter(filter);
  SimpleFeatureCollection features = featureSource.getFeatures(query);
  assertEquals(1, features.size());
  try (SimpleFeatureIterator iterator = features.features()) {
    assertTrue(iterator.hasNext());
    SimpleFeature feature = (SimpleFeature) iterator.next();
    assertEquals(2, feature.getAttributeCount());
    assertEquals(new Double(1.1), feature.getAttribute(aname("doubleProperty")));
    assertNotNull(feature.getAttribute(aname("intProperty")));
  }
}

代码示例来源:origin: opentripplanner/OpenTripPlanner

CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
  Query query = new Query();
  query.setCoordinateSystem(sourceCRS);
  query.setCoordinateSystemReproject(WGS84);
  SimpleFeatureCollection featureCollection = featureSource.getFeatures(query);
  SimpleFeatureIterator it = featureCollection.features();
  int i = 0;
  while (it.hasNext()) {
    SimpleFeature feature = it.next();
    Geometry geom = (Geometry) feature.getDefaultGeometry();
    Point point = null;
    if (geom instanceof Point) {
      label = Integer.toString(i);
    } else {
      label = feature.getAttribute(labelAttribute).toString();
      Number n = (Number) feature.getAttribute(inputAttribute);
      input = n.doubleValue(); 
  it.close();
} catch (Exception ex) {
  LOG.error("Error loading population from shapefile: {}", ex.getMessage());

代码示例来源:origin: geoserver/geoserver

@Test
public void testFeautureSourceFidFilter() throws Exception {
  // grab the last feature in the collection (there are more than one)
  SimpleFeatureSource fs = rts.getFeatureSource(RENAMED);
  // build a filter that will retrieve that feature only
  FilterFactory ff = CommonFactoryFinder.getFilterFactory(null);
  final String fid = RENAMED + ".1107531701011";
  Filter fidFilter = ff.id(Collections.singleton(ff.featureId(fid)));
  SimpleFeatureCollection fc = fs.getFeatures(new Query(RENAMED, fidFilter));
  assertEquals(RENAMED, fc.getSchema().getName().getLocalPart());
  assertEquals(1, fc.size());
  FeatureIterator<SimpleFeature> it = fc.features();
  assertTrue(it.hasNext());
  SimpleFeature sf = it.next();
  assertFalse(it.hasNext());
  it.close();
  assertEquals(fid, sf.getID());
}

代码示例来源:origin: geotools/geotools

public void testNaturalSortingAsc() throws Exception {
  Query q = new Query(featureSource.getSchema().getTypeName());
  q.setSortBy(new SortBy[] {SortBy.NATURAL_ORDER});
  try (SimpleFeatureIterator features = featureSource.getFeatures(q).features()) {
    String prevId = null;
    while (features.hasNext()) {
      String currId = features.next().getID();
      if (prevId != null) assertTrue(prevId.compareTo(currId) <= 0);
      prevId = currId;
    }
  }
}

代码示例来源:origin: geotools/geotools

public void testGeometryFactoryHintsCS() throws IOException {
  SimpleFeatureSource fs = dataStore.getFeatureSource(tname("road"));
  assertTrue(fs.getSupportedHints().contains(Hints.JTS_COORDINATE_SEQUENCE_FACTORY));
  Query q = new Query(tname("road"));
  Hints hints =
      new Hints(
          Hints.JTS_COORDINATE_SEQUENCE_FACTORY, new LiteCoordinateSequenceFactory());
  q.setHints(hints);
  try (SimpleFeatureIterator it = fs.getFeatures(q).features()) {
    it.hasNext();
    SimpleFeature f = (SimpleFeature) it.next();
    LineString ls = (LineString) f.getDefaultGeometry();
    assertTrue(ls.getCoordinateSequence() instanceof LiteCoordinateSequence);
  }
}

代码示例来源:origin: geotools/geotools

void doTestSimpleJoinWithSort(boolean exposePrimaryKeys) throws Exception {
  dataStore.setExposePrimaryKeyColumns(exposePrimaryKeys);
  FilterFactory ff = dataStore.getFilterFactory();
  Filter j = ff.equal(ff.property(aname("stringProperty")), ff.property(aname("name")), true);
  Query q = new Query(tname("ft1"));
  q.getJoins().add(new Join(tname("ftjoin"), j));
  q.setSortBy(new SortBy[] {ff.sort(aname("intProperty"), SortOrder.DESCENDING)});
  SimpleFeatureCollection features = dataStore.getFeatureSource(tname("ft1")).getFeatures(q);
  try (SimpleFeatureIterator it = features.features()) {
    assertTrue(it.hasNext());
    assertEquals("two", it.next().getAttribute(aname("stringProperty")));
    assertTrue(it.hasNext());
    assertEquals("one", it.next().getAttribute(aname("stringProperty")));
    assertTrue(it.hasNext());
    assertEquals("zero", it.next().getAttribute(aname("stringProperty")));
  }
}

代码示例来源:origin: opentripplanner/OpenTripPlanner

CoordinateReferenceSystem WGS84 = CRS.decode("EPSG:4326", true);
Query query = new Query();
query.setCoordinateSystem(sourceCRS);
query.setCoordinateSystemReproject(WGS84);
SimpleFeatureCollection featureCollection = featureSource.getFeatures(query);
SimpleFeatureIterator it = featureCollection.features();
SimpleFeature protoFt = it.next();
if (propertyFields == null) {
  propertyFields = new ArrayList<String>();
  for (Property p : protoFt.getProperties()) {
    propertyFields.add(p.getName().toString());
it = featureCollection.features();
PointSet ret = new PointSet(featureCollection.size());
int i=0;
while (it.hasNext()) {
  SimpleFeature feature = it.next();
  Geometry geom = (Geometry) feature.getDefaultGeometry();
    ft.setId(Integer.toString(i));
  } else {
    ft.setId(feature.getProperty(originIDField).getValue().toString());

相关文章