Skip to content

Instantly share code, notes, and snippets.

@binary-data
Created July 13, 2015 06:48
Show Gist options
  • Save binary-data/f1e5608650afea28d4ff to your computer and use it in GitHub Desktop.
Save binary-data/f1e5608650afea28d4ff to your computer and use it in GitHub Desktop.
<?php
class Search extends Controller {
/**
* @var Elasticsearch\Client
*/
private $client;
public function before() {
$this->client = new Elasticsearch\Client();
}
public function index() {
$data['query'] = $query = isset($_GET['search']) ? $_GET['search'] : '';
if (!empty($this->route['params']['slug'])) {
$last_query = ORM::for_table('last_queries')->where('slug', $this->route['params']['slug'])->find_one();
if ($last_query) {
$data['query'] = $query = $last_query->text;
}
}
if (empty($query)) {
$this->notfound404();
}
$data['page'] = $page = isset($_GET['page']) && is_numeric($_GET['page']) ? $_GET['page'] : 1;
$data['limit'] = $limit = $this->config['frontend']['per_page'];
$data['pages_count'] = 0;
$es_query = ['match' =>
[
'_all' => [
'query' => $query,
'fuzziness' => 'AUTO',
'operator' => 'and',
'fuzzy_transpositions' => 'true',
],
],
];
$es_filter = [];
if (isset($_GET['show'])) {
if ($_GET['show'] == 'hits') {
$es_filter['term']['is_hit'] = true;
}
if ($_GET['show'] == 'discount') {
$es_filter['term']['has_discount'] = true;
}
}
$params = [
'index' => $this->key_prefix.ModelSearch::ES_INDEX,
'type' => ModelSearch::ES_TYPE,
'size' => $limit,
'from' => ($page-1)*$limit,
'body' => [
'query' => [
'filtered' => [
'query' => $es_query,
'filter' => $es_filter,
],
],
],
];
$params['body']['sort'] = [
['price' => ['order' => 'asc']],
];
try {
$product_results = $this->client->search($params);
} catch (Exception $e) {}
if (!empty($product_results['hits']['hits'])) {
// Doing other stuff with results array
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment