public function findArticles($params) { $query = $params['query']; # берем основу слов, если нету собственных имен (заглавных) if (!preg_match('/[A-Z]/', $query) && !preg_match('/[А-Я]/u', $query)) { $query = $this->lingua->stem_string($query); } # каждое слово дополняется с конца звездочкой (wildcard) $words = explode(' ', $query); $query = implode('* ', $words) . '*'; $client = new \Elasticsearch\Client(); $searchParams['index'] = 'evrika'; $searchParams['type'] = 'article'; $searchParams['body']['from'] = $params['from']; $searchParams['body']['size'] = $params['size']; $searchParams['body']['query']['filtered']['query']['query_string']['query'] = $query; $searchParams['body']['query']['filtered']['query']['query_string']['default_operator'] = 'OR'; $searchParams['body']['query']['filtered']['filter']['term']['enabled'] = true; $searchParams['body']['query']['filtered']['filter']['term']['type'] = $params['type'] == 'event' ? 'event' : 'publication'; if ($params['order'] == 'created') { $searchParams['body']['query']['filtered']['query']['query_string']['fields'] = array('title', 'shortText', 'body'); $searchParams['body']['sort']['created'] = 'desc'; } else { $searchParams['body']['query']['filtered']['query']['query_string']['fields'] = array('title^15', 'shortText^5', 'body^1'); } $retDoc = $client->search($searchParams); return $retDoc; }
public function buscar($q, $tipos, $limit = NULL, $start = NULL) { $client_params = array('hosts' => $this->config->item('elasticsearch_hosts')); $types = ''; $campos = array(); $ultimo = count($tipos); $ultimo_tipo = $tipos[$ultimo - 1]; $client = new Elasticsearch\Client($client_params); foreach ($tipos as $tipo) { if ($tipo == $ultimo_tipo) { $types .= $tipo; $campos = array_merge($campos, $this->get_campos($tipo)); } else { $types .= $tipo . ','; $campos = array_merge($campos, $this->get_campos($tipo)); } } $params['index'] = 'varadouro'; $params['type'] = $types; $filter = array(); $query = array(); if (strlen($q) > 0) { $query['multi_match'] = array('query' => $q, 'fields' => $campos); } else { $query['match_all'] = array(); } $params['body']['from'] = $start; $params['body']['size'] = $limit; $params['body']['highlight'] = array('pre_tags' => array('<span class="highlight">'), 'post_tags' => array('</span>'), 'fields' => array('nome_responsavel' => array('type' => 'plain'), 'atividades_culturais' => array('type' => 'plain'))); $params['body']['query']['filtered'] = array('filter' => $filter, 'query' => $query); $results = $client->search($params); return $results; }
public function indexAction() { $keyword = trim($this->request->getQuery("q")); if (!$keyword) { $tag = new Tag(); $tags = $tag->getPopularTags(30); $this->view->setVar('tags', $tags); return; } $client = new \Elasticsearch\Client(array('hosts' => $this->getDI()->getConfig()->EvaSearch->elasticsearch->servers->toArray())); $searchParams['index'] = 'wallstreetcn'; $type = $this->request->getQuery('type'); $type = in_array($type, array('article', 'wiki', 'livenews')) ? $type : 'article'; $searchParams['type'] = $type; $searchParams['size'] = 15; $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1; $page = $page > 0 ? $page : 1; $searchParams['from'] = ($page - 1) * $searchParams['size']; $searchParams['body']['query']['multi_match'] = array('query' => $keyword, "fields" => array("title", "content"), "tie_breaker" => 0.3); $searchParams['body']['highlight'] = array("fields" => array("title" => array("type" => "plain"), "content" => array("fragment_size" => 50, "number_of_fragments" => 3, "type" => "plain"))); $searchParams['body']['filter'] = array("bool" => array("should" => array("term" => array("status" => "published")))); $searchParams['body']['sort'] = array('createdAt' => array('order' => 'desc'), '_score' => array('order' => 'desc')); $ret = $client->search($searchParams); $this->view->setVar('hits', $ret['hits']); $pager = new PurePaginator($searchParams['size'], $ret['hits']['total'], $ret['hits']['hits']); $this->view->setVar('pager', $pager); $this->view->setVar('keyword', $keyword); }
public function testSniff() { $params['connectionPoolClass'] = '\\Elasticsearch\\ConnectionPool\\SniffingConnectionPool'; $params['connectionPoolParams']['sniffingInterval'] = -10; $params['hosts'] = array($_SERVER['ES_TEST_HOST']); $client = new \Elasticsearch\Client($params); $client->ping(); }
public function highlight() { $client = new Elasticsearch\Client(); $params['body'] = array('_source' => array('profile.female.not_pregnant.a', 'title'), 'query' => array('match' => array('profile.female.not_pregnant.a' => 'v****a')), 'highlight' => array('fields' => array('profile.female.not_pregnant.a' => new \stdClass()))); $results = $client->search($params); $data = array('results' => $results); $this->load->view('welcome_message', $data); }
public static function putMapping() { $config = config('session.elastic', static::$defaultConfig); $ttl = $this->getTTL(); $client = new \Elasticsearch\Client(['hosts' => [$config['url']]]); $mappingParams = ['index' => $config['index'], 'type' => $config['type'], 'body' => ['properties' => ['created' => ['type' => 'date'], 'updated' => ['type' => 'date'], 'data' => ['type' => 'string', 'index' => 'no']], '_ttl' => $ttl ? ['enabled' => true, 'default' => $ttl ?: '30m'] : ['enabled' => false]]]; $client->indices()->putMapping($mappingParams); }
/** * Reverse the migrations. * * @return void */ public function down() { $prefix = \Config::get('reports.prefix'); if ($prefix) { $prefix .= '_'; } $client = new Elasticsearch\Client(); $client->indices()->delete(['index' => $prefix . 'reporter']); }
function requete2($id) { $paramsH['hosts'] = array('5.135.106.169:9200'); $client = new Elasticsearch\Client($paramsH); $params['type'] = 'oeuvre'; $params['index'] = 'arts'; $params['id'] = $id; return $client->get($params); }
public function importMovies(Pio $pio) { $index = 1; $pio_eventclient = $pio->eventClient(); $http_client = new \GuzzleHttp\Client(); $es_client = new \Elasticsearch\Client(); for ($x = 1; $x <= 100; $x++) { $movies_url = 'https://api.themoviedb.org/3/movie/popular?api_key=' . env('TMDB_KEY') . '&page=' . $x; $movies_response = $http_client->get($movies_url); $movies_body = $movies_response->getBody(); $movies_result = json_decode($movies_body, true); $movies = $movies_result['results']; if (!empty($movies)) { foreach ($movies as $row) { $id = $row['id']; $title = $row['title']; $poster_path = ''; if (!empty($row['poster_path'])) { $poster_path = $row['poster_path']; } $moviedetails_url = 'https://api.themoviedb.org/3/movie/' . $id . '?api_key=' . env('TMDB_KEY'); $moviedetails_response = $http_client->get($moviedetails_url); $movie_details_body = $moviedetails_response->getBody(); $movie = json_decode($movie_details_body, true); $overview = $movie['overview']; $release_date = $movie['release_date']; $genre = ''; if (!empty($movie['genres'][0])) { $genre = $movie['genres'][0]['name']; } $popularity = $movie['popularity']; $movie_data = array('itypes' => 1, 'tmdb_id' => $id, 'title' => $title, 'poster_path' => $poster_path, 'overview' => $overview, 'release_date' => $release_date, 'genre' => $genre, 'popularity' => $popularity); $pio_response = $pio_eventclient->setItem($index, $movie_data); //create elasticsearch index $params = array(); $params['body'] = $movie_data; $params['index'] = 'movierecommendation_app'; $params['type'] = 'movie'; $params['id'] = $index; $es_res = $es_client->index($params); /* optional if you want to see what's happening echo "<pre>"; print_r($pio_response); echo "</pre>"; echo "---"; echo "<pre>"; print_r($es_res); echo "</pre>"; echo "<br><br>"; */ $index++; } } } return 'awesome!'; }
public function search($gender, $age, $state = "not_pregnant") { $client = new Elasticsearch\Client(); $searchParams['index'] = 'utano'; $searchParams['type'] = 'sti'; $profile = "profile." . $gender . "." . $state . "." . $age; $searchParams['body'] = array('_source' => 'profile.female.not_pregnant.a', 'query' => array('match_all' => new \stdClass()), 'highlight' => array('fields' => array('profile.female.not_pregnant.a' => new \stdClass()))); $retDoc = $client->search($searchParams); return $retDoc; }
public function delete($postid, $type, $index) { //Delete single value from Elastic //@return bool $client = new Elasticsearch\Client(); $params = array(); $params['type'] = $type; $params['index'] = $index; $params['id'] = $postid; if ($ret = $client->delete($params)) { return 1; } }
private function insertIntoElasticSearch($json) { $client = new Elasticsearch\Client(['hosts' => ['http://localhost:9200']]); $params = []; $params['index'] = 'hrqls'; $params['type'] = 'crimedata'; foreach ($json as $item) { $params['body'][] = array('create' => array('_id' => sha1($item['link']))); $params['body'][] = $item; } print_r($params); $client->bulk($params); }
public function api($key) { $client = new Elasticsearch\Client($this->elastic); $getParams = array(); $getParams['index'] = 'images'; $getParams['type'] = 'string'; $getParams['id'] = $key; $file = $client->get($getParams); $filename = $file['_source']['file_name'] . '.png'; $im = imagecreatefrompng("./uploads/" . $filename); header('Content-Type: image/png'); imagepng($im); }
public function fetchPost($id) { //Fetch Post //@return Encrypted string $client = new Elasticsearch\Client(); $params['index'] = 'blog'; $params['type'] = 'posts'; if (isset($id)) { $params['id'] = $id; } $allData = array(); $results = $client->get($params); $allData['id'] = $id; if (isset($results['_source']['author'])) { $allData['author'] = $results['_source']['author']; } if (isset($results['_source']['title'])) { $allData['title'] = $results['_source']['title']; } if (isset($results['_source']['content'])) { $allData['content'] = $results['_source']['content']; } $allData = json_encode($allData); return $allData; }
public function index() { if (!$this->input->is_cli_request()) { show_error('Acesso não autorizado', 403); } $client_params = array('hosts' => $this->config->item('elasticsearch_hosts')); $client = new Elasticsearch\Client($client_params); try { $client->indices()->delete(array('index' => 'varadouro')); } catch (Exception $e) { echo "Indice não existe, será criado\n"; } $client->indices()->create(array('index' => 'varadouro', 'body' => array('mappings' => array('evento' => array('properties' => array('titulo' => array('type' => 'string'), 'slug' => array('type' => 'string', 'index' => 'not_analyzed'), 'descricao' => array('type' => 'string'), 'data' => array('type' => 'string', 'index' => 'not_analyzed'))), 'noticia' => array('properties' => array('data' => array('type' => 'string', 'index' => 'not_analyzed'), 'titulo' => array('type' => 'string'), 'slug' => array('type' => 'string', 'index' => 'not_analyzed'), 'conteudo' => array('type' => 'string'))), 'espaco_cultural' => array('properties' => array('nome_espaco' => array('type' => 'string'), 'slug' => array('type' => 'string', 'index' => 'not_analyzed'), 'atividades_culturais' => array('type' => 'string'))), 'agente_cultural' => array('properties' => array('nome_responsavel' => array('type' => 'string'), 'slug' => array('type' => 'string', 'index' => 'not_analyzed'), 'atividades_culturais' => array('type' => 'string'))))))); echo "Indexando eventos...\n"; $start = 0; $eventos = $this->eventos_m->get_all(128, $start); while ($eventos) { foreach ($eventos as $evento) { echo "Indexando \"{$evento->id} - {$evento->titulo}\"\n"; $client->index(array('body' => array('titulo' => $evento->titulo, 'slug' => $evento->slug, 'descricao' => strip_tags_better($evento->descricao), 'data' => $evento->data), 'index' => 'varadouro', 'type' => 'evento', 'id' => $evento->id)); } $start += 128; $eventos = $this->eventos_m->get_all(128, $start); } echo "Indexando noticias...\n"; $start = 0; $noticias = $this->noticias_m->get_all(128, $start); while ($noticias) { foreach ($noticias as $noticia) { echo "Indexando \"{$noticia->id} - {$noticia->titulo}\"\n"; $client->index(array('body' => array('data' => $noticia->data, 'titulo' => $noticia->titulo, 'slug' => $noticia->slug, 'conteudo' => strip_tags_better($noticia->conteudo)), 'index' => 'varadouro', 'type' => 'noticia', 'id' => $noticia->id)); } $start += 128; $noticias = $this->noticias_m->get_all(128, $start); } echo "Indexando espaços culturais...\n"; $start = 0; $espacos = $this->espacos_culturais_m->get_all(128, $start); while ($espacos) { foreach ($espacos as $espaco) { echo "Indexando \"{$espaco->id} - {$espaco->nome_espaco}\"\n"; $client->index(array('body' => array('nome_espaco' => $espaco->nome_espaco, 'slug' => $espaco->slug, 'atividades_culturais' => strip_tags_better($espaco->atividades_culturais)), 'index' => 'varadouro', 'type' => 'espaco_cultural', 'id' => $espaco->id)); } $start += 128; $espacos = $this->espacos_culturais_m->get_all(128, $start); } echo "Indexando agentes culturais...\n"; $start = 0; $agentes = $this->agentes_culturais_m->get_all(128, $start); while ($agentes) { foreach ($agentes as $agente) { echo "Indexando \"{$agente->id} - {$agente->nome_responsavel}\"\n"; $client->index(array('body' => array('nome_responsavel' => $agente->nome_responsavel, 'slug' => $agente->slug, 'atividades_culturais' => strip_tags_better($agente->atividades_culturais)), 'index' => 'varadouro', 'type' => 'agente_cultural', 'id' => $agente->id)); } $start += 128; $agentes = $this->agentes_culturais_m->get_all(128, $start); } }
public function main() { set_time_limit(0); $logs = TableRegistry::get('LogLogins'); $params = array(); $params['hosts'] = array('192.168.26.112:9200'); $client = new \Elasticsearch\Client($params); # create a index $params = ['index' => 'mobgame', 'body' => ['settings' => ['number_of_shards' => 3, 'number_of_replicas' => 1], 'mappings' => ['log_logins' => ['properties' => ['user_id' => ['type' => 'integer'], 'created' => ['type' => 'date', 'format' => 'date_time'], 'modified' => ['type' => 'date', 'format' => 'date_time'], 'os' => ['type' => 'string', 'index' => 'not_analyzed'], 'resolution' => ['type' => 'string'], 'sdk_ver' => ['type' => 'string', 'index' => 'not_analyzed'], 'game_id' => ['type' => 'integer'], 'g_ver' => ['type' => 'string'], 'device' => ['type' => 'string', 'index' => 'not_analyzed'], 'network' => ['type' => 'string', 'index' => 'not_analyzed'], 'ip' => ['type' => 'string', 'index' => 'not_analyzed'], 'distributor' => ['type' => 'string', 'index' => 'not_analyzed']]]]]]; try { $client->indices()->create($params); $params['index'] = 'mobgame'; $params['type'] = 'log_logins'; $ret = $client->indices()->getMapping(array('index' => 'mobgame', 'type' => 'log_logins')); } catch (Exception $e) { echo $e->getMessage(); } $i = 0; $offset = 2; do { $this->out('Fetching data... '); $this->out('Offset: ' . $offset * $i); $query = $logs->find()->where(['id >=' => $i * $offset, 'id <' => ($i + 1) * $offset]); $docs = array(); if ($query->count() == 0) { break; } foreach ($query as $row) { $data = $row->toArray(); unset($data['id']); $data['created'] = $data['created']->toISO8601String(); $data['modified'] = $data['modified']->toISO8601String(); $docs['body'] = $data; $docs['index'] = 'mobgame'; $docs['type'] = 'log_logins'; debug($docs); $client->index($docs); $i++; die; } } while (true); }
public function recommendedMovies(Pio $pio) { $recommended_movies = array(); try { $user_id = session('user_id'); $pio_predictionclient = $pio->predictionClient(); $recommended_movies_raw = $pio_predictionclient->sendQuery(array('user' => $user_id, 'num' => 9)); $movie_ids = array_map(function ($item) { return $item['item']; }, $recommended_movies_raw['itemScores']); $es_client = new \Elasticsearch\Client(); $search_params['index'] = 'movierecommendation_app'; $search_params['type'] = 'movie'; $search_params['body']['query']['bool']['must']['terms']['_id'] = $movie_ids; $es_response = $es_client->search($search_params); $recommended_movies = $es_response['hits']['hits']; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } session(array('movies_viewed' => 0, 'user_id' => null)); return view('recommended_movies', array('recommended_movies' => $recommended_movies)); }
private function deleteEntity($config, $entity) { try { $classAttribute = $config->get('mapping')->get('id'); if (method_exists($entity, $method = 'get' . ucfirst($classAttribute))) { $id = $entity->{$method}(); } $params = ['index' => $config->get('index'), 'type' => $config->get('type'), 'id' => $id]; $response = $this->elasticsearchClient->delete($params); } catch (\Exception $e) { var_dump($e); // @todo - Hier müssen genauere Fehlermeldungen rausgehauen werden. Was fehlt denn? Return false die('deleteEntity is failing'); } }
private function desindexar_agente($id) { $client_params = array('hosts' => $this->config->item('elasticsearch_hosts')); $client = new Elasticsearch\Client($client_params); $client->delete(array('index' => 'varadouro', 'type' => 'agente_cultural', 'id' => $id)); }
<?php require '../vendor/autoload.php'; header('Content-type: application/json'); $type = $_REQUEST['type'] ? $_REQUEST['type'] : 'nearstop'; $client = new Elasticsearch\Client(array('hosts' => array('127.0.0.1:9200'))); $mainSearchParams['index'] = 'vehicleevents'; $mainSearchParams['type'] = 'event'; $mainSearchParams['body']['aggs']['vehicleevents']['filter']['not']['filter']['term']['eventType'] = $type; $mainSearchParams['body']['aggs']['vehicleevents']['aggs']['routeevents']['terms']['field'] = 'routeTag'; $mainSearchParams['body']['aggs']['vehicleevents']['aggs']['routeevents']['terms']['size'] = 0; $mainSearchParams['body']['size'] = 0; $mainResults = $client->search($mainSearchParams); echo json_encode($mainResults['aggregations']['vehicleevents']['routeevents']);
/** * Indicates if connection to the search engine is up or not * * @return bool */ public function getStatus() { return $this->_client->ping(); }
/** * @return \Elasticsearch\Namespaces\IndicesNamespace */ protected function _getIndices() { return $this->_client->indices(); }
use Symfony\Component\Yaml\Yaml; // Define some constants define(ROOT_NODE, 'ROOT'); define(SEARCH_CONTEXT_MIN_WEIGHT, 0.8); // WME 13072015: disabled since this is already done in search_settings.php // that one is currently always loaded before this one (see Deltaskin.skin.php) // Load parameters from parameters.yml //$settings = Yaml::parse(file_get_contents(__DIR__ .'/parameters.yml')); //$parameters = $settings['parameters']; // Check if a query was given if (!isset($_GET['q'])) { header("Location: {$indexUrl}"); exit; } // Create an ElasticSearch client $esclient = new Elasticsearch\Client(array('hosts' => array($parameters['elastic.server']))); // Retrieve all contexts $contexts = $esclient->search(array('index' => $parameters['elastic.index'], 'type' => 'context', 'size' => 1000, 'body' => array('query' => array('match_all' => array())))); $contexts = $contexts['hits']['hits']; // Get search results $search_results = $esclient->search(array('index' => $parameters['elastic.index'], 'size' => 100, 'body' => array('query' => array('multi_match' => array('query' => $_GET['q'], 'fields' => array("skos:prefLabel^3", "skos:definition", "title^3", "content", "concerns_readable^2", "context_readable^2")))))); $search_results = $search_results['hits']['hits']; // only take results with VN page $search_results = array_filter($search_results, function ($res) { return count($res['_source']['suggest']['payload']['vn_pages']) > 0; }); // This helper returns the VN page that should be visited // when a link is clicked (if available) function vn_url($source) { if (count($source['suggest']['payload']['vn_pages']) > 0) {
<?php $type = $_REQUEST['type'] ? $_REQUEST['type'] : 'speeding'; $route = $_REQUEST['route']; $index = $_REQUEST['index']; require '../vendor/autoload.php'; header('Content-type: application/json'); $client = new Elasticsearch\Client(array('hosts' => array('127.0.0.1:9200'))); $mainSearchParams['body']['size'] = 0; $filters = array(); $locationField = 'location'; if ($index == 'complaints') { $mainSearchParams['index'] = 'complaints'; $mainSearchParams['type'] = 'complaints'; $locationField = 'point'; $mainSearchParams['body']['aggs']['events']['geohash_grid']['field'] = 'point'; } else { array_push($filters, array('term' => ['eventType' => $type])); $mainSearchParams['index'] = 'vehicleevents'; $mainSearchParams['type'] = 'event'; $mainSearchParams['body']['aggs']['events']['geohash_grid']['field'] = 'location'; } array_push($filters, array('geo_bounding_box' => [$locationField => ['top_left' => ['lat' => 37.850636, 'lon' => -122.551841], 'bottom_right' => ['lat' => 37.665367, 'lon' => -122.276801]]])); if ($route) { array_push($filters, array('term' => ['routeTag' => $route])); } $mainSearchParams['body']['query']['bool']['must'] = $filters; $mainSearchParams['body']['aggs']['events']['geohash_grid']['precision'] = 8; $mainSearchParams['body']['aggs']['events']['geohash_grid']['size'] = 1000; $mainHits = $client->search($mainSearchParams); $maxCount = -1;
function esquery() { global $clientparams; $filter = hextostr($_REQUEST['filter']); $logtype = hextostr($_REQUEST['logtype']); $timestamp = hextostr($_REQUEST['se']); $tests = 0; $msg = ""; // Check timestamps $pattern = '/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\|\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}/'; if (!preg_match($pattern, $timestamp)) { $tests = 1; $msg = "Bad time format!"; } list($start, $end) = explode("|", $timestamp); $start = strtotime($start) . "000"; $end = strtotime($end) . "000"; $now = strtotime("now") . "000"; if ($start > $end || $start == $end || $start > $now) { $tests = 1; $msg = "Bad time logic!"; } // Bail if ts logic isn't sound if ($tests == 1) { $result = array("dbg" => "{$msg}"); $theJSON = json_encode($result); echo $theJSON; exit; } $client = new Elasticsearch\Client($clientparams); $params = array(); $params['size'] = '500'; $params['ignore'] = '400,404'; $json = "{\n \"query\": {\n \"filtered\": {\n \"query\": {\n \"query_string\": {\n \"query\": \"type:{$logtype} AND ({$filter})\"\n}\n},\n \"filter\": {\n \"range\": {\n \"timestamp\": {\n \"from\": {$start},\n \"to\": {$end}\n}\n}\n}\n}\n},\n \"size\": 500,\n \"sort\": [{\n \"timestamp\": {\n \"order\": \"desc\"\n}\n}]\n\n}"; $params['body'] = $json; $result = $client->search($params); /* if ($result[2] == "e") { $result = array("dbg" => "Invalid query!"); } */ $theJSON = json_encode($result); echo $theJSON; }
<?php require_once 'includes.php'; $client = new Elasticsearch\Client(); $jsonString = file_get_contents('amazondata.json'); $documents = json_decode($jsonString, true); $params['index'] = 'flipzon'; $params['type'] = 'docs'; $count = 0; foreach ($documents as $document) { $params['body']['query']['filtered']['query']['bool']['must'] = [['match' => ['title' => $document['title']]], ['match' => ['color' => $document['color']]]]; $params['body']['query']['filtered']['filter']['range']['internal']['gte'] = $document['internal']; $results = $client->search($params); if ($results['hits']['total'] != 0) { //update the document $count++; $id = $results['hits']['hits'][0]['_id']; $price_from_fk = $results['hits']['hits'][0]['_source']['price_from_fk']; unset($params['body']); $params['id'] = $id; $params['body']['doc'] = $document; $client->update($params); unset($params['body']); unset($params['id']); } } echo $count;
<?php require __DIR__ . '/../vendor/autoload.php'; use RecipeSearch\Constants; use RecipeSearch\Util; // Add recipe if one was submitted if (count($_POST) > 0) { // Connect to Elasticsearch (1-node cluster) $esPort = getenv('APP_ES_PORT') ?: 9200; $client = new Elasticsearch\Client(['hosts' => ['localhost:' . $esPort]]); // Convert recipe title to ID $id = Util::recipeTitleToId($_POST['title']); // Check if recipe with this ID already exists $exists = $client->exists(['id' => $id, 'index' => Constants::ES_INDEX, 'type' => Constants::ES_TYPE]); if ($exists) { $message = 'A recipe with this title already exists. You can view it ' . '<a href="/view.php?id=' . $id . '">here</a> or rename your recipe.'; } else { // Index the recipe in Elasticsearch $recipe = $_POST; $recipe['tags'] = Util::recipeTagsToArray($_POST['tags']); $document = ['id' => $id, 'index' => Constants::ES_INDEX, 'type' => Constants::ES_TYPE, 'body' => $recipe]; $client->index($document); // Redirect user to recipe view page $message = 'Recipe added!'; header('Location: /view.php?id=' . $id . '&message=' . $message); exit; } } ?> <html> <head>
private function elastic() { $client = new Elasticsearch\Client(); $results = $client->search(['index' => 'reporter', 'type' => 'reporter', 'size' => 1, 'body' => ['query' => ['match_all' => []], 'sort' => ['time' => ['order' => 'asc']]]]); print_r($results); }
<?php ini_set('error_reporting', E_ALL); ini_set('display_errors', 1); ini_set('display_startup_errors', 1); session_start(); include_once dirname(__FILE__) . '/lib/loaderPHPClass.php'; $client = new Elasticsearch\Client(); $uri = htmlspecialchars($_SERVER['REQUEST_URI']); $topdx = ''; $debug = ''; //Ask a most spoted dx $searchParams['index'] = 'dxspider'; $searchParams['type'] = 'spots'; $searchParams['size'] = 0; $searchParams['body']['query']['filtered']['query']['match_all'] = array(); $searchParams['body']['query']['filtered']['filter']['range']['_timestamp']['gte'] = time() * 1000 - 60 * 60 * 1000; $searchParams['body']['aggs']['topdx']['terms']['field'] = 'dx'; $searchParams['body']['aggs']['topdx']['terms']['size'] = 18; $retDoc = $client->search($searchParams); foreach ($retDoc["aggregations"]["topdx"]["buckets"] as $agg) { $topdx .= "<tr><td><small><a href=\"/?q={$agg["key"]}\">" . $agg["key"] . "</a></small></td><td><small>" . $agg["doc_count"] . "</small></td></tr>"; } //Ask a band activity for last hour $band_data = array(); $band = array("vlf", "160m", "80m", "60m", "40m", "30m", "20m", "17m", "15m", "12m", "10m", "6m", "4m", "2m", "70cm", "23cm", "6cm", "3cm"); foreach ($band as $key => $value) { $searchParams1['index'] = 'dxspider'; $searchParams1['type'] = 'spots'; $searchParams1['body']['filter']['term']['band'] = $value; $searchParams1['body']['query']['range']['_timestamp']['gt'] = 'now-1h';
$app->get('/movies/recommended', 'App\\Http\\Controllers\\HomeController@recommendedMovies'); $app->get('/test', 'App\\Http\\Controllers\\HomeController@test'); $app->get('/aaa', function () { $movies_viewed = session('movies_viewed'); $movies_viewed += 1; if ($movies_viewed == 20) { //$movie['has_recommended'] = true; } session(array('movies_viewed' => $movies_viewed)); return $movies_viewed; }); $app->get('/bbb', function () { return $b + $c; }); $app->get('/es', function () { $es_client = new \Elasticsearch\Client(); /* $response = $client->sendQuery(array('user'=> 1, 'num'=> 3)); $array = array_map(function($item){ return $item['item']; }, $response['itemScores']); */ $searchParams['index'] = 'movierecommendation_app'; $searchParams['type'] = 'movie'; $searchParams['body']['query']['bool']['must']['terms']['_id'] = array(1, 2, 3, 42, 50, 60, 88, 70, 100); $queryResponse = $es_client->search($searchParams); return $queryResponse; }); $app->get('/ya', function () use($app) { $user_id = '55358a20dd477';