Query
require(["esri/tasks/support/Query"], function(Query) { /* code goes here */ });
esri/tasks/support/Query
This class defines parameters for executing queries for features from a layer or layer view. Once a Query object's properties are defined, it can then be passed into an executable function, which will return the features in a FeatureSet.
There are three types of queries: attribute, spatial, and statistic queries. You can query for features in one of these categories or use elements of each in a single query.
Attribute queries
To query features based on attribute values, specify a SQL where clause in the where property. You can optionally use the text property for a LIKE
statement. 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 to query all counties in the state of Washington from a layer representing U.S. Counties:
var query = featureLayer.createQuery();
query.where = "STATE_NAME = 'Washington'";
query.outFields = [ "STATE_NAME", "COUNTY_NAME", "POPULATION", "(POPULATION / AREA) as 'POP_DENSITY'" ];
featureLayer.queryFeatures(query)
.then(function(response){
// returns a feature set with features containing the following attributes
// STATE_NAME, COUNTY_NAME, POPULATION, POP_DENSITY
});
Spatial queries
You can query 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.
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 all features within 2 miles of a mouse move, you would do the following:
view.on("pointer-move", function(event){
var query = featureLayer.createQuery();
query.geometry = view.toMap(event); // the point location of the pointer
query.spatialRelationship = "intersects"; // this is the default
query.returnGeometry = true;
query.outFields = [ "POPULATION" ];
featureLayerView.queryFeatures(query)
.then(function(response){
// returns a feature set with features containing the
// POPULATION attribute and each feature's geometry
});
});
You could also use where
, for example, to return all features with a population greater than 10,000 within the 2-mile buffer.
Statistic queries
Rather than return individual features from a query, you can return statistics for field attributes and expressions. Statistic queries are defined by the outStatistics parameter, which requires an array of StatisticDefinition objects.
For example, you can query for the average and total population of counties in the layer mentioned above in the following manner:
// query for the sum of the population in all features
var sumPopulation = {
onStatisticField: "POP_2015", // service field for 2015 population
outStatisticFieldName: "Pop_2015_sum",
statisticType: "sum"
};
// query for the average population in all features
var avgPopulation = {
onStatisticField: "POP_2015", // service field for 2015 population
outStatisticFieldName: "Pop_2015_avg",
statisticType: "avg"
};
// Notice that you can pass a SQL expression as a field name to calculate statistics
var populationChangeDefinition = {
onStatisticField: "POP_2015 - POP_2010", // service field for 2015 population
outStatisticFieldName: "avg_pop_change_2015_2010",
statisticType: "avg"
};
var query = layer.createQuery();
query.where = "STATE_NAME = 'Washington'";
query.outStatistics = [ sumPopulation, avgPopulation, populationChangeDefinition ];
layer.queryFeatures(query)
.then(function(response){
var stats = response.features[0].attributes;
console.log("Total Population in WA": stats.Pop_2015_sum);
console.log("Average Population in WA counties": stats.Pop_2015_avg);
console.log("Average Population change in WA counties": stats.avg_pop_change_2015_2010);
});
Working with results
Query results can be used in a number of ways depending on the use case. Consider the following parameters which impact the format of the resulting feature set.
- returnGeometry - Returning a geometry is useful for displaying results back in the view as graphics, or for conducting further spatial analysis. If the geometry isn't necessary in your workflow, then don't request it to improve app performance.
- outStatistics - Querying for statistics will never return features from the layer, only an object with number properties for the requested statistics.
- returnDistinctValues - Returns the unique values that exist in a field as an array of strings, so no features are returned when this parameter is true.
- See also:
Constructors
- new Query(properties)
- Parameter:properties Objectoptional
See the properties for a list of all the properties that may be passed into the constructor.
Property Overview
Name | Type | Summary | Class | |
---|---|---|---|---|
Number | Datum transformation used for projecting geometries in the query results when outSpatialReference is different than the layer's spatial reference. more details | more details | Query | |
String | The name of the class. more details | more details | Accessor | |
Number | Specifies a search distance from a given geometry in a spatial query. more details | more details | Query | |
String | Specifies the geodatabase version to display for feature service queries. more details | more details | Query | |
Geometry | The geometry to apply to the spatial filter. more details | more details | Query | |
Number | Specifies the number of decimal places for geometries returned by the query operation. more details | more details | Query | |
String[] | Used only in statistical queries. more details | more details | Query | |
String | A condition used with outStatistics and groupByFieldsForStatistics to limit query results to groups that satisfy the aggregation function(s). more details | more details | Query | |
Date | The historic moment to query. more details | more details | Query | |
Number | The maximum distance in units of outSpatialReference used for generalizing geometries returned by the query operation. more details | more details | Query | |
Number | When set, the maximum number of features returned by the query will equal the | more details | Query | |
String | Parameter dictates how the geometry of a multipatch feature will be returned. more details | more details | Query | |
Number | The number of features to retrieve. more details | more details | Query | |
Number[] | A comma delimited list of ObjectIDs for the features in the layer being queried. more details | more details | Query | |
String[] | One or more field names used to order the query results. more details | more details | Query | |
String[] | Attribute fields to include in the FeatureSet. more details | more details | Query | |
SpatialReference | The spatial reference for the returned geometry. more details | more details | Query | |
StatisticDefinition[] | The definitions for one or more field-based statistics to be calculated. more details | more details | Query | |
Object[] | Filters features from the layer based on pre-authored parameterized filters. more details | more details | Query | |
Symbol | Specifies the pixel level to be identified on the X and Y axis. more details | more details | Query | |
Object | Used to project the geometry onto a virtual grid, likely representing pixels on the screen. more details | more details | Query | |
Object[] | Filters features from the layer that are within the specified range values. more details | more details | Query | |
String | The Dimensionally Extended 9 Intersection Model (DE-9IM) matrix relation (encoded as a string) to query the spatial relationship of the input geometry to the layer's features. more details | more details | Query | |
Boolean | If | more details | Query | |
Boolean | If | more details | Query | |
Boolean | If | more details | Query | |
Boolean | If | more details | Query | |
Boolean | If | more details | Query | |
Boolean | If | more details | Query | |
String | For spatial queries, this parameter defines the spatial relationship to query features in the layer or layer view against the input geometry. more details | more details | Query | |
String | This parameter can be either standard SQL92 | more details | Query | |
Number | The zero-based index indicating where to begin retrieving features. more details | more details | Query | |
String | Shorthand for a where clause using "like". more details | more details | Query | |
String | The unit for calculating the buffer distance when distance is specified in spatial queries. more details | more details | Query | |
String | A where clause for the query. more details | more details | Query |
Property Details
- datumTransformationNumberSince: ArcGIS API for JavaScript 4.7
Datum transformation used for projecting geometries in the query results when outSpatialReference is different than the layer's spatial reference. Requires ArcGIS Server service 10.5 or greater.
- Since: ArcGIS API for JavaScript 4.7
The name of the class. The declared class name is formatted as
esri.folder.className
.
- distanceNumber
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
.
- gdbVersionStringSince: ArcGIS API for JavaScript 4.7
Specifies the geodatabase version to display for feature service queries.
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.
- geometryPrecisionNumber
Specifies the number of decimal places for geometries returned by the query operation.
- groupByFieldsForStatisticsString[]
Used only in statistical queries. When one or more field names are provided in this property, the output statisics will be grouped based on unique values from those fields. This is only valid when outStatistics has been defined.
Example:query.outStatistics = [{ onStatisticField: "CUSTOMERS", outStatisticFieldName: "avg_customers", statisticType: "avg" }, { onStatisticField: "RATING", outStatisticFieldName: "min_rating", statisticType: "min" }, { onStatisticField: "1=1", outStatisticFieldName: "total_businesses", statisticType: "count" }]; query.groupByFieldsForStatistics = [ "region" ]; // query the above stats for each region in the layer layer.queryFeatures(query).then(displayResults);
- havingStringSince: ArcGIS API for JavaScript 4.9
A condition used with outStatistics and groupByFieldsForStatistics to limit query results to groups that satisfy the aggregation function(s).
The following aggregation functions are supported in this clause:
MIN
|MAX
|AVG
|SUM
|STDDEV
|COUNT
|VAR
Aggregation functions used in
having
must be included in theoutStatistics
as well. See the snippet below for an example of how this works.For service-based layer queries, this parameter applies only if the supportsHavingClause property of the layer is
true
. This property is supported on all LayerView queries.Example:query.outStatistics = [{ onStatisticField: "CUSTOMERS", outStatisticFieldName: "avg_customers", statisticType: "avg" }, { onStatisticField: "RATING", outStatisticFieldName: "min_rating", statisticType: "min" }, { onStatisticField: "1=1", outStatisticFieldName: "total_businesses", statisticType: "count" }]; query.groupByFieldsForStatistics = [ "region" ]; query.having = "AVG(CUSTOMERS) >= 1,000 AND MIN(RATING) >= 3"; // query the above stats for all regions where // the average number of daily customers per business is // greater than 1,000 and the minimum customer rating // for a business within the region is 3 layer.queryFeatures(query).then(displayResults);
- historicMomentDateSince: ArcGIS API for JavaScript 4.7
The historic moment to query. This parameter applies only if the
supportsQueryWithHistoricMoment
capability of the service being queried istrue
. This setting is provided in the layer resource.
- maxAllowableOffsetNumber
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.
- maxRecordCountFactorNumberSince: ArcGIS API for JavaScript 4.7
When set, the maximum number of features returned by the query will equal the
maxRecordCount
of the service multiplied by this factor. The value of this property may not exceed5
.For example, if the
maxRecordCount
of your feature service is2000
, and you set themaxRecordCountFactor
to5
, then the maximum number of features that could be returned by the query is10000
.Known Limitations
Only supported with ArcGIS Online hosted services or ArcGIS Enterprise 10.6 services.
- Default Value:1
- multipatchOptionString
Parameter dictates how the geometry of a multipatch feature will be returned. Currently, the only supported value is
xyFootprint
. If indicated, the xy footprint of each multipatch geometry will be returned in the result.Example:var queryTask = new QueryTask( ... ); var query = new Query({ objectIds: [22], multipatchOption: "xyFootprint", outFields: ["*"], returnGeometry: true }); queryTask.execute(query);
- numNumber
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.Known Limitations
This property does not apply to layer view or CSVLayer queries.
- objectIdsNumber[]
A comma delimited list of ObjectIDs for the features in the layer being queried.
- orderByFieldsString[]
One or more field names used to order the query results. Specfiy
ASC
(ascending) orDESC
(descending) after the field name to control the order. The default order isASC
.Known Limitations
- If querying a MapImageLayer, then
supportsAdvancedQueries
must betrue
on the service. - For FeatureLayer,
FeatureLayer.capabilities.queryRelated.supportsOrderBy
must betrue
.
- See also:
Example:query.orderByFields = ["STATE_NAME DESC"];
- If querying a MapImageLayer, then
- outFieldsString[]
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.
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
- outSpatialReferenceSpatialReferenceautocast
The spatial reference for the returned geometry. If not specified, the geometry is returned in the spatial reference of the map.
- outStatisticsStatisticDefinition[]autocastAutocasts from Object[]
The definitions for one or more field-based statistics to be calculated. If
outStatistics
is specified the only other query parameters that should be used are groupByFieldsForStatistics, orderByFields, text, and where.Known Limitations
For service-based queries,
outStatistics
is only supported on layers wheresupportsStatistics = true
.Example:var query = new Query(); var statisticDefinition: new StatisticDefinition({ statisticType: "sum", onStatisticField: "POP2000", outStatisticFieldName: "TotalPop" }); query.outStatistics [ statisticsDefinition ];
- parameterValuesObject[]Since: ArcGIS API for JavaScript 4.7
Filters features from the layer based on pre-authored parameterized filters. When value is not specified for any parameter in a request, the default value, that is assigned during authoring time, gets used. Requires an ArcGIS Enterprise service 10.5 or greater.
- Properties:
- name String
The parameter name.
Single value or array of values.
Specifies the pixel level to be identified on the X and Y axis. Defaults to the base resolution of the dataset if not specified. Applicable only to Image Service layers.
- quantizationParametersObject
Used to project the geometry onto a virtual grid, likely representing pixels on the screen.
Known Limitations
Only supported with ArcGIS Online hosted services or ArcGIS Enterprise 10.6.1 services.
- Properties:
- optionalextent Extent
An extent defining the quantization grid bounds. Its SpatialReference matches the input geometry spatial reference if one is specified for the query. Otherwise, the extent will be in the layer's spatial reference.
optionalmode StringGeometry coordinates are optimized for viewing and displaying of data. Possible Values: view
optionaloriginPosition StringDefault Value:upper-leftThe integer's coordinates will be returned relative to the origin position defined by this property value. Possible Values: upper-left | lower-left
optionaltolerance NumberThe size of one pixel in the units of outSpatialReference. This number is used to convert coordinates to integers by building a grid with a resolution matching the tolerance. Each coordinate is then snapped to one pixel on the grid. Consecutive coordinates snapped to the same pixel are removed for reducing the overall response size. The units of tolerance will match the units of outSpatialReference. If outSpatialReference is not specified, then tolerance is assumed to be in the units of the spatial reference of the layer. If tolerance is not specified, the maxAllowableOffset is used. If tolerance and maxAllowableOffset are not specified, a grid of 10,000 * 10,000 grid is used by default.
Example:var query = new Query(); query.quantizationParameters = { mode: "view", originPosition: "upper-left", tolerance: 4820, extent: layer.fullExtent };
- rangeValuesObject[]Since: ArcGIS API for JavaScript 4.7
Filters features from the layer that are within the specified range values. Requires ArcGIS Enterprise services 10.5 or greater.
- Properties:
- name String
The range id.
Single value or value range.
- relationParameterString
The Dimensionally Extended 9 Intersection Model (DE-9IM) matrix relation (encoded as a string) to query the spatial relationship of the input geometry to the layer's features. This string contains the test result of each intersection represented in the DE-9IM matrix. Each result is one character of the string and may be represented as either a number (maximum dimension returned: 0,1,2), a Boolean value (T or F), or a mask character (for ignoring results: '*').
Set this parameter when the spatialRelationship is
relation
. The Relational functions for ST_Geometry topic has additional details on how to construct these strings.Known Limitations
This property does not apply to layer view or CSVLayer queries.
Example:var query = new Query({ relationParameter: "FFFTTT***" });
- returnCentroidBooleanSince: ArcGIS API for JavaScript 4.6
If
true
, each feature in the returned FeatureSet will be returned with a centroid. This property only applies to queries against polygon FeatureLayers.Known Limitations
Only supported with ArcGIS Online hosted services or ArcGIS Enterprise 10.6.1 services.
- Default Value:false
- returnDistinctValuesBoolean
If
true
then the query returns distinct values based on the field(s) specified in outFields.Known Limitations
- For service-based queries, this parameter applies only if the
supportsAdvancedQueries
capability of the layer istrue
.
- Default Value:false
- For service-based queries, this parameter applies only if the
- returnExceededLimitFeaturesBooleanSince: ArcGIS API for JavaScript 4.6
If
true
, then all features are returned for each tile request, even if they exceed the maximum record limit per query indicated on the service bymaxRecordCount
. Iffalse
, the tile request will not return any features if themaxRecordCount
limit is exceeded.Known Limitations
Only supported with ArcGIS Online hosted services or ArcGIS Enterprise 10.6 services.
- Default Value:true
- returnGeometryBoolean
If
true
, each feature in the returned FeatureSet includes the geometry.Known Limitations
For FeatureLayerView queries, the precision of the returned geometries will only be as high as the view's scale resolution since geometries are quantized for improved performance on the view. The smaller the scale, the lower the resolution of the geometries.
This limitation does not apply to FeatureLayer, CSVLayer, and CSVLayerView queries.
- Default Value:false
- returnMBooleanSince: ArcGIS API for JavaScript 4.6
If
true
, and returnGeometry istrue
, then m-values are included in the geometry.
- returnZBoolean
If
true
, and returnGeometry istrue
, then z-values are included in the geometry.
- spatialRelationshipString
For spatial queries, this parameter defines the spatial relationship to query features in the layer or layer view against the input geometry. See the Types of spatial relationships that can be validated document for more details about each spatial relationship.
The possible values are listed in the table below:
Value Description intersects Returns features from the layer or layer view that intersect the input geometry. contains Returns features from the layer or layer view that are completely contained by the input geometry. crosses Returns features from the layer or layer view that cross the input geometry. envelope-intersects Returns features from the layer or layer view that intersect the envelope (or extent) of the input geometry. index-intersects The envelope of the query feature class intersects the index entry for the target feature class. overlaps Returns features from the layer or layer view that overlap the input geometry. touches Returns features from the layer or layer view that touch the input geometry. within Returns features from the layer or layer view that are completely within the input geometry. relation Allows specification of any relationship defined using the Shape Comparison Language. If this value is specified, then the relationParameter must also be specified. - Default Value:intersects
Example:var query = new Query({ spatialRelationship: "contains" });
- sqlFormatStringSince: ArcGIS API for JavaScript 4.7
This parameter can be either standard SQL92
standard
or it can use the native SQL of the underlying datastorenative
. See the ArcGIS REST API documentation for more information.Possible Values: none | standard | native
Known Limitations
This property does not apply to layer view or CSVLayer queries.
- Default Value:none
- startNumber
The zero-based index indicating where to begin retrieving features. This property hould be used in conjunction with num. Use this to implement paging and retrieve "pages" of results when querying. Features are sorted ascending by object ID by default.
Known Limitations
This property does not apply to layer view or CSVLayer queries.
- textString
Shorthand for a where clause using "like". The field used is the display field defined in the services directory.
- Default Value:null
- unitsString
The unit for calculating the buffer distance when distance is specified in spatial queries. if
unit
is not specified, the unit is derived from the layer or layer view's SpatialReference.Known Limitations
For service-based queries, this parameter only applies if supportsQueryWithDistance is
true
.Possible Values: feet | miles | nautical-miles | us-nautical-miles | meters | kilometers
- whereString
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.
Examples:query.where = "NAME = '" + stateName + "'";
query.where = "POP04 > " + population;
Method Overview
Name | Return Type | Summary | Class | |
---|---|---|---|---|
Query | Creates a deep clone of Query object. more details | more details | Query | |
* | Creates a new instance of this class and initializes it with values from a JSON object generated from a product in the ArcGIS platform. more details | more details | Query | |
Object | Converts an instance of this class to its ArcGIS portal JSON representation. more details | more details | Query |
Method Details
- clone(){Query}Since: ArcGIS API for JavaScript 4.6
Creates a deep clone of Query object.
Returns:Type Description Query A new instance of a Query object equal to the object used to call .clone()
.
- fromJSON(json){*}static
Creates a new instance of this class and initializes it with values from a JSON object generated from a product in the ArcGIS platform. 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.Parameter:json 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.
Returns:Type Description * Returns a new instance of this class.
- toJSON(){Object}
Converts an instance of this class to its ArcGIS portal JSON representation. See the Using fromJSON() topic in the Guide for more information.
Returns:Type Description Object The ArcGIS portal JSON representation of an instance of this class.