> ## Documentation Index
> Fetch the complete documentation index at: https://docs-relytone.data.cloud/llms.txt
> Use this file to discover all available pages before exploring further.

# PostGIS

> Get started with PostGIS in Relyt ONE for powerful geospatial data analysis and operations.

Relyt ONE integrates **PostGIS 3.5.4** with **GDAL 3.11**, providing industry-leading spatial database capabilities for storing, querying, and analyzing geographic data directly in PostgreSQL.

PostGIS extends PostgreSQL with support for geographic objects, spatial indexes, and hundreds of spatial functions for processing and analyzing vector and raster data.

## Key Features

* **Spatial Data Types**: Support for points, lines, polygons, and complex geometries
* **Coordinate Systems**: Full projection support with thousands of spatial reference systems
* **Spatial Indexing**: High-performance GiST and BRIN indexes for spatial queries
* **Geometry Operations**: Distance calculations, intersections, unions, buffers, and more
* **Standards Compliant**: OGC-compliant implementation of SQL/MM specifications
* **Raster Support**: Store and analyze raster data with GDAL 3.11 integration

## Quick Start

### Step 1: Enable PostGIS Extension

First, enable the PostGIS extension in your database:

```sql theme={null}
CREATE EXTENSION IF NOT EXISTS postgis;
```

Verify the installation and check the version:

```sql theme={null}
SELECT PostGIS_Version();
```

**Expected Output:**

```
3.5 USE_GEOS=1 USE_PROJ=1 USE_STATS=1
```

### Step 2: Create a Spatial Table

Create a table with geometry columns to store spatial data:

```sql theme={null}
CREATE TABLE cities (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100),
  population INTEGER,
  geom GEOMETRY(Point, 4326)
);

COMMENT ON COLUMN cities.id IS 'Primary key, auto-increment';
COMMENT ON COLUMN cities.name IS 'City name';
COMMENT ON COLUMN cities.population IS 'Population count';
COMMENT ON COLUMN cities.geom IS 'Geographic point (longitude, latitude) in WGS84';
```

The `GEOMETRY(Point, 4326)` type specifies:

* `Point`: The geometry type (point, linestring, polygon, etc.)
* `4326`: The SRID (Spatial Reference System Identifier) for WGS84 coordinates

### Step 3: Insert Spatial Data

Insert cities with their geographic coordinates:

```sql theme={null}
INSERT INTO cities (name, population, geom) VALUES
  ('San Francisco', 873965, ST_SetSRID(ST_MakePoint(-122.4194, 37.7749), 4326)),
  ('New York', 8336817, ST_SetSRID(ST_MakePoint(-74.0060, 40.7128), 4326)),
  ('Los Angeles', 3979576, ST_SetSRID(ST_MakePoint(-118.2437, 34.0522), 4326)),
  ('Chicago', 2693976, ST_SetSRID(ST_MakePoint(-87.6298, 41.8781), 4326)),
  ('Seattle', 753675, ST_SetSRID(ST_MakePoint(-122.3321, 47.6062), 4326));
```

You can also use the simpler `ST_Point` function:

```sql theme={null}
INSERT INTO cities (name, population, geom) VALUES
  ('Boston', 692600, ST_GeomFromText('POINT(-71.0589 42.3601)', 4326));
```

### Step 4: Create Spatial Index

Create a spatial index to accelerate spatial queries:

```sql theme={null}
CREATE INDEX cities_geom_idx 
ON cities 
USING GIST (geom);
```

**Benefits:**

* Dramatically improves performance for spatial queries
* Essential for large datasets with millions of geometries
* Uses R-tree-like indexing structure

### Step 5: Basic Spatial Queries

#### Distance Calculations

Find cities within 500 km of San Francisco:

```sql theme={null}
SELECT 
  name, 
  population,
  ST_Distance(
    geom::geography,
    ST_SetSRID(ST_MakePoint(-122.4194, 37.7749), 4326)::geography
  ) / 1000 AS distance_km
FROM cities
WHERE ST_DWithin(
  geom::geography,
  ST_SetSRID(ST_MakePoint(-122.4194, 37.7749), 4326)::geography,
  500000  -- 500 km in meters
)
ORDER BY distance_km;
```

#### Nearest Neighbor Search

Find the 3 closest cities to a given point:

```sql theme={null}
SELECT 
  name,
  ST_Distance(
    geom::geography,
    ST_SetSRID(ST_MakePoint(-118.2437, 34.0522), 4326)::geography
  ) / 1000 AS distance_km
FROM cities
ORDER BY geom <-> ST_SetSRID(ST_MakePoint(-118.2437, 34.0522), 4326)
LIMIT 3;
```

The `<->` operator uses the spatial index for efficient nearest neighbor queries.

### Step 6: Working with Polygons

Create a table for geographic regions:

```sql theme={null}
CREATE TABLE regions (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100),
  geom GEOMETRY(Polygon, 4326)
);
```

Insert a polygon representing a geographic area:

```sql theme={null}
INSERT INTO regions (name, geom) VALUES
  ('Bay Area', ST_GeomFromText(
    'POLYGON((
      -123.0 38.0,
      -122.0 38.0,
      -122.0 37.0,
      -123.0 37.0,
      -123.0 38.0
    ))', 4326
  ));
```

Find cities within a region:

```sql theme={null}
SELECT c.name, c.population
FROM cities c
JOIN regions r ON ST_Contains(r.geom, c.geom)
WHERE r.name = 'Bay Area';
```

### Step 7: Advanced Spatial Operations

#### Buffer Operations

Create a 100 km buffer around a city:

```sql theme={null}
SELECT 
  name,
  ST_Buffer(geom::geography, 100000)::geometry AS buffer_geom
FROM cities
WHERE name = 'San Francisco';
```

#### Area and Distance Calculations

Calculate the area of a polygon in square kilometers:

```sql theme={null}
SELECT 
  name,
  ST_Area(geom::geography) / 1000000 AS area_sq_km
FROM regions;
```

#### Intersection Detection

Check if two geometries intersect:

```sql theme={null}
SELECT 
  c.name AS city,
  r.name AS region
FROM cities c
CROSS JOIN regions r
WHERE ST_Intersects(c.geom, r.geom);
```

#### Centroid Calculation

Find the geometric center of a polygon:

```sql theme={null}
SELECT 
  name,
  ST_AsText(ST_Centroid(geom)) AS centroid
FROM regions;
```

### Step 8: Converting Coordinate Systems

Transform coordinates between different spatial reference systems:

```sql theme={null}
-- Convert from WGS84 (4326) to Web Mercator (3857)
SELECT 
  name,
  ST_AsText(ST_Transform(geom, 3857)) AS mercator_coords
FROM cities
LIMIT 3;
```

### Step 9: Export Spatial Data

Export geometries in various formats:

```sql theme={null}
-- GeoJSON format
SELECT 
  name,
  ST_AsGeoJSON(geom) AS geojson
FROM cities
LIMIT 1;

-- Well-Known Text (WKT)
SELECT 
  name,
  ST_AsText(geom) AS wkt
FROM cities
LIMIT 1;

-- KML format
SELECT 
  name,
  ST_AsKML(geom) AS kml
FROM cities
LIMIT 1;
```

## Common Spatial Functions

| Function        | Description                             | Example                          |
| --------------- | --------------------------------------- | -------------------------------- |
| `ST_Distance`   | Calculate distance between geometries   | `ST_Distance(geom1, geom2)`      |
| `ST_DWithin`    | Check if geometries are within distance | `ST_DWithin(geom1, geom2, 1000)` |
| `ST_Contains`   | Check if geometry contains another      | `ST_Contains(polygon, point)`    |
| `ST_Intersects` | Check if geometries intersect           | `ST_Intersects(geom1, geom2)`    |
| `ST_Buffer`     | Create buffer around geometry           | `ST_Buffer(geom, 1000)`          |
| `ST_Area`       | Calculate area of polygon               | `ST_Area(geom::geography)`       |
| `ST_Length`     | Calculate length of linestring          | `ST_Length(geom::geography)`     |
| `ST_Union`      | Combine multiple geometries             | `ST_Union(geom1, geom2)`         |
| `ST_Centroid`   | Find center point                       | `ST_Centroid(geom)`              |
| `ST_Transform`  | Transform between coordinate systems    | `ST_Transform(geom, 3857)`       |

## Best Practices

1. **Use Geography vs Geometry**: Cast to `geography` type for accurate distance calculations on Earth's surface
2. **Always Create Spatial Indexes**: Essential for performance on large datasets
3. **Specify SRID**: Always specify the spatial reference system (e.g., 4326 for WGS84)
4. **Use Appropriate Functions**: Use `ST_DWithin` instead of `ST_Distance < x` for better performance
5. **Validate Geometries**: Use `ST_IsValid()` to check geometry validity before operations

## Next Steps

* Explore [PostGIS documentation](https://postgis.net/documentation/) for comprehensive function reference
* Learn about [raster data support](https://postgis.net/docs/RT_reference.html) with GDAL
* Check out [topology](https://postgis.net/docs/Topology.html) features for advanced spatial relationships
* Integrate with QGIS, ArcGIS, or other GIS tools using standard PostgreSQL connections

***

For advanced features including 3D geometries, routing, geocoding, and raster analysis, refer to the official [PostGIS documentation](https://postgis.net/docs/).
