Skip to content

Instantly share code, notes, and snippets.

@arunchinnachamy
Last active July 25, 2024 11:36
Show Gist options
  • Save arunchinnachamy/35855f01f7b430ce696c to your computer and use it in GitHub Desktop.
Save arunchinnachamy/35855f01f7b430ce696c to your computer and use it in GitHub Desktop.
PHP code to show Location search in SOLR using Solarium. Details can be found at http://www.arunchinnachamy.com/how-to-use-solr-geo-spatial-search/
<?php
//Solarium Installed using composer.
require "vendor/autoload.php";
$config = array(
'endpoint' => array(
'localhost' => array(
'host' => SOLR_IP,
'port' => 8080,
'path' => '/solr/',
'core' => 'TEST_CORE'
)
)
);
$lat = $_GET['lat'];
$long = $_GET['long'];
$client = new Solarium\Client($config);
// get a select query instance and a query helper instance
$query = $client->createSelect();
$helper = $query->getHelper();
$query->setStart(0)->setRows(50);
// add a filterquery to find products in a range of 50km, using the helper to generate the 'geofilt' filter
$query->createFilterQuery('location')->setQuery($helper->geofilt('location', $lat, $long, 50));
// Get the distance as part of document field
$query->setFields(array('*','_dist_:geodist(location,'.$lat.','.$long .')'));
//Sorting the results based on the distance
$query->addSort('geodist(location,'.$lat.','.$long .')', $query::SORT_ASC);
$request = $client->createRequest($query);
//The variable can be used to debug. The variable contains the raw SOLR query
$debugInfo = (string)$request;
// this executes the query and returns the result
$resultset = $client->select($query);
// show documents using the resultset iterator
$results = array();
foreach($resultset as $document) {
$item = array();
foreach($document as $field => $value) {
$item[$field] = $value;
}
$results[] = $item;
}
echo json_encode($results);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment