Module 23 - Querying Feature Layers
Level 5 · Query & Analysis · 🟠 · 4 hours · Prereq: Module 22
What you'll build
A query console: build a query interactively, run it against any of the four query surfaces, see the generated REST request, the response size, and the timing - so the trade-offs stop being abstract.
Plus a queryAll() helper that pages past maxRecordCount correctly.
Why this matters
Every non-trivial map application is mostly queries. Getting them right is the difference between an app that responds in 80 ms and one that downloads 40 MB to count 12 features.
The four query surfaces have genuinely different semantics, and choosing wrongly is the most common performance bug in this SDK.
Concepts
1. The four surfaces
// 1. Layer - hits the SERVICE. Sees all data.
const result = await layer.queryFeatures(query);
// 2. LayerView - runs on features already DOWNLOADED into this view.
const layerView = await view.whenLayerView(layer);
const result = await layerView.queryFeatures(query);
// 3. The REST module - no layer object needed, just a URL.
import * as query from "@arcgis/core/rest/query.js";
const result = await query.executeQueryJSON(SERVICE_URL, params);
// 4. A client-side layer - the layer surface, answered locally.
// Same API, no network. (Module 10.)
layer.queryFeatures |
layerView.queryFeatures |
|
|---|---|---|
| Sees | Everything in the service | Only what's loaded in this view |
| Network | Yes | No |
| Latency | 50-500 ms | < 5 ms |
Respects definitionExpression |
Yes | Yes |
Respects layerView.filter |
No | Yes |
| Statistics | Yes | Yes (over loaded features) |
maxRecordCount |
Applies | N/A |
| Right for | Authoritative answers, big data | Interactive UI over visible data |
The trap: layerView.queryFeatures is fast and returns the wrong answer if you meant "all
the data." A count of features in an extent is fine; a count of features in the whole dataset
is not.
2. The Query object
const query = layer.createQuery(); // pre-populated from the layer's config
query.where = "POPULATION > 50000 AND STATE_NAME = 'Ontario'";
query.geometry = view.extent;
query.spatialRelationship = "intersects";
query.distance = 5;
query.units = "kilometers";
query.outFields = ["NAME", "POPULATION"];
query.returnGeometry = true;
query.orderByFields = ["POPULATION DESC"];
query.num = 100; // page size
query.start = 0; // page offset
query.outSpatialReference = view.spatialReference;
query.maxAllowableOffset = view.resolution; // simplify geometry to a screen pixel
query.returnDistinctValues = false;
query.cacheHint = true; // let the server cache this query
query.timeExtent = { start, end };
const { features, exceededTransferLimit } = await layer.queryFeatures(query);
layer.createQuery() rather than new Query() - it inherits outFields,
definitionExpression, outSpatialReference and gdbVersion from the layer, so your query is
consistent with what the layer already does.
3. The four things that control payload size
query.outFields = ["NAME"]; // 1. fewer fields
query.returnGeometry = false; // 2. no geometry at all
query.maxAllowableOffset = view.resolution; // 3. simplified geometry
query.num = 50; // 4. fewer features
These are the levers. In order of impact for a typical polygon layer:
| Change | Typical reduction |
|---|---|
returnGeometry: false |
90-98% |
maxAllowableOffset at screen resolution |
60-85% |
outFields from ["*"] to 3 fields |
50-80% |
num |
proportional |
If you're populating a table, you almost never need geometry. That one line is the biggest single win available.
4. maxRecordCount and paging
const { features, exceededTransferLimit } = await layer.queryFeatures(query);
if (exceededTransferLimit) {
// There are more. You got the first `maxRecordCount` of them.
}
Most services cap at 1,000 or 2,000. To get everything:
// src/query/queryAll.js
/**
* Page through a query until the service stops returning more.
*
* Requires the service to support pagination - check
* `layer.capabilities.query.supportsPagination` first. Without it, use the
* object-id chunking fallback below.
*
* @param {__esri.FeatureLayer} layer
* @param {object} queryProps
* @param {{pageSize?: number, maxFeatures?: number, signal?: AbortSignal,
* onProgress?: (n: number) => void}} [options]
*/
export async function queryAll(layer, queryProps, options = {}) {
const {
pageSize = layer.capabilities?.query?.maxRecordCount ?? 1000,
maxFeatures = Infinity,
signal,
onProgress,
} = options;
const all = [];
let start = 0;
for (;;) {
signal?.throwIfAborted();
const query = layer.createQuery();
Object.assign(query, queryProps, { num: pageSize, start });
const { features, exceededTransferLimit } =
await layer.queryFeatures(query, { signal });
all.push(...features);
onProgress?.(all.length);
if (all.length >= maxFeatures) return all.slice(0, maxFeatures);
if (!exceededTransferLimit || features.length === 0) return all;
start += features.length;
// A service that ignores `start` would loop forever returning page 1.
// Detect it rather than hanging the browser.
if (start > 1_000_000) {
throw new Error(
"queryAll: over 1,000,000 features fetched - the service may not support paging."
);
}
}
}
/**
* Fallback for services without pagination: fetch object ids (cheap - no
* geometry, no attributes), then request features in id batches.
*/
export async function queryAllByIds(layer, queryProps, options = {}) {
const { batchSize = 500, signal, onProgress } = options;
const idQuery = layer.createQuery();
Object.assign(idQuery, queryProps, { returnGeometry: false, outFields: [] });
const objectIds = await layer.queryObjectIds(idQuery, { signal });
const all = [];
for (let i = 0; i < objectIds.length; i += batchSize) {
signal?.throwIfAborted();
const batch = objectIds.slice(i, i + batchSize);
const query = layer.createQuery();
Object.assign(query, queryProps, { objectIds: batch, where: null, geometry: null });
const { features } = await layer.queryFeatures(query, { signal });
all.push(...features);
onProgress?.(all.length);
}
return all;
}
queryObjectIds is the underused method here. It returns just an array of numbers, so it's
tiny even for a million features, and it gives you the exact count plus the keys to page by.
The runaway guard matters. A service that ignores start returns page 1 forever, and
without the check you fill memory until the tab dies.
5. The lightweight query methods
const count = await layer.queryFeatureCount(query); // a number
const ids = await layer.queryObjectIds(query); // number[]
const extent = await layer.queryExtent(query); // { count, extent }
const related = await layer.queryRelatedFeatures({ relationshipId: 0, objectIds: [1, 2] });
queryExtent is the right way to "zoom to results" - one small request returns the bounding
extent and the count, without downloading a single geometry.
// ❌ downloads every matching feature to compute an extent
const { features } = await layer.queryFeatures({ where });
await view.goTo(features);
// ✅ one tiny request
const { extent, count } = await layer.queryExtent({ where });
if (count > 0) await view.goTo(extent.expand(1.1));
6. Spatial relationships
query.geometry = polygon;
query.spatialRelationship = "intersects";
| Relationship | Matches when |
|---|---|
intersects |
Any shared point. The default and usually right |
contains |
The query geometry fully contains the feature |
within |
The feature fully contains the query geometry |
crosses |
Interiors intersect but neither contains the other |
touches |
Boundaries touch, interiors don't |
overlaps |
Same dimension, partial overlap |
envelope-intersects |
Bounding boxes intersect - fast and approximate |
disjoint |
No shared points |
envelope-intersects is much cheaper than intersects on complex polygons. Use it when a
loose match is acceptable, or as a first pass before a precise one.
contains vs within is asymmetric and people reverse it constantly. Read it as
"queryGeometry contains feature" - the query geometry is the subject.
7. Statistics
import StatisticDefinition from "@arcgis/core/rest/support/StatisticDefinition.js";
const query = layer.createQuery();
query.outStatistics = [
new StatisticDefinition({ statisticType: "count", onStatisticField: "OBJECTID",
outStatisticFieldName: "n" }),
new StatisticDefinition({ statisticType: "sum", onStatisticField: "POPULATION",
outStatisticFieldName: "total" }),
new StatisticDefinition({ statisticType: "avg", onStatisticField: "POPULATION",
outStatisticFieldName: "mean" }),
];
query.groupByFieldsForStatistics = ["STATE_NAME"];
query.orderByFields = ["total DESC"];
const { features } = await layer.queryFeatures(query);
// One feature per group, geometry-less, attributes = the statistics
Types: count, sum, min, max, avg, stddev, var, percentile_cont,
percentile_disc.
This is the single most valuable technique in Level 5. The server aggregates 5 million rows and sends you 50. Module 26 goes deeper.
8. Cancellation
const controller = new AbortController();
const promise = layer.queryFeatures(query, { signal: controller.signal });
controller.abort();
Every SDK request method takes { signal }. Use it for anything driven by user input.
Build it - the query console
Step 1 - The runner
// src/query/runner.js
/**
* Run a query on a chosen surface and report what it cost.
*/
export async function runQuery({ layer, layerView, surface, queryProps, signal }) {
const query = layer.createQuery();
Object.assign(query, queryProps);
const started = performance.now();
let responseBytes = null;
// Measure the actual payload via PerformanceObserver, because the SDK
// doesn't report it and "it felt slow" isn't a measurement.
const observer = observeTransferSize((bytes) => { responseBytes = bytes; });
try {
const target = surface === "layerView" ? layerView : layer;
const result = await target.queryFeatures(query, { signal });
return {
features: result.features,
exceededTransferLimit: result.exceededTransferLimit ?? false,
elapsedMs: Math.round(performance.now() - started),
responseBytes,
surface,
requestUrl: surface === "layer" ? describeRequest(layer, query) : "(client-side)",
};
} finally {
observer?.disconnect();
}
}
function observeTransferSize(onBytes) {
if (typeof PerformanceObserver === "undefined") return null;
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.name.includes("/query")) onBytes(entry.transferSize || entry.encodedBodySize);
}
});
try {
observer.observe({ type: "resource", buffered: false });
return observer;
} catch {
return null;
}
}
/** Reconstruct the REST request so the user can see what was actually sent. */
function describeRequest(layer, query) {
const params = new URLSearchParams({
f: "json",
where: query.where || "1=1",
outFields: (query.outFields ?? ["*"]).join(","),
returnGeometry: String(query.returnGeometry ?? true),
});
if (query.geometry) {
params.set("geometryType", esriGeometryType(query.geometry.type));
params.set("spatialRel", `esriSpatialRel${pascal(query.spatialRelationship ?? "intersects")}`);
}
if (query.num) params.set("resultRecordCount", String(query.num));
if (query.start) params.set("resultOffset", String(query.start));
if (query.maxAllowableOffset) params.set("maxAllowableOffset", String(query.maxAllowableOffset));
if (query.orderByFields?.length) params.set("orderByFields", query.orderByFields.join(","));
return `${layer.url}/${layer.layerId}/query?${params}`;
}
const esriGeometryType = (type) => ({
point: "esriGeometryPoint", polyline: "esriGeometryPolyline",
polygon: "esriGeometryPolygon", extent: "esriGeometryEnvelope",
}[type] ?? "esriGeometryEnvelope");
const pascal = (s) => s.split("-").map((p) => p[0].toUpperCase() + p.slice(1)).join("");
Showing the reconstructed REST URL is the console's most educational feature. Paste it into a browser tab and you see exactly what the server sees. That closes the loop between the JS API and the REST API, and it is how you debug the queries the SDK builds for you.
Step 2 - The comparison experiment
// src/query/compare.js
import { runQuery } from "./runner.js";
const VARIANTS = [
{ name: "Everything", props: { where: "1=1", outFields: ["*"], returnGeometry: true } },
{ name: "No geometry", props: { where: "1=1", outFields: ["*"], returnGeometry: false } },
{ name: "3 fields + geometry", props: { where: "1=1", outFields: ["NAME","POPULATION","ST"], returnGeometry: true } },
{ name: "3 fields, no geometry", props: { where: "1=1", outFields: ["NAME","POPULATION","ST"], returnGeometry: false } },
{ name: "Simplified geometry", props: { where: "1=1", outFields: ["NAME"], returnGeometry: true, maxAllowableOffset: 1000 } },
{ name: "Count only", props: { where: "1=1", outStatistics: [
{ statisticType: "count", onStatisticField: "OBJECTID", outStatisticFieldName: "n" }] } },
];
export async function compareVariants({ layer, layerView }) {
const rows = [];
for (const variant of VARIANTS) {
// Sequential on purpose: parallel requests share bandwidth and the
// timings become meaningless.
const result = await runQuery({ layer, layerView, surface: "layer", queryProps: variant.props });
rows.push({
name: variant.name,
features: result.features.length,
ms: result.elapsedMs,
kb: result.responseBytes ? Math.round(result.responseBytes / 1024) : null,
});
}
return rows;
}
Run this on the US counties layer. Typical shape of the result:
| Variant | Features | ms | KB |
|---|---|---|---|
| Everything | 1000 | 2400 | 8500 |
| No geometry | 1000 | 320 | 410 |
| 3 fields + geometry | 1000 | 2100 | 8100 |
| 3 fields, no geometry | 1000 | 180 | 62 |
| Simplified geometry | 1000 | 640 | 1200 |
| Count only | 1 | 90 | 0.3 |
Geometry dominates. That single observation should change how you write every query for the rest of your career.
Step 3 - A safe where builder
Reuse buildPredicate/combine from Module 21 - the same rules apply. Add:
// src/query/validateWhere.js
/**
* Reject obviously malformed SQL before sending it, so the user gets a useful
* message instead of a 400 with an Esri error code.
*/
export function validateWhere(where, fields) {
if (!where || where.trim() === "") return { valid: true, where: "1=1" };
const fieldNames = new Set(fields.map((f) => f.name.toUpperCase()));
// Unbalanced parentheses
let depth = 0;
for (const char of where) {
if (char === "(") depth++;
if (char === ")") depth--;
if (depth < 0) return { valid: false, error: "Unbalanced closing parenthesis" };
}
if (depth !== 0) return { valid: false, error: "Unbalanced opening parenthesis" };
// Unterminated string
const quotes = (where.match(/'/g) ?? []).length;
if (quotes % 2 !== 0) return { valid: false, error: "Unterminated string literal" };
// Identifiers that aren't fields or keywords
const KEYWORDS = new Set([
"AND","OR","NOT","IN","LIKE","IS","NULL","BETWEEN","DATE","TIMESTAMP",
"UPPER","LOWER","TRUE","FALSE",
]);
const identifiers = where.replace(/'[^']*'/g, "").match(/\b[A-Za-z_][A-Za-z0-9_]*\b/g) ?? [];
const unknown = identifiers.filter(
(id) => !KEYWORDS.has(id.toUpperCase()) && !fieldNames.has(id.toUpperCase())
);
if (unknown.length) {
return { valid: false, error: `Unknown field: ${[...new Set(unknown)].join(", ")}` };
}
return { valid: true, where };
}
Client-side validation isn't security - the server validates too. It's usability. "Unknown field: POPULATON" beats "Unable to complete operation. Error code 400."
Step 4 - Progressive loading with feedback
// src/query/progressive.js
import { queryAll } from "./queryAll.js";
export async function loadAllWithProgress({ layer, queryProps, onProgress, onDone, signal }) {
// Get the count first, so the progress bar can be a real proportion
// rather than a spinner. One tiny request buys a much better UX.
const total = await layer.queryFeatureCount(
Object.assign(layer.createQuery(), queryProps),
{ signal }
);
onProgress({ loaded: 0, total });
const features = await queryAll(layer, queryProps, {
signal,
onProgress: (loaded) => onProgress({ loaded, total }),
});
onDone(features);
return features;
}
How it works
What the SDK sends
layer.queryFeatures(query) becomes an HTTP request to <layer url>/query. The SDK chooses
GET or POST based on URL length - a long where or a complex geometry goes as POST.
The response is Esri JSON (or PBF if the service supports it and the SDK negotiates it - which is significantly smaller for geometry-heavy responses).
You can replay any query by hand. Take the reconstructed URL from the console you just built, paste it in a browser, and change parameters. This is the fastest way to understand a service that's behaving oddly.
Why maxAllowableOffset is so effective
It applies Douglas-Peucker simplification server-side before serialising. A county boundary with 4,000 vertices at 1 m precision, simplified to a 1,000 m tolerance, might keep 80 vertices.
Set it to view.resolution and the simplification is invisible - you're discarding detail
finer than one screen pixel.
query.maxAllowableOffset = view.resolution;
Two caveats:
- Never for geometry you'll store or analyse. The simplified shape is not the real shape.
- Adjacent polygons can develop slivers between them after independent simplification.
Why queryFeatureCount is nearly free
The server runs the where and spatial filter against its index and returns a row count. No
geometry serialisation, no attribute assembly, no JSON of any size.
On an indexed field it's a fraction of a full query's cost. Always use it when you only need "how many."
Why the LayerView query can't see everything
The LayerView holds features the renderer downloaded for the current extent and scale, capped by what the service returned. It is a cache of what's drawn, not a copy of the dataset.
Zoom out and features drop out of it. Apply a definitionExpression and they never enter.
Hit maxRecordCount and you have a truncated set.
So: layerView.queryFeatures for "what's on screen", layer.queryFeatures for "what's
true."
Common mistakes
outFields: ["*"] everywhere.
The default that costs the most.
returnGeometry: true when populating a table.
90%+ of the payload for nothing.
Downloading features to compute an extent.
queryExtent does it in one small request.
Downloading features to count them.
queryFeatureCount.
Ignoring exceededTransferLimit.
Your "all features" is the first 1,000 and you don't know it.
Paging without a runaway guard.
A service that ignores start loops forever.
layerView.queryFeatures for an authoritative answer.
Sees only what's drawn.
No signal.
Stale responses arrive out of order.
Reversing contains and within.
The query geometry is the subject of the verb.
Exercises
Exercise 23.1 - Complete the console
Build the full tool:
- Layer URL input
wherebuilder with field/operator/value pickers and validation- Spatial filter: current extent, drawn polygon, or none
- Toggles for
outFields,returnGeometry,maxAllowableOffset,num - Surface selector (layer / layerView)
- Result table, timing, payload size, and the reconstructed REST URL
- A warning when
exceededTransferLimitis true
Exercise 23.2 - The payload table
Run compareVariants against three layers of different geometry types: a point layer, a line
layer, and a complex polygon layer.
Produce the table for each and write one paragraph on how geometry complexity changes the ranking. Keep this - it's the evidence for every optimisation argument you'll make.
Exercise 23.3 - Page a large layer
Find a service with more than 10,000 features. Then:
- Query it naively and observe
exceededTransferLimit - Use
queryAllwith progress feedback - Use
queryAllByIdsand compare timing - Add cancellation and verify that aborting mid-way stops the requests
Record how long each approach takes for 25,000 features.
Exercise 23.4 - Relationship queries
Find a service with a relationship class (many ArcGIS Hub inspection datasets have one).
- Query the parent features
- Use
queryRelatedFeaturesto get children for 10 parents - Compare against 10 separate queries with a
whereclause - Note what
queryRelatedFeaturesdoes aboutmaxRecordCountper parent
Checkpoint
- What are the four query surfaces, and which sees all the data?
- What single change usually cuts a query's payload the most?
- How do you zoom to query results without downloading them?
- What does
exceededTransferLimit: truemean, and what do you do about it? - Why does
maxAllowableOffset = view.resolutionlook identical to full detail? - When is
layerView.queryFeaturesthe wrong choice? - Why guard a paging loop with a maximum?
layer.queryFeatures(service),layerView.queryFeatures(loaded features in one view), therest/querymodule (a URL, no layer object), and a client-side layer (local). Only the layer/REST surfaces see all the data.returnGeometry: false- geometry is typically 90%+ of a feature query's bytes.layer.queryExtent(query)returns{ count, extent }in one small request.- The service truncated at
maxRecordCount; you have a partial result. Page withnum/start, or fetch object ids and request in batches. - It simplifies geometry to a tolerance finer than one screen pixel, so the discarded detail was never visible.
- Whenever you need an authoritative answer over the whole dataset - counts, statistics, or selection outside the current extent.
- A service that ignores
resultOffsetreturns page 1 forever; without a guard the loop fills memory until the tab dies.
Further reading
- https://developers.arcgis.com/javascript/latest/api-reference/esri-rest-support-Query.html
- https://developers.arcgis.com/rest/services-reference/enterprise/query-feature-service-layer/ - every REST parameter
- https://developers.arcgis.com/javascript/latest/sample-code/featurelayerview-query/