require(["esri/rest/support/TopFeaturesQuery"], (TopFeaturesQuery) => { /* code goes here */ });
import TopFeaturesQuery from "@arcgis/core/rest/support/TopFeaturesQuery.js";
esri/rest/support/TopFeaturesQuery
This class defines parameters for executing top features queries from a FeatureLayer. Once a TopFeaturesQuery object's properties are defined, it can then be passed into executable functions on a server-side FeatureLayer, which can return a FeatureSet containing features within a group. For example, you can use FeatureLayer's queryTopFeatures() method to query the most populous three counties in each state of the United States.
This class has many of the same properties as Query class. However, unlike the Query class,
this class does not support properties such as outStatistics
and its related parameters or returnDistinctValues
.
// query the top three most populous counties from each state.
// Results will be ordered based the population of each county in descending order
// top query will run against all features available in the service
const query = new TopFeaturesQuery({
outFields: ["State, Pop_total, County"],
topFilter: new TopFilter({
topCount: 3,
groupByFields: ["State"],
orderByFields: ["Pop_total DESC"]
})
});
featureLayer.queryTopFeatures(query)
.then(function(response){
// returns a feature set with features containing the most populous
// three counties in each state ordered by population.
// The following attributes are returned as well: State, Pop_total, County
});
There are three types of top features queries: attribute, spatial and temporal queries. You can query for features in one of these categories or use elements of each in a single query. When running a top features query, the topFilter parameter must always be set.
Attribute queries
To query top features based on attribute values, specify a SQL where clause in the where property along with the topFilter property. Setting the outFields of the query will limit the attributes returned from the query. This can improve the speed of the query if your app doesn't require all the attributes for each feature.
For example, you can use where and topFilter parameters to query the top three most populous cities in each country if the population is over 1,000,000.
const query = new TopFeaturesQuery({
where: "Population >= 1000000",
outFields: ["Country, Population, Name"],
topFilter: new TopFilter({
topCount: 3,
groupByFields: ["Country"],
orderByFields: [`Population DESC`]
})
});
featureLayer.queryTopFeatures(query)
.then(function(response){
// returns a feature set with features containing the most populous three cities
// in each country. The query will run only against cities where the population is
// over one million.
});
Spatial queries
You can query top features by geometry/location. While where is not required in this
workflow, you can use where
as part of the query to get more refined results. The topFilter property
must be set in addition to geometry property.
To execute a spatial query, you must set the geometry parameter to a
Geometry object and specify a valid spatialRelationship.
You can optionally provide a query distance and units to query features against a buffer
around the given geometry.
For example, to query for the two tallest buildings in each zoning category within 10 miles of a mouse move, you would do the following:
view.on("pointer-move", function(event){
const query = new TopFeaturesQuery({
outFields: ["Zoning, Floors, Year"],
topFilter: new TopFilter({
topCount: 2,
groupByFields: ["Zoning"],
orderByFields: ["Floors DESC"]
}),
geometry: view.toMap(event),
spatialRelationship: "intersects",
units: "miles",
distance: 10,
returnGeometry: true
});
featureLayer.queryTopFeatures(query)
.then(function(response){
// returns two tallest buildings in zoning category within a given geometry
// The following attributes are returned as well: Zoning, Floors, Year
});
});
You could also use where
, for example, to return the tallest buildings in a specific residential zoning districts within
the 10-mile buffer.
Temporal queries
You can query top features based on a given time range by specifying the timeExtent property. The temporal query will return results only if the feature service is published with timeInfo information. The temporal query can also be combined with attribute and geometry queries.
For example, you can use timeExtent and topFilter parameters to query hurricane tracks with the highest wind speed, grouped by the hurricane categories within a given time extent.
// query hurricanes that took place in 1992 and
// return a hurricane track with the highest wind speed in each category
const query = new TopFeaturesQuery({
outFields: ["STAGE, WINDSPEED, PRESSURE"],
topFilter: new TopFilter({
topCount: 1,
groupByFields: ["STAGE"],
orderByFields: ["WINDSPEED DESC"]
}),
timeExtent: {
start: new Date(1992, 0, 1),
end: new Date(1992, 11, 31)
}
});
featureLayer.queryTopFeatures(query)
.then(function(response){
// returns a hurricane with the highest wind speed
// in each stage... the query will only run against
// hurricanes that happened in 1992
});
Known Limitations
- Currently, the
TopFeatureQuery
is only supported with server-side FeatureLayer.
- See also
Constructors
-
Parameterproperties Objectoptional
See the properties for a list of all the properties that may be passed into the constructor.
Property Overview
Name | Type | Summary | Class |
---|---|---|---|
Indicates if the service should cache the query results. | TopFeaturesQuery | ||
The name of the class. | Accessor | ||
Specifies a search distance from a given geometry in a spatial query. | TopFeaturesQuery | ||
The geometry to apply to the spatial filter. | TopFeaturesQuery | ||
Specifies the number of decimal places for geometries returned by the query operation. | TopFeaturesQuery | ||
The maximum distance in units of outSpatialReference used for generalizing geometries returned by the query operation. | TopFeaturesQuery | ||
The number of features to retrieve. | TopFeaturesQuery | ||
An array of ObjectIDs to be used to query for features in a layer. | TopFeaturesQuery | ||
One or more field names used to order the query results. | TopFeaturesQuery | ||
Attribute fields to include in the FeatureSet. | TopFeaturesQuery | ||
The spatial reference for the returned geometry. | TopFeaturesQuery | ||
If | TopFeaturesQuery | ||
If | TopFeaturesQuery | ||
If | TopFeaturesQuery | ||
For spatial queries, this parameter defines the spatial relationship to query features in the layer or layer view against the input geometry. | TopFeaturesQuery | ||
The zero-based index indicating where to begin retrieving features. | TopFeaturesQuery | ||
A time extent for a temporal query against time-aware layers. | TopFeaturesQuery | ||
The | TopFeaturesQuery | ||
The unit for calculating the buffer distance when distance is specified in spatial queries. | TopFeaturesQuery | ||
A where clause for the query. | TopFeaturesQuery |
Property Details
-
cacheHint
cacheHint Boolean
-
Indicates if the service should cache the query results. It only applies if the layer's capabilities.queryTopFeatures.supportsCacheHint is set to
true
. Use only for queries that have the same parameters every time the app is used. Some examples of cacheable queries:- Queries based on preset input, for example, a drop-down list of US states.
- Queries based on preset extents, for example bookmarks, in web maps.
- Default Value:undefined
-
distance
distance Number
-
Specifies a search distance from a given geometry in a spatial query. The units property indicates the unit of measurement. In essence, setting this property creates a buffer at the specified size around the input geometry. The query will use that buffer to return features in the layer or layer view that adhere to the to the indicated spatial relationship.
If querying a feature service, the supportsQueryWithDistance capability must be
true
.
-
The geometry to apply to the spatial filter. The spatial relationship as specified by spatialRelationship will indicate how the geometry should be used to query features.
Known Limitations
Mesh geometry types are currently not supported.
-
geometryPrecision
geometryPrecision Number
-
Specifies the number of decimal places for geometries returned by the query operation.
-
maxAllowableOffset
maxAllowableOffset Number
-
The maximum distance in units of outSpatialReference used for generalizing geometries returned by the query operation. It limits how far any part of the generalized geometry can be from the original geometry. If
outSpatialReference
is not defined, the spatialReference of the data is used.
-
num
num Number
-
The number of features to retrieve. This option should be used in conjunction with the start property. Use this to implement paging (i.e. to retrieve "pages" of results when querying).
If not provided, but an instance of Query has a
start
property, then the default value ofnum
is 10. If neithernum
norstart
properties are provided, then the default value ofnum
is equal to themaxRecordCount
of the service, which can be found at the REST endpoint of the FeatureLayer.
-
An array of ObjectIDs to be used to query for features in a layer.
-
One or more field names used to order the query results. Specify
ASC
(ascending) orDESC
(descending) after the field name to control the order. The default order isASC
.- See also
Examplequery.orderByFields = ["STATE_NAME DESC"];
-
Attribute fields to include in the FeatureSet. Fields must exist in the service layer. You must list actual field names rather than field aliases. You may, however, use field aliases when you display the results of the query.
When specifying the output fields, you should limit the fields to only those you expect to use in the query or the results. The fewer fields you include, the smaller the payload size, and therefore the faster the response of the query.
You can also specify SQL expressions as
outFields
to calculate new values server side for the query results. See the example snippets below for an example of this.Each query must have access to the
Shape
andObjectId
fields for a layer. However, the list of outFields does not need to include these two fields.Known Limitations
- If specifying outFields as expressions on a feature service-based FeatureLayer, the service capabilities
advancedQueryCapabilities.supportsOutFieldSQLExpression
anduseStandardizedQueries
must both be true.
- Default Value:null
Examples// query for field attributes query.outFields = [ "NAME", "STATE_ABBR", "POP04" ];
// query for data returned from an expressions and other fields as the following field names // POP_CHANGE_2020, NAME, POP2020 // where POP_CHANGE_2020 represents the population change from 2010 - 2020 query.outFields = [ "( (POP2020 - POP2010) / POP2010 ) * 100 as POP_CHANGE_2020", "NAME", "POP2020" ]
- If specifying outFields as expressions on a feature service-based FeatureLayer, the service capabilities
-
outSpatialReference
outSpatialReference SpatialReferenceautocast
-
The spatial reference for the returned geometry. If not specified, the geometry is returned in the spatial reference of the queried layer.
-
returnGeometry
returnGeometry Boolean
-
If
true
, each feature in the returned FeatureSet includes the geometry.- Default Value:false
-
returnM
returnM Boolean
-
If
true
, and returnGeometry istrue
, then m-values are included in the geometry.
-
returnZ
returnZ Boolean
-
If
true
, and returnGeometry istrue
, then z-values are included in the geometry.
-
spatialRelationship
spatialRelationship String
-
For spatial queries, this parameter defines the spatial relationship to query features in the layer or layer view against the input geometry. The spatial relationships discover how features are spatially related to each other. For example, you may want to know if a polygon representing a county completely contains points representing settlements.
The spatial relationship is determined by whether the boundaries or interiors of a geometry intersect.
- Boundary — The endpoints of all linear parts for line features, or the linear outline of a polygon. Only lines and polygons have boundaries.
- Interior — Points are entirely interior and have no boundary. For lines and polygons, the interior is any part of the geometry that is not part of the boundary.
The possible values for this parameter are described below and the images highlight the geometries returned for the specified spatial relationship for given geometries.
The
intersects
spatial relationship returns features in the layer view that intersect the query geometry.The
contains
spatial relationship returns features in the layer view that are completely contained by the query geometry.The
crosses
spatial relationship returns features in the layer view when the interior of a query geometry comes into contact with the interior or boundary of features in the layer view. In other words, the geometries share some interior area, but not all interior area.The
envelope-intersects
spatial relationship returns features in the layer view that intersect the envelope (or extent) of the filter geometry.The
overlaps
spatial relationship returns features in the layer view that overlap the query geometry. Only features of the same geometry can be compared.The
touches
spatial relationship returns features in the layer view that touch the query geometry. The boundaries of the geometries intersect, but not their interiors.The
within
spatial relationship returns features in the layer view that completely contain the query geometry. In other words, the filter geometry is completelywithin
the features in the layer view. It is opposite ofcontains
.Known Limitations
- For spatial queries on 3D Object SceneLayers and BuildingSceneLayers the spatial relationship is evaluated based on the Extent of the feature and not the footprint. This means that a feature might be returned from the query, even though its footprint is not in a spatial relationship with the geometry.
- Currently only
intersects
,contains
, anddisjoint
spatialRelationships are supported on spatial queries for 3D Object SceneLayers and BuildingSceneLayers.
Possible Values:"intersects" |"contains" |"crosses" |"envelope-intersects" |"index-intersects" |"overlaps" |"touches" |"within" |"relation"
- Default Value:intersects
Exampleconst query = new TopFeaturesQuery({ spatialRelationship: "contains", geometry: extent, topFilter: new TopFilter({ topCount: 3, groupByFields: ["State"], orderByFields: ["Pop_total DESC"] }) });
-
timeExtent
timeExtent TimeExtentautocast
-
A time extent for a temporal query against time-aware layers. For example, it can be used to discover all crimes that occurred during the night shift from 10 PM to 6 AM on a particular date.
Example// query hurricanes that took place in 1992 and // return a hurricane track with the highest wind speed in each category const query = new TopFeaturesQuery({ outFields: ["STAGE, WINDSPEED, PRESSURE"], topFilter: new TopFilter({ topCount: 1, groupByFields: ["STAGE"], orderByFields: ["WINDSPEED DESC"] }), timeExtent: { start: new Date(1992, 0, 1), end: new Date(1992, 11, 31) } }); featureLayer.queryTopFeatures(query) .then(function(response){ // returns a hurricane with the highest wind speed // in each stage... the query will only run against // hurricanes that happened in 1992 });
-
The
topFilter
parameter is used to set the groupByFields, orderByFields, and topCount criteria used in generating the result.Example// return top three most populous cities from each state const query = new TopFeaturesQuery({ topFilter: new TopFilter({ topCount: 3, groupByFields: ["State"], orderByFields: ["Pop_total DESC"] }) }); layer.queryTopFeatures(query).then(function(featureSet) { ... });
-
units
units String
-
The unit for calculating the buffer distance when distance is specified in spatial queries. If
units
is not specified, the unit is derived from the geometry spatial reference. If the geometry spatial reference is not specified, the unit is derived from the feature service data spatial reference. For service-based queries, this parameter only applies if the layer's capabilities.query.supportsDistance istrue
.Possible Values:"feet" |"miles" |"nautical-miles" |"us-nautical-miles" |"meters" |"kilometers"
- Default Value:null
Example// Query at a distance in pixels of the query geometry. // Use the unit of the query geometry's spatial reference. layerView.queryFeatures({ geometry: event.mapPoint, distance: 2 * view.resolution, returnGeometry: true }).then(processResults);
-
where
where String
-
A where clause for the query. Any legal SQL where clause operating on the fields in the layer is allowed. Be sure to have the correct sequence of single and double quotes when writing the where clause in JavaScript.
Examplesquery.where = `NAME = ${stateName}`;
query.where = `POP04 > ${population}`;
Method Overview
Name | Return Type | Summary | Class |
---|---|---|---|
Adds one or more handles which are to be tied to the lifecycle of the object. | Accessor | ||
Creates a deep clone of TopFeaturesQuery object. | TopFeaturesQuery | ||
* | Creates a new instance of this class and initializes it with values from a JSON object generated from an ArcGIS product. | TopFeaturesQuery | |
Returns true if a named group of handles exist. | Accessor | ||
Removes a group of handles owned by the object. | Accessor | ||
Converts an instance of this class to its ArcGIS portal JSON representation. | TopFeaturesQuery |
Method Details
-
Inherited from Accessor
Since: ArcGIS Maps SDK for JavaScript 4.25Accessor since 4.0, addHandles added at 4.25. -
Adds one or more handles which are to be tied to the lifecycle of the object. The handles will be removed when the object is destroyed.
// Manually manage handles const handle = reactiveUtils.when( () => !view.updating, () => { wkidSelect.disabled = false; }, { once: true } ); this.addHandles(handle); // Destroy the object this.destroy();
ParametershandleOrHandles WatchHandle|WatchHandle[]Handles marked for removal once the object is destroyed.
groupKey *optionalKey identifying the group to which the handles should be added. All the handles in the group can later be removed with Accessor.removeHandles(). If no key is provided the handles are added to a default group.
-
clone
clone(){TopFeaturesQuery}
-
Creates a deep clone of TopFeaturesQuery object.
ReturnsType Description TopFeaturesQuery A new instance of a TopFeaturesQuery object equal to the object used to call .clone()
.
-
Creates a new instance of this class and initializes it with values from a JSON object generated from an ArcGIS product. The object passed into the input
json
parameter often comes from a response to a query operation in the REST API or a toJSON() method from another ArcGIS product. See the Using fromJSON() topic in the Guide for details and examples of when and how to use this function.Parameterjson ObjectA JSON representation of the instance in the ArcGIS format. See the ArcGIS REST API documentation for examples of the structure of various input JSON objects.
ReturnsType Description * Returns a new instance of this class.
-
hasHandles
InheritedMethodhasHandles(groupKey){Boolean}
Inherited from AccessorSince: ArcGIS Maps SDK for JavaScript 4.25Accessor since 4.0, hasHandles added at 4.25. -
Returns true if a named group of handles exist.
ParametergroupKey *optionalA group key.
ReturnsType Description Boolean Returns true
if a named group of handles exist.Example// Remove a named group of handles if they exist. if (obj.hasHandles("watch-view-updates")) { obj.removeHandles("watch-view-updates"); }
-
Inherited from Accessor
Since: ArcGIS Maps SDK for JavaScript 4.25Accessor since 4.0, removeHandles added at 4.25. -
Removes a group of handles owned by the object.
ParametergroupKey *optionalA group key or an array or collection of group keys to remove.
Exampleobj.removeHandles(); // removes handles from default group obj.removeHandles("handle-group"); obj.removeHandles("other-handle-group");
-
toJSON
toJSON(){Object}
-
Converts an instance of this class to its ArcGIS portal JSON representation. See the Using fromJSON() guide topic for more information.
ReturnsType Description Object The ArcGIS portal JSON representation of an instance of this class.