/** * Creates new record of the given module and returns its formatted representation * * @param ServiceBase $api * @param array $args API arguments * * @return array Formatted representation of the bean * @throws SugarApiExceptionInvalidParameter * @throws SugarApiExceptionMissingParameter * @throws SugarApiExceptionNotAuthorized */ public function findNear(ServiceBase $api, array $args) { if (empty($args['location']) || empty($args['lat_long'])) { throw new SugarApiExceptionMissingParameter("Missing location"); } $modules = !empty($args['module']) ? array($args['module']) : $this->getValidModules(); // Load global search engine $engine = $this->getEngine(); $iName = $engine->getReadIndexName($modules); $client = $engine->getClient(); $index = $client->getIndex($iName); $query = new Elastica\Query\MatchAll(); $search = new Elastica\Search($client); $search->addIndex($index); foreach ($modules as $module) { $search->addType($module); } if (!empty($args['distance'])) { $filter = new Elastica\Filter\GeoDistance('lat_long_c', $args['location'], $args['distance']); $query = new Elastica\Query\Filtered($query, $filter); } //Add sort $query = Elastica\Query::create($query); $query->addSort(array('_geo_distance' => array("lat_long_c" => $args['location'], "order" => "asc", "unit" => "mi"))); $results = $search->search($query)->getResults(); $ret = array(); foreach ($results as $result) { $dist = $result->getParam("sort"); $module = $result->getType(); $bean = $this->formatBeanFromResult($api, $args, $result, BeanFactory::getBean($module)); $bean['_distance'] = $dist[0]; $bean['_distance_unit'] = 'mi'; $ret[] = $bean; } return $ret; }
/** * @param CM_Elasticsearch_Type_Abstract[] $types * @param array|null $data * @return array */ public function query(array $types, array $data = null) { if (!$this->getEnabled()) { return array(); } $this->getServiceManager()->getDebug()->incStats('search', json_encode($data)); $client = $this->getRandomClient(); $search = new Elastica\Search($client); foreach ($types as $type) { $search->addIndex($type->getIndex()); $search->addType($type->getType()); } try { $response = $client->request($search->getPath(), 'GET', $data); } catch (Elastica\Exception\ConnectionException $ex) { foreach ($client->getConnections() as $connection) { $connection->setEnabled(); } throw $ex; } return $response->getData(); }