TopFeaturesQuery

AMD: require(["esri/rest/support/TopFeaturesQuery"], (TopFeaturesQuery) => { /* code goes here */ });
ESM: import TopFeaturesQuery from "@arcgis/core/rest/support/TopFeaturesQuery";
Class: esri/rest/support/TopFeaturesQuery
Inheritance: TopFeaturesQuery Accessor
Since: ArcGIS API for JavaScript 4.20

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

new TopFeaturesQuery(properties)
Parameter:
properties Object
optional

See the properties for a list of all the properties that may be passed into the constructor.

Property Overview

Any properties can be set, retrieved or listened to. See the Working with Properties topic.
Show inherited properties Hide inherited properties
Name Type Summary Class
Booleanmore details

Indicates if the service should cache the query results.

more detailsTopFeaturesQuery
Stringmore details

The name of the class.

more detailsAccessor
Numbermore details

Specifies a search distance from a given geometry in a spatial query.

more detailsTopFeaturesQuery
Geometrymore details

The geometry to apply to the spatial filter.

more detailsTopFeaturesQuery
Numbermore details

Specifies the number of decimal places for geometries returned by the query operation.

more detailsTopFeaturesQuery
Numbermore details

The maximum distance in units of outSpatialReference used for generalizing geometries returned by the query operation.

more detailsTopFeaturesQuery
Numbermore details

The number of features to retrieve.

more detailsTopFeaturesQuery
Number[]more details

An array of ObjectIDs to be used to query for features in a layer.

more detailsTopFeaturesQuery
String[]more details

One or more field names used to order the query results.

more detailsTopFeaturesQuery
String[]more details

Attribute fields to include in the FeatureSet.

more detailsTopFeaturesQuery
SpatialReferencemore details

The spatial reference for the returned geometry.

more detailsTopFeaturesQuery
Booleanmore details

If true, each feature in the returned FeatureSet includes the geometry.

more detailsTopFeaturesQuery
Booleanmore details

If true, and returnGeometry is true, then m-values are included in the geometry.

more detailsTopFeaturesQuery
Booleanmore details

If true, and returnGeometry is true, then z-values are included in the geometry.

more detailsTopFeaturesQuery
Stringmore details

For spatial queries, this parameter defines the spatial relationship to query features in the layer or layer view against the input geometry.

more detailsTopFeaturesQuery
Numbermore details

The zero-based index indicating where to begin retrieving features.

more detailsTopFeaturesQuery
TimeExtentmore details

A time extent for a temporal query against time-aware layers.

more detailsTopFeaturesQuery
TopFiltermore details

The topFilter parameter is used to set the groupByFields, orderByFields, and topCount criteria used in generating the result.

more detailsTopFeaturesQuery
Stringmore details

The unit for calculating the buffer distance when distance is specified in spatial queries.

more detailsTopFeaturesQuery
Stringmore details

A where clause for the query.

more detailsTopFeaturesQuery

Property Details

cacheHint Boolean

Indicates if the service should cache the query results. It only applies if the layer's capabilities.query.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
declaredClass Stringreadonly inherited

The name of the class. The declared class name is formatted as esri.folder.className.

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.

geometry Geometryautocast

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 Number

Specifies the number of decimal places for geometries returned by the query operation.

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 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 of num is 10. If neither num nor start properties are provided, then the default value of num is equal to the maxRecordCount of the service, which can be found at the REST endpoint of the FeatureLayer.

objectIds Number[]

An array of ObjectIDs to be used to query for features in a layer.

orderByFields String[]

One or more field names used to order the query results. Specify ASC (ascending) or DESC (descending) after the field name to control the order. The default order is ASC.

See also:
Example:
query.orderByFields = ["STATE_NAME DESC"];
outFields String[]

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 and ObjectId 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 and useStandardizedQueries 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" ]
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 Boolean

If true, each feature in the returned FeatureSet includes the geometry.

Default Value:false
returnM Boolean

If true, and returnGeometry is true, then m-values are included in the geometry.

returnZ Boolean

If true, and returnGeometry is true, then z-values are included in the geometry.

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.

intersects

The contains spatial relationship returns features in the layer view that are completely contained by the query geometry.

contains

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.

crosses

The envelope-intersects spatial relationship returns features in the layer view that intersect the envelope (or extent) of the filter geometry.

envelope-intersects

The overlaps spatial relationship returns features in the layer view that overlap the query geometry. Only features of the same geometry can be compared.

overlaps

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.

touches

The within spatial relationship returns features in the layer view that completely contain the query geometry. In other words, the filter geometry is completely within the features in the layer view. It is opposite of contains.

within

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, and disjoint 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
Example:
const query = new TopFeaturesQuery({
  spatialRelationship: "contains",
  geometry: extent,
  topFilter: new TopFilter({
    topCount: 3,
    groupByFields: ["State"],
    orderByFields: ["Pop_total DESC"]
  })
});
start Number

The zero-based index indicating where to begin retrieving features. This property should 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.

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
   });
topFilter TopFilterautocast

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 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 is true.

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 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.

Examples:
query.where = `NAME = ${stateName}`;
query.where = `POP04 > ${population}`;

Method Overview

Name Return Type Summary Class
TopFeaturesQuerymore details

Creates a deep clone of TopFeaturesQuery object.

more detailsTopFeaturesQuery
*more details

Creates a new instance of this class and initializes it with values from a JSON object generated from an ArcGIS product.

more detailsTopFeaturesQuery
Objectmore details

Converts an instance of this class to its ArcGIS portal JSON representation.

more detailsTopFeaturesQuery

Method Details

clone(){TopFeaturesQuery}

Creates a deep clone of TopFeaturesQuery object.

Returns:
Type Description
TopFeaturesQuery A new instance of a TopFeaturesQuery 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 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.

Parameter:
json Object

A 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() guide topic for more information.

Returns:
Type Description
Object The ArcGIS portal JSON representation of an instance of this class.

Your browser is no longer supported. Please upgrade your browser for the best experience. See our browser deprecation post for more details.