---
title: "Query a Spatial Index"
url: "https://docs.ravendb.net/6.2/indexes/querying/spatial"
version: "6.2"
language: "php"
---

# Query a Spatial Index

> Client language: PHP. Also available for [C#](https://docs.ravendb.net/6.2/indexes/querying/spatial.md), [Python](https://docs.ravendb.net/6.2/indexes/querying/spatial.python.md), [Node.js](https://docs.ravendb.net/6.2/indexes/querying/spatial.nodejs.md), [Java](https://docs.ravendb.net/6.2/indexes/querying/spatial.java.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> - Documents that contain spatial data can be queried by spatial queries that employ geographical criteria.  
>   You have two options:
>
>   - **Dynamic spatial query**  
>     Either make a dynamic spatial query on a collection (see [how to make a spatial query](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-make-a-spatial-query.md)).  
>     An auto-index will be created by the server.
>
>   - **Spatial index query**  
>     Or, index your documents' spatial data in a static-index (see [indexing spatial data](https://docs.ravendb.net/6.2/indexes/indexing-spatial-data.php.md))  
>     and then make a spatial query on this index ( **described in this article** ).
>
> - A few examples of querying a spatial index are provided below.  
>   **A spatial query performed on a static-index is similar to the** [dynamic spatial query](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-make-a-spatial-query.md).  
>   Find all spatial API methods listed [here](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-make-a-spatial-query.md#spatial-api).
>
> - Examples in this page:
>   - [Search by radius](#search-by-radius)
>   - [Search by shape](#search-by-shape)
>   - [Sort results](#sort-results)

## Search by radius

- Query the spatial index:

- Use the `withinRadius` method to search for all documents containing spatial data that is located  
  within the specified distance from the given center point.

### Query

```php
// Define a spatial query on index 'Events_ByNameAndCoordinates'
/** @var array<Event> $employeesWithinRadius */
$employeesWithinRadius = $session
  ->query(Event::class, Events_ByNameAndCoordinates::class)
   // Call 'Spatial' method
  ->spatial(
      // Pass the spatial index-field containing the spatial data
      "Coordinates",
      // Set the geographical area in which to search for matching documents
      // Call 'withinRadius', pass the radius and the center points coordinates
      function ($criteria) { return $criteria->withinRadius(20, 47.623473, -122.3060097); })
  ->toList();

// The query returns all matching Event entities
// that are located within 20 kilometers radius
// from point (47.623473 latitude, -122.3060097 longitude).
```

### documentQuery

```php
// Define a spatial query on index 'Events_ByNameAndCoordinates'
$employeesWithinRadius = $session->advanced()
  ->documentQuery(Event::class, Events_ByNameAndCoordinates::class)
   // Call 'Spatial' method
  ->spatial(
      // Pass the spatial index-field containing the spatial data
      "Coordinates",
      // Set the geographical area in which to search for matching documents
      // Call 'WithinRadius', pass the radius and the center points coordinates
      function($criteria) { return $criteria->withinRadius(20, 47.623473, -122.3060097); })
  ->toList();

// The query returns all matching Event entities
// that are located within 20 kilometers radius
// from point (47.623473 latitude, -122.3060097 longitude).
```

### Index

```php
class Event
{
  private ?string $id = null;
  private ?string $name = null;
  private ?float $latitude = null;
  private ?float $longitude = null;

  public function getId(): ?string
  {
      return $this->id;
  }

  public function setId(?string $id): void
  {
      $this->id = $id;
  }

  public function getName(): ?string
  {
      return $this->name;
  }

  public function setName(?string $name): void
  {
      $this->name = $name;
  }

  public function getLatitude(): ?float
  {
      return $this->latitude;
  }

  public function setLatitude(?float $latitude): void
  {
      $this->latitude = $latitude;
  }

  public function getLongitude(): ?float
  {
      return $this->longitude;
  }

  public function setLongitude(?float $longitude): void
  {
      $this->longitude = $longitude;
  }
}

class Events_ByNameAndCoordinates extends AbstractIndexCreationTask
{
  public function __construct()
  {
      parent::__construct();

      $this->map = "docs.Events.Select(e => new { " .
          "    name = e.name, " .
          "    coordinates = this.CreateSpatialField(((double ? ) e.latitude), ((double ? ) e.longitude)) " .
          "})";
  }
}
```

### RQL

```sql
from index "Events/ByNameAndCoordinates"
where spatial.within(
  Coordinates,
  spatial.circle(20, 47.623473, -122.3060097)
)

// The query returns all matching Event entities
// that are located within 20 kilometers radius
// from point (47.623473 latitude, -122.3060097 longitude).
```

## Search by shape

- Query the spatial index:  
  Use the `RelatesToShape` method to search for all documents containing spatial data that is located  
  in the specified relation to the given shape.

- The shape in the query is specified as either a **circle** or a **polygon** in a WKT format.  
  See polygon rules [here](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-make-a-spatial-query.md#polygonrules).

- The relation to the shape can be one of: `WITHIN`, `CONTAINS`, `DISJOINT`, `INTERSECTS`.

- See more usage examples in the [dynamic search by shape](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-make-a-spatial-query.md#search-by-shape) query.

### Query

```php
// Define a spatial query on index 'EventsWithWKT_ByNameAndWKT'
/** @var array<EventWithWKT> $employeesWithinShape */
$employeesWithinShape = $session
  ->query(EventWithWKT::class, EventsWithWKT_ByNameAndWKT::class)
  // Call 'spatial' method
  ->spatial(
      // Pass the spatial index-field containing the spatial data
      "WKT",
      // Set the geographical search criteria, call 'RelatesToShape'
      function($criteria) { return $criteria->relatesToShape(
          // Specify th   e WKT string
          "POLYGON ((
                         -118.6527948 32.7114894,
                         -95.8040242 37.5929338,
                         -102.8344151 53.3349629,
                         -127.5286633 48.3485664,
                         -129.4620208 38.0786067,
                         -118.7406746 32.7853769,
                         -118.6527948 32.7114894
                    ))",
          // Specify the relation between the WKT shape and the documents spatial data
          SpatialRelation::within()); })
  ->toList();

// The query returns all matching Event entities
// that are located within the specified polygon.
```

### documentQuery

```php
// Define a spatial query on index 'EventsWithWKT_ByNameAndWKT'
/** @var array<EventWithWKT> $employeesWithinShape */
$employeesWithinShape = $session->advanced()
  ->documentQuery(EventWithWKT::class, EventsWithWKT_ByNameAndWKT::class)
  // Call 'Spatial' method
  ->spatial(
      // Pass the spatial index-field containing the spatial data
      "WKT",
      // Set the geographical search criteria, call 'RelatesToShape'
      function($criteria) { return $criteria->relatesToShape(
          // Specify the WKT string
          "POLYGON ((
                 -118.6527948 32.7114894,
                 -95.8040242 37.5929338,
                 -102.8344151 53.3349629,
                 -127.5286633 48.3485664,
                 -129.4620208 38.0786067,
                 -118.7406746 32.7853769,
                 -118.6527948 32.7114894
            ))",
          // Specify the relation between the WKT shape and the documents spatial data
          SpatialRelation::within()); })
  ->toList();

// The query returns all matching Event entities
// that are located within the specified polygon.
```

### Index

```php
class EventWithWKT {
  private ?string $id = null;
  private ?string $name = null;
  private ?string $wkt = null;

  public function getId(): ?string
  {
      return $this->id;
  }

  public function setId(?string $id): void
  {
      $this->id = $id;
  }

  public function getName(): ?string
  {
      return $this->name;
  }

  public function setName(?string $name): void
  {
      $this->name = $name;
  }

  public function getWkt(): ?string
  {
      return $this->wkt;
  }

  public function setWkt(?string $wkt): void
  {
      $this->wkt = $wkt;
  }
}

class EventsWithWKT_ByNameAndWKT extends AbstractIndexCreationTask
{
  public function __construct()
  {
      parent::__construct();

      $this->map = "docs.EventWithWKTs.Select(e => new { " .
          "    name = e.name, " .
          "    wkt = this.CreateSpatialField(e.wkt) " .
          "})";
  }
}
```

### RQL

```sql
from index "EventsWithWKT/ByNameAndWKT"
where spatial.within(
  WKT,
  spatial.wkt("POLYGON ((
      -118.6527948 32.7114894,
      -95.8040242 37.5929338,
      -102.8344151 53.3349629,
      -127.5286633 48.3485664,
      -129.4620208 38.0786067,
      -118.7406746 32.7853769,
      -118.6527948 32.7114894))")
)

// The query returns all matching Event entities
// that are located within the specified polygon.
```

- Note:  
  The index in the above example indexes a WKT string in the spatial index-field.  
  However, you can query by shape also on spatial data that is indexed as lat/lng coordinates.

## Sort results

- Query the spatial index:  
  Use `OrderByDistance` to sort the results by distance from a given point.

- By default, distance in RavenDB measured in **kilometers**.  
  The distance can be rounded to a specific range.

### Query

```php
// Define a spatial query on index 'Events_ByNameAndCoordinates'
/** @var array<Event> $employeesSortedByDistance */
$employeesSortedByDistance = $session
  ->query(Event::class, Events_ByNameAndCoordinates::class)
   // Filter results by geographical criteria
  ->spatial(
      "Coordinates",
      function($criteria) { return $criteria->withinRadius(20, 47.623473, -122.3060097); })
   // Sort results, call 'OrderByDistance'
  ->orderByDistance(
      // Pass the spatial index-field containing the spatial data
      "Coordinates",
      // Sort the results by their distance from this point:
      47.623473, -122.3060097)
  ->toList();

// Return all matching Event entities located within 20 kilometers radius
// from point (47.623473 latitude, -122.3060097 longitude).

// Sort the results by their distance from a specified point,
// the closest results will be listed first.
```

### documentQuery

```php
// Define a spatial query on index 'Events_ByNameAndCoordinates'
/** @var array<Event> $employeesSortedByDistance */
$employeesSortedByDistance = $session->advanced()
  ->documentQuery(Event::class, Events_ByNameAndCoordinates::class)
   // Filter results by geographical criteria
  ->spatial(
      "Coordinates",
      function($criteria) { return $criteria->withinRadius(20, 47.623473, -122.3060097); })
   // Sort results, call 'OrderByDistance'
  ->orderByDistance(
      // Pass the spatial index-field containing the spatial data
      "Coordinates",
      // Sort the results by their distance from this point:
      47.623473, -122.3060097)
  ->toList();

// Return all matching Event entities located within 20 kilometers radius
// from point (47.623473 latitude, -122.3060097 longitude).

// Sort the results by their distance from a specified point,
// the closest results will be listed first.
```

### Index

```php
class Event
{
  private ?string $id = null;
  private ?string $name = null;
  private ?float $latitude = null;
  private ?float $longitude = null;

  public function getId(): ?string
  {
      return $this->id;
  }

  public function setId(?string $id): void
  {
      $this->id = $id;
  }

  public function getName(): ?string
  {
      return $this->name;
  }

  public function setName(?string $name): void
  {
      $this->name = $name;
  }

  public function getLatitude(): ?float
  {
      return $this->latitude;
  }

  public function setLatitude(?float $latitude): void
  {
      $this->latitude = $latitude;
  }

  public function getLongitude(): ?float
  {
      return $this->longitude;
  }

  public function setLongitude(?float $longitude): void
  {
      $this->longitude = $longitude;
  }
}

class Events_ByNameAndCoordinates extends AbstractIndexCreationTask
{
  public function __construct()
  {
      parent::__construct();

      $this->map = "docs.Events.Select(e => new { " .
          "    name = e.name, " .
          "    coordinates = this.CreateSpatialField(((double ? ) e.latitude), ((double ? ) e.longitude)) " .
          "})";
  }
}
```

### RQL

```sql
from index "Events/ByNameAndCoordinates"
where spatial.within(
  Coordinates,
  spatial.circle(20, 47.623473, -122.3060097)
)
order by spatial.distance(
  Coordinates,
  spatial.point(47.623473, -122.3060097)
)

// The query returns all matching Event entities located within 20 kilometers radius
// from point (47.623473 latitude, -122.3060097 longitude).

// Sort the results by their distance from a specified point,
// the closest results will be listed first.
```

- More sorting examples are available in the [dynamic spatial query](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-make-a-spatial-query.md#spatial-sorting) article.

- To get the **distance** for each resulting entity see [get resulting distance](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-make-a-spatial-query.md#getresultingdistance).

## Syntax

```php
object CreateSpatialField(double? lat, double? lng); // Latitude/Longitude coordinates
object CreateSpatialField(string shapeWkt);          // Shape in WKT string format
```

```php
class SpatialOptionsFactory
{
  public function geography(): GeographySpatialOptionsFactory
  {
      return new GeographySpatialOptionsFactory();
  }

  public function cartesian(): CartesianSpatialOptionsFactory
  {
      return new CartesianSpatialOptionsFactory();
  }
}
```

```php
interface GeographySpatialOptionsFactory
{
  // if $circleRadiusUnits is not set SpatialUnits::kilometers() will be used

  // Default is GeohashPrefixTree strategy with maxTreeLevel set to 9
  public function defaultOptions(?SpatialUnits $circleRadiusUnits = null): SpatialOptions;

  public function boundingBoxIndex(?SpatialUnits $circleRadiusUnits = null): SpatialOptions;

  public function geohashPrefixTreeIndex(int $maxTreeLevel, ?SpatialUnits $circleRadiusUnits = null): SpatialOptions;

  public function quadPrefixTreeIndex(int $maxTreeLevel, ?SpatialUnits $circleRadiusUnits = null): SpatialOptions;
}
```

```php
interface CartesianSpatialOptionsFactory
{
  public function boundingBoxIndex(): SpatialOptions;
  public function quadPrefixTreeIndex(int $maxTreeLevel, SpatialBounds $bounds): SpatialOptions;
}

class SpatialBounds
{
  private float $minX;
  private float $maxX;
  private float $minY;
  private float $maxY;

  // ... getters and setters
}
```

## See also

- [Indexing Spatial Data](https://docs.ravendb.net/6.2/indexes/indexing-spatial-data.php.md)
- [How to make a spatial query](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-make-a-spatial-query.md)
- [How to Query a Spatial Index](https://docs.ravendb.net/6.2/indexes/querying/spatial.php.md)
- [Spatial query view](https://docs.ravendb.net/6.2/studio/database/queries/spatial-queries-map-view.md)
