Spatial Search Tutorial

This is a trivial example to demonstrate Xapiand’s spatial search capabilities. Given any point, find the closest large cities in the US. For this example, a large city incorporates places in the United States with a population of at least 100,000.

Loading the Sample Dataset

The population and location data used in this example is from OpenDataSoft.

You can download the sample dataset. Extract it to our current directory and let’s load it into our cluster as follows:

RESTORE /cities/
Content-Type: application/x-ndjson
@cities.ndjson

Searching

Let’s look for the nearest big cities near El Cerrito, CA, a city neighboring Berkeley in the San Francisco Bay Area.

El Cerrito, CA

The red circle in the map has a radius of 20 km and is at the latitude/longitude of El Cerrito (37.9180233, -122.3198401). The map also shows all trixels that will be searched for (to speed the query up). See Hierarchical Triangular Mesh to find how HTM trixels work.

SEARCH /cities/
{
  "_query": {
    "population": {
      "_in": {
        "_range": {
          "_from": 100000
        }
      }
    },
    "location": {
      "_in": {
        "_circle": {
          "_latitude": 37.9180233,
          "_longitude": -122.3198401,
          "_radius": 20000
        }
      }
    }
  },
  "_selector": "city"
}

Sure enough, Xapiand returns a list of cities in the Bay Area, nearest first:

{
  "total": 5,
  "count": 5,
  "hits": [
    "Richmond",
    "Berkeley",
    "Oakland",
    "San Francisco",
    "Vallejo"
  ]
}

Sorting

It might be that you want to change the reference point for sorting purposes, for example you still might want to get the same cities close to El Cerrito, but this time sorting them by their proximity to San Francisco, CA.

The latitude/longitude of San Francisco is (37.7576171, -122.5776844).

SEARCH /cities/
{
  "_query": {
    "population": {
      "_in": {
        "_range": {
          "_from": 100000
        }
      }
    },
    "location": {
      "_in": {
        "_circle": {
          "_latitude": 37.9180233,
          "_longitude": -122.3198401,
          "_radius": 20000
        }
      }
    }
  },
  "_sort": {
    "location": {
      "_order": "asc",
      "_value": {
        "_point": {
          "_latitude": 37.7576171,
          "_longitude": -122.5776844,
        }
      }
    }
  },
  "_selector": "city"
}

Now Xapiand returns the same cities, but now nearest to San Francisco first.

{
  "total": 5,
  "count": 5,
  "hits": [
    "San Francisco",
    "Oakland",
    "Richmond",
    "Berkeley",
    "Vallejo"
  ]
}