Databases Azure Cosmos DB complete template-specs-five-use-cases template-specs-five-use-cases-three-case-studies

Spatial index

A spatial index is an indexing rule that helps Azure Cosmos DB answer location-based questions efficiently. Instead of treating coordinates like ordinary JSON text, the container indexes a GeoJSON property so queries can find nearby points, intersecting areas, or items inside a region. It is useful for maps, delivery zones, assets, devices, and territory searches. The index does not fix bad data models by itself. It works best when the application stores valid geometry, uses a sensible partition key, and queries with supported spatial functions.

Aliases
Cosmos DB spatial index, geospatial index, GeoJSON index, location index
Difficulty
intermediate
CLI mappings
5
Last verified
2026-05-24

Microsoft Learn

Microsoft Learn shows spatial indexes in Azure Cosmos DB indexing policies as path-specific definitions for GeoJSON properties. They support spatial query types such as Point, Polygon, and MultiPolygon so location queries can use the container index instead of scanning every item.

Microsoft Learn: Manage indexing policies in Azure Cosmos DB2026-05-24

Technical context

In Azure Cosmos DB for NoSQL, a spatial index lives inside the container indexing policy. The policy defines included paths, excluded paths, indexing mode, and spatialIndexes entries that target GeoJSON property paths and geometry types. The index interacts with query planning, request unit consumption, write cost, index transformation, and partitioning. Operators usually inspect it through Data Explorer, ARM templates, SDK container properties, or Azure CLI JSON output. It is a data-plane performance feature controlled through a control-plane or SDK configuration document for the container.

Why it matters

Spatial indexes matter because location queries can become expensive very quickly. A fleet, store locator, delivery, insurance, or public-safety application may ask which records are near a point or inside a boundary thousands of times per hour. Without the right spatial index, those queries can consume excessive request units, run slowly, or force awkward application-side filtering. With the right index, the database can evaluate supported spatial predicates more efficiently. The term also matters for governance: teams need to know which property is indexed, which geometry types are valid, and whether an indexing-policy change will increase write cost or trigger transformation work.

Where you see it

Signals, screens, and Azure surfaces where this term usually becomes operational.

Signal 01

In the Cosmos DB container Indexing Policy editor, where spatialIndexes entries show the GeoJSON path and geometry types included for location-aware queries. and deployment review.

Signal 02

In Azure CLI or SDK output for a SQL container, where the indexingPolicy JSON reveals whether spatial index settings drifted from the deployment template. in release gates.

Signal 03

In query metrics and RU charges, where missing or mismatched spatial indexing appears as high request units, throttling, or slow cross-partition location searches. during live incidents.

When this becomes relevant

Specific situations where this term helps solve real Azure design, operations, migration, security, reliability, cost, or governance problems.

  • Power a store, clinic, or depot locator that must find nearby records quickly without scanning every Cosmos DB item.
  • Evaluate delivery zones, service territories, or emergency response boundaries using indexed GeoJSON polygons and point-in-polygon queries.
  • Reduce RU consumption for IoT fleet tracking queries that repeatedly search vehicles, devices, or assets by location.
  • Standardize container indexing policies during migration so spatial queries behave the same in development, test, and production accounts.
  • Prove whether a slow map feature is caused by missing spatial index paths, poor partitioning, or application-side geometry filtering.

Real-world case studies

Different enterprise-style examples that show the term being used to hit measurable objectives.

Case study 01

Courier platform cuts expensive depot searches

Scenario, objectives, solution, measured impact, and takeaway.

Scenario

A same-day courier platform stored driver pings and depot service areas in Cosmos DB. Dispatch maps became sluggish during holiday peaks because every nearby-driver lookup scanned too many documents across partitions.

Business/Technical Objectives
  • Reduce p95 nearby-driver lookup latency below 250 milliseconds.
  • Lower request-unit consumption for map refreshes during peak routing.
  • Keep dispatch data in the existing Cosmos DB account.
  • Create a repeatable indexing policy for new cities.
Solution Using Spatial index

Engineers reviewed the container schema and found that driver coordinates were valid GeoJSON points under a consistent location property, but the indexing policy lacked a spatialIndexes entry for that path. They exported the current policy with Azure CLI, added a reviewed spatial index for Point geometry, and deployed it through the infrastructure pipeline. Query tests were changed to include RU charge, partition scope, and p95 latency. The dispatch service was also updated to include city partition filters before running distance queries. Operators kept the previous policy JSON as rollback evidence and monitored index transformation before routing all peak traffic through the updated container.

Results & Business Impact
  • p95 nearby-driver lookup latency dropped from 740 milliseconds to 180 milliseconds.
  • Average RU charge per map refresh fell by 46 percent.
  • Holiday dispatch screens handled 2.3 times more refreshes without throughput increases.
  • New-city onboarding reused the same indexing-policy template with no emergency portal edits.
Key Takeaway for Glossary Readers

A spatial index is most valuable when it is paired with the right document path, partition filter, and measured query baseline.

Case study 02

Utility outage map survives storm traffic

Scenario, objectives, solution, measured impact, and takeaway.

Scenario

An electric utility used Cosmos DB to power a public outage map. During a storm, customers searched by service polygon, but the map API throttled because boundary queries were not indexed consistently.

Business/Technical Objectives
  • Keep outage-map p95 API responses under one second during storms.
  • Support polygon-based searches for affected service areas.
  • Avoid buying extra throughput as the first mitigation.
  • Document privacy handling for customer location data.
Solution Using Spatial index

The data team discovered that staging had a spatial index for serviceArea geometry while production only had range indexes. They standardized the Cosmos DB indexing policy with spatialIndexes entries for Polygon and MultiPolygon shapes. Azure CLI inventory checks were added to the deployment gate so environment drift would block release. Engineers tested storm-sized documents, query predicates, and partition routing in a load-test account before production rollout. The security team also reviewed logs to make sure full customer coordinates were not written into diagnostic messages. Monitoring dashboards tracked RU charge, throttling, and API latency for boundary searches separately from ordinary account lookups.

Results & Business Impact
  • Storm boundary-search p95 latency improved from 2.8 seconds to 640 milliseconds.
  • Throttled map requests fell by 81 percent during the next major weather event.
  • No additional provisioned throughput was required for the outage-map container.
  • Deployment drift checks found and blocked two later attempts to remove the spatial index.
Key Takeaway for Glossary Readers

Spatial indexing helps public-facing location services stay responsive when geography, traffic, and operational urgency all spike at once.

Case study 03

Travel app fixes inconsistent geofence results

Scenario, objectives, solution, measured impact, and takeaway.

Scenario

A travel-experience app offered location-based recommendations around airports, attractions, and transit hubs. Some geofence searches returned missing results because documents mixed points and multipolygons without a clear indexing policy.

Business/Technical Objectives
  • Return consistent recommendations for supported geofence shapes.
  • Reduce manual application-side filtering after Cosmos DB queries.
  • Create test data that catches invalid geometry before release.
  • Keep recommendation latency low on mobile networks.
Solution Using Spatial index

Architects split the mixed location model into clearly named GeoJSON properties and updated the Cosmos DB indexing policy to include the paths and geometry types the application actually queried. Spatial query tests were added for points near airports, polygons around attractions, and multipolygons representing transit zones. Azure CLI scripts exported container policies from each environment and compared them with the approved JSON file during release. Invalid geometries were rejected at ingestion, and mobile API responses logged RU charge and result counts without exposing precise traveler coordinates. The team kept partition filters aligned with city and experience category to avoid broad cross-partition searches.

Results & Business Impact
  • Incorrect empty geofence responses dropped from 9 percent of searches to less than 1 percent.
  • Mobile recommendation p95 latency improved from 1.4 seconds to 520 milliseconds.
  • Application-side geometry filtering code shrank by 35 percent.
  • Release validation caught three invalid geometry changes before they reached production.
Key Takeaway for Glossary Readers

Spatial indexes work best when data shape, query shape, and deployment automation all agree on the same geography contract.

Why use Azure CLI for this?

With ten years of Azure engineering experience, I use Azure CLI for spatial indexes because indexing policy drift is easy to miss in the portal. A container can look healthy while one environment has a spatialIndexes entry and another does not. CLI can export the exact indexing policy JSON, compare it across accounts, and apply a reviewed policy file during controlled changes. It also helps correlate query cost, throughput, and container configuration during incidents. For spatial workloads, the important evidence is not just whether Cosmos DB exists; it is the path, geometry types, indexing mode, transformation state, and request-unit impact.

CLI use cases

  • Show a Cosmos DB container and extract its indexingPolicy JSON for spatialIndexes review.
  • Update a container with a reviewed indexing-policy file that includes the correct GeoJSON path and geometry types.
  • Compare spatial index settings across development, staging, and production containers before a release.
  • Check provisioned throughput and throttling evidence when spatial queries consume more request units than expected.
  • Export container configuration for an audit that asks how location data is indexed and governed.

Before you run CLI

  • Confirm the account, database, container, partition key, and target subscription before editing any indexing policy.
  • Use show commands first and save the current indexingPolicy JSON so rollback is possible.
  • Check whether the workload uses NoSQL spatial functions and valid GeoJSON before adding index paths.
  • Treat indexing policy updates as performance and cost changes because transformations and writes can consume request units.
  • Coordinate with application owners so query tests run before and after the policy update.

What output tells you

  • The indexingPolicy object shows included paths, excluded paths, indexing mode, and any spatialIndexes entries.
  • The spatialIndexes path identifies the exact GeoJSON property being indexed for location queries.
  • The geometry types show whether points, polygons, or multipolygons are covered by the policy.
  • Container throughput and partition settings help explain whether query cost is an index issue or a capacity issue.
  • Provisioning or transformation-related fields help operators decide whether a policy change is still taking effect.

Mapped Azure CLI commands

Cosmos DB indexing policy commands

direct
az cosmosdb sql container show --account-name <account> --resource-group <resource-group> --database-name <database> --name <container> --query "resource.indexingPolicy"
az cosmosdb sql containerdiscoverDatabases
az cosmosdb sql container update --account-name <account> --resource-group <resource-group> --database-name <database> --name <container> --idx @indexing-policy.json
az cosmosdb sql containerconfigureDatabases
az cosmosdb sql container throughput show --account-name <account> --resource-group <resource-group> --database-name <database> --name <container>
az cosmosdb sql container throughputdiscoverDatabases
az cosmosdb sql container list --account-name <account> --resource-group <resource-group> --database-name <database> --output table
az cosmosdb sql containerdiscoverDatabases
az monitor metrics list --resource <cosmos-account-resource-id> --metric TotalRequestUnits
az monitor metricsdiscoverDatabases

Architecture context

Architecturally, a spatial index is part of the Cosmos DB container design, not a separate service. The application writes GeoJSON documents, the container indexing policy decides which geometry paths are indexed, and query code uses spatial functions against those paths. Partition key design still matters because an index cannot remove every cross-partition cost. In mature designs, architects document the location property, accepted geometry shapes, expected query patterns, RU budget, and indexing policy as one decision. I also expect the deployment template to own the policy, because portal-only edits are hard to review. The architecture is strongest when spatial queries, indexing, partitioning, and throughput are tested together.

Security

Security impact is indirect but real. A spatial index does not grant access by itself, but it can make sensitive location data easier and faster to query once a caller has permission. That matters for vehicles, patients, employees, stores, or critical infrastructure. Access should be controlled through Cosmos DB RBAC, keys, managed identities, private endpoints, network rules, and application authorization. Teams should also classify GeoJSON fields, restrict diagnostic logs that might expose coordinates, and avoid storing more precision than the business needs. Indexing sensitive location data requires the same privacy review as collecting it. Privacy owners should review those choices.

Cost

Spatial indexes affect cost mostly through request units and write overhead. The right index can reduce expensive query scans for geospatial lookups, but maintaining indexes also adds work during writes and indexing transformations. A poorly scoped policy can index unnecessary geometry paths, while a missing index can push applications into high-RU queries or larger provisioned throughput. Cost reviews should compare query RU before and after policy changes, especially for location-heavy workloads. Operators should also consider storage growth from indexing, batch migration cost, and the risk of paying for throughput that only masks a bad indexing strategy. Measure before scaling throughput.

Reliability

Reliability impact appears through predictable query behavior and safe indexing changes. If a production service depends on fast geospatial lookup, removing or misconfiguring the spatial index can cause latency spikes, RU exhaustion, timeouts, or degraded user workflows. Updating indexing policy can trigger index transformation, so operators should plan changes during low-risk windows and monitor progress. Reliability also depends on valid GeoJSON, consistent property paths, and partition-aware query design. Runbooks should include rollback policy JSON, sample spatial queries, expected RU ranges, and alerts for query throttling. The index helps reliability when it keeps location workloads within tested limits. Test before traffic moves.

Performance

Performance impact is direct for location queries. A spatial index helps Cosmos DB evaluate supported spatial predicates against indexed GeoJSON paths instead of relying on inefficient scans or client-side filtering. Query speed still depends on partition key, result size, RU budget, indexing policy, and geometry complexity. Large polygons, cross-partition searches, and inconsistent data shapes can still be slow. Operators should test representative point-in-polygon, distance, and intersection queries with production-like data. They should also monitor RU charge, continuation behavior, throttling, and p95 latency. Spatial indexing is most effective when query patterns are known before the container design is finalized. Test carefully.

Operations

Operators inspect spatial indexes by reading the container indexing policy, reviewing ARM or Bicep templates, checking SDK container properties, and comparing deployed JSON with the approved version. Day-to-day work includes validating geometry paths, watching request-unit consumption, monitoring query latency, and confirming that deployments did not remove spatialIndexes entries. During incidents, teams check whether a new application version changed the GeoJSON shape or query predicate. During migrations, they test representative spatial queries before switching traffic. Good operations keep sample queries, RU baselines, and indexing policy files in source control. They should alert when RU spikes turn location endpoints into customer-facing failures.

Common mistakes

  • Indexing the wrong property path because application documents changed from one GeoJSON field name to another.
  • Assuming a spatial index fixes cross-partition query cost caused by a weak partition-key design.
  • Using invalid geometry or inconsistent coordinate order, then blaming Cosmos DB indexing for bad results.
  • Updating indexing policy in the portal without saving a rollback copy or source-controlled template.
  • Ignoring write RU impact when adding indexes to high-ingest containers with heavy location updates.