Esempio n. 1
1
 public function main(Request $req, Application $app)
 {
     $client = new Client();
     $params = array('index' => 'hrqls', 'type' => 'houseData', 'body' => ['from' => 0, 'size' => 100, 'filter' => array('range' => array('avgHomeValueIndex' => array('gte' => 0))), 'query' => ['match' => ['state' => 'Virginia']]]);
     $results = $client->search($params)['hits']['hits'];
     $responseObject = [];
     $averageHouseValue = array('total' => 0, 'number' => 0);
     $averageTurnover = array('total' => 0, 'number' => 0);
     $maxHouseValue = 0;
     $minHouseValue = 900000;
     foreach ($results as $zip) {
         $averageHouseValue['total'] += $zip['_source']['avgHomeValueIndex'];
         $averageHouseValue['number']++;
         $averageTurnover['total'] += $zip['_source']['turnoverWithinLastYear'];
         $averageTurnover['number']++;
         if ($zip['_source']['avgHomeValueIndex'] > $maxHouseValue) {
             $maxHouseValue = $zip['_source']['averageHouseValue'];
         }
         if ($zip['_source']['averageHouseValue'] < $minHouseValue) {
             $minHouseValue = $zip['_source']['averageHouseValue'];
         }
     }
     $averageHouse = $averageHouseValue['total'] / $averageHouseValue['number'];
     $averageTurn = $averageTurnover['total'] / $averageTurnover['number'];
     $slidervalue = $req->get('slidervalue');
     foreach ($results as $zip) {
         $sliderInfo = $this->calculate($slidervalue);
         $weight = $this->determineWeight($sliderInfo, $zip['_source']['avgHomeValueIndex'], $averageHouse, $maxHouseValue, $minHouseValue);
         $responseObject[] = array('lat' => $zip['_source']['location']['lat'], 'lon' => $zip['_source']['location']['lon'], 'weight' => $weight);
     }
     return new Response(json_encode($responseObject), 200);
 }
 public function findProducts(ListingFilter $filter)
 {
     $must = [];
     if ($filter->getEshop() !== null) {
         $must[] = ["term" => [ProductMeta::ESHOP_ID => (string) $filter->getEshop()->getId()]];
     }
     if ($filter->getCategory() !== null) {
         /** @var Category[] $childrenCategories */
         $childrenCategories = $this->categoryRepository->find([CategoryMeta::PATH => $filter->getCategory()->getId()]);
         $must[] = ["terms" => [ProductMeta::CATEGORY_IDS => array_merge([(string) $filter->getCategory()->getId()], array_map(function (Category $category) {
             return (string) $category->getId();
         }, $childrenCategories))]];
     }
     $body = ["query" => ["filtered" => ["filter" => ["bool" => ["must" => $must]]]], "from" => $filter->getOffset(), "size" => $filter->getLimit(), "sort" => ["_score" => "desc"]];
     if ($filter->getQ() !== null) {
         $body["query"]["filtered"]["query"] = ["multi_match" => ["query" => $filter->getQ(), "fields" => [ProductMeta::NAME . "^5", ProductMeta::LONG_NAME . "^5", ProductMeta::DESCRIPTION, ProductMeta::MANUFACTURER . "^2", ProductMeta::BRAND . "^2", ProductMeta::ESHOP . "." . EshopMeta::NAME . "^2"]]];
     }
     //		if (empty($body["query"]["filtered"]["filter"]["bool"]["must"])) {
     //			unset($body["query"]["filtered"]["filter"]);
     //		}
     $response = $this->elasticsearch->search(["index" => $this->catalogIndexAliasName, "type" => ProductMeta::SHORT_NAME, "body" => $body]);
     if (!isset($response["hits"]["hits"])) {
         throw new \RuntimeException("Response does not have hits->hits. Got: " . json_encode($response));
     }
     $products = [];
     foreach ($response["hits"]["hits"] as $hit) {
         $products[] = ProductMeta::fromArray($hit["_source"], "json:");
     }
     return $products;
 }
 /**
  * @param $searchString
  * @return MarkdownSearchResult[]
  */
 public function searchMarkdownDocuments($searchString)
 {
     $params = array('index' => $this->index, 'type' => self::MARKDOWN_DOCUMENT_TYPE, 'fields' => array('title'));
     $searchStringParts = explode(' ', $searchString);
     foreach ($searchStringParts as $searchStringPart) {
         $params['body']['query']['bool']['should'][]['wildcard']['content'] = $searchStringPart . '*';
     }
     $result = $this->client->search($params);
     $numHits = $result['hits']['total'];
     if ($numHits == 0) {
         return array();
     }
     $searchResults = array();
     foreach ($result['hits']['hits'] as $hit) {
         $searchResult = new MarkdownSearchResult();
         $searchResult->setPath(FilePath::parse($hit['_id']));
         $searchResult->setScore($hit['_score']);
         if (isset($hit['fields'])) {
             if (isset($hit['fields']['title'][0])) {
                 $searchResult->setTitle($hit['fields']['title'][0]);
             }
         }
         $searchResults[] = $searchResult;
     }
     return $searchResults;
 }
Esempio n. 4
0
 /**
  * {@inheritdoc}
  */
 public function search(Searchable $model, $query)
 {
     if (!is_array($query) && ($field = $model->getDefaultSearchField())) {
         $query = [$field => $query];
     }
     return $this->client->search($this->buildSearchQuery($model, $query));
 }
 public function search($needle, $index, array $types, array $options = [])
 {
     $response = $this->client->search(['index' => $index, 'type' => $types, 'body' => ['query' => ['multi_match' => ['query' => $needle, 'type' => 'phrase_prefix', 'fields' => ['_all']]]]]);
     $hits = array_map(function ($hit) {
         return ['id' => $hit['_id'], 'index' => $hit['_index'], 'type' => $hit['_type'], 'data' => $hit['_source']];
     }, $response['hits']['hits']);
     return new SearchResult($hits, $response['hits']['total']);
 }
Esempio n. 6
0
File: Db.php Progetto: toohamster/ws
 /**
  * 查询 结果
  *
  * @param  string $index 索引
  * @param  string $type 类型
  * @param  string $body 查询字符串
  * @param  array  $attrs 额外查询参数
  *
  * @return mixed
  */
 public function search($index, $type, $body, $attrs = [])
 {
     $query = ['index' => $index, 'type' => $type, 'body' => $body];
     if (!empty($attrs)) {
         $query = array_merge($attrs, $query);
     }
     return $this->esClient->search($query);
 }
Esempio n. 7
0
 /**
  *
  * {@inheritdoc}
  *
  */
 public function getParameters(View $view, FormFactoryInterface $formFactoty, Request $request)
 {
     $searchQuery = ['index' => $view->getContentType()->getEnvironment()->getAlias(), 'type' => $view->getContentType()->getName(), 'search_type' => 'count', 'body' => $view->getOptions()['aggsQuery']];
     $retDoc = $this->client->search($searchQuery);
     foreach (explode('.', $view->getOptions()['pathToBuckets']) as $attribute) {
         $retDoc = $retDoc[$attribute];
     }
     return ['keywords' => $retDoc, 'view' => $view, 'contentType' => $view->getContentType(), 'environment' => $view->getContentType()->getEnvironment()];
 }
Esempio n. 8
0
 /**
  * load all options of a facet
  *
  * @param array $facet
  * @return array
  */
 public function getFacet($facet)
 {
     $params = array_replace($this->defaultParams, ['size' => 0, 'body' => ["aggs" => ["facet" => ["terms" => ["field" => $facet['field']]]]]]);
     $results = $this->client->search($params);
     $options = array();
     foreach ($results['aggregations']['facet']['buckets'] as $bucket) {
         $options[] = array('value' => $bucket['key'], 'count' => $bucket['doc_count']);
     }
     return $options;
 }
 /**
  * @param array $terms
  *
  * @return array
  */
 public function search(array $terms, $from = 0, $size = 25, $group = false)
 {
     $params = ['index' => env('ES_INDEX'), 'type' => $this->type, 'body' => ['from' => $from, 'size' => $size, 'query' => ['bool' => ['must' => [], 'should' => ['multi_match' => ['query' => $terms['keyword'], 'fields' => ["scanSpecimenSpeciesCommonName", "scanSpecimenSpeciesScientificName"]]]]]]];
     foreach ($terms['filter'] as $key => $value) {
         $params['body']['query']['bool']['must'][] = ['match' => [$key => $value]];
     }
     if ($group) {
         $params['body']['aggs'] = ["top-scanIds" => ["terms" => ["field" => "scanScanId"], "aggs" => ["top_scanIds_hits" => ["top_hits" => ["sort" => [["_score" => ["order" => "desc"]]], "size" => 1]]]]];
     }
     return $this->client->search($params);
 }
Esempio n. 10
0
 /**
  * @param $glassNamePartial
  * @param int $limit
  * @return array []
  */
 public function glass($glassNamePartial, $limit = 10)
 {
     $params = ['index' => ElasticSearch::INDEX, 'type' => 'supply', 'body' => ['query' => ['match_phrase_prefix' => ['polishName' => ['query' => $glassNamePartial, 'max_expansions' => 10]]], 'filter' => ['prefix' => ['_id' => 'glass.']]]];
     $results = $this->client->search($params);
     if ($results['hits']['total'] === 0) {
         return [];
     }
     $liquids = [];
     foreach ($results['hits']['hits'] as $result) {
         $liquids[] = new Supply($result['_id'], $result['_source']['polishName']);
     }
     return $liquids;
 }
Esempio n. 11
0
 private function searchBlog(Criteria $criteria, Struct\ProductContextInterface $context)
 {
     /**@var $condition SearchTermCondition*/
     $condition = $criteria->getCondition('search');
     $query = $this->createMultiMatchQuery($condition);
     $search = new Search();
     $search->addQuery($query);
     $search->setFrom(0)->setSize(5);
     $index = $this->indexFactory->createShopIndex($context->getShop());
     $params = ['index' => $index->getName(), 'type' => 'blog', 'body' => $search->toArray()];
     $raw = $this->client->search($params);
     return $this->createBlogStructs($raw);
 }
Esempio n. 12
0
 /**
  * {@inheritdoc}
  */
 public function query($string, $offset, $perPage, SearchEngineOptions $options = null)
 {
     $options = $options ?: new SearchEngineOptions();
     $context = $this->context_factory->createContext($options);
     /** @var QueryCompiler $query_compiler */
     $query_compiler = $this->app['query_compiler'];
     $recordQuery = $query_compiler->compile($string, $context);
     $params = $this->createRecordQueryParams($recordQuery, $options, null);
     $params['body']['from'] = $offset;
     $params['body']['size'] = $perPage;
     if ($this->options->getHighlight()) {
         $params['body']['highlight'] = $this->buildHighlightRules($context);
     }
     if ($aggs = $this->getAggregationQueryParams($options)) {
         $params['body']['aggs'] = $aggs;
     }
     $res = $this->client->search($params);
     $results = new ArrayCollection();
     $n = 0;
     foreach ($res['hits']['hits'] as $hit) {
         $results[] = ElasticsearchRecordHydrator::hydrate($hit, $n++);
     }
     /** @var FacetsResponse $facets */
     $facets = $this->facetsResponseFactory->__invoke($res);
     $query['ast'] = $query_compiler->parse($string)->dump();
     $query['query_main'] = $recordQuery;
     $query['query'] = $params['body'];
     $query['query_string'] = json_encode($params['body']);
     return new SearchEngineResult($results, json_encode($query), $res['took'], $offset, $res['hits']['total'], $res['hits']['total'], null, null, $facets->getAsSuggestions(), [], $this->indexName, $facets);
 }
Esempio n. 13
0
 /**
  * {@inheritdoc}
  */
 public function hydrate(array $elasticResult, ProductNumberSearchResult $result, Criteria $criteria, ShopContextInterface $context)
 {
     if (!isset($elasticResult['aggregations'])) {
         return;
     }
     if (!isset($elasticResult['aggregations']['agg_properties'])) {
         return;
     }
     $data = $elasticResult['aggregations']['agg_properties']['buckets'];
     $ids = array_column($data, 'key');
     if (empty($ids)) {
         return;
     }
     $groupIds = $this->getGroupIds($ids);
     $search = new Search();
     $search->addFilter(new IdsFilter($groupIds));
     $search->addFilter(new TermFilter('filterable', 1));
     $search->addSort(new FieldSort('name'));
     $index = $this->indexFactory->createShopIndex($context->getShop());
     $data = $this->client->search(['index' => $index->getName(), 'type' => PropertyMapping::TYPE, 'body' => $search->toArray()]);
     $data = $data['hits']['hits'];
     $properties = $this->hydrateProperties($data, $ids);
     $actives = $this->getFilteredValues($criteria);
     $criteriaPart = $this->createCollectionResult($properties, $actives);
     $result->addFacet($criteriaPart);
 }
Esempio n. 14
0
 /**
  * @param Criteria $criteria
  * @return SearchResultSlice
  */
 public function search(Criteria $criteria)
 {
     $results = $this->client->search($this->parametersBuiler->createParameters($criteria));
     if ($results['hits']['total'] === 0) {
         return new SearchResultSlice($criteria, [], 0);
     }
     $recipes = [];
     foreach ($results['hits']['hits'] as $result) {
         $recipe = new SearchEngine\Result\Recipe($result['_id'], $result['_source']['name'], $result['_source']['description']['text']);
         if (!is_null($result['_source']['publicationDate'])) {
             $recipe->publishedAt(new \DateTimeImmutable($result['_source']['publicationDate']));
         }
         $recipes[] = $recipe;
     }
     return new SearchResultSlice($criteria, $recipes, $results['hits']['total']);
 }
Esempio n. 15
0
 /**
  *
  * {@inheritdoc}
  *
  */
 public function getParameters(View $view, FormFactoryInterface $formFactoty, Request $request)
 {
     try {
         $renderQuery = $this->twig->createTemplate($view->getOptions()['body'])->render(['view' => $view, 'contentType' => $view->getContentType(), 'environment' => $view->getContentType()->getEnvironment()]);
     } catch (\Exception $e) {
         $renderQuery = "{}";
     }
     $searchQuery = ['index' => $view->getContentType()->getEnvironment()->getAlias(), 'type' => $view->getContentType()->getName(), 'body' => $renderQuery, 'size' => $view->getOptions()['size']];
     $result = $this->client->search($searchQuery);
     try {
         $render = $this->twig->createTemplate($view->getOptions()['template'])->render(['view' => $view, 'contentType' => $view->getContentType(), 'environment' => $view->getContentType()->getEnvironment(), 'result' => $result]);
     } catch (\Exception $e) {
         $render = "Something went wrong with the template of the view " . $view->getName() . " for the content type " . $view->getContentType()->getName() . " (" . $e->getMessage() . ")";
     }
     return ['render' => $render, 'view' => $view, 'contentType' => $view->getContentType(), 'environment' => $view->getContentType()->getEnvironment()];
 }
 /**
  * Rewinds the iterator by performing the initial search.
  *
  * The "search_type" parameter will determine if the first "page" contains
  * hits or if the first page contains just a "scroll_id"
  *
  * @return void
  * @see    Iterator::rewind()
  */
 public function rewind()
 {
     $this->clearScroll();
     $this->currentKey = 0;
     $this->currentScrolledResponse = $this->client->search($this->params);
     $this->scrollId = $this->currentScrolledResponse['_scroll_id'];
 }
 public function create()
 {
     $elasticsearch = new Client();
     $sight = $this->sightRepository->getById(Input::get('sight_id'));
     $time = Carbon::now($sight->city->timezone)->hour;
     $searchQuery['index'] = 'sightseeing';
     $searchQuery['type'] = 'sight';
     $searchQuery['body'] = ['min_score' => 0.0001, 'query' => ['function_score' => ['query' => ['bool' => ['must' => [0 => ['range' => ['cost' => ['lte' => Input::get('cost')]]]], 'should' => [0 => ['range' => ['closing_hours' => ['gte' => $time]]], 1 => ['range' => ['opening_hours' => ['lte' => $time]]]]]], 'functions' => [0 => ['gauss' => ['location' => ['origin' => $sight->latitude . ',' . $sight->longitude, 'offset' => '0.5km', 'scale' => '0.1km', 'decay' => 0.33]]]]]]];
     $suggestions = $elasticsearch->search($searchQuery);
     $filteredSuggestions = array();
     $filteredSuggestions['data'] = [];
     foreach ($suggestions['hits']['hits'] as $suggestion) {
         $suggestionAdded = false;
         foreach ($suggestion['_source']['categories'] as $category) {
             if (in_array($category['id'], Input::get('categories')) && !$suggestionAdded && $suggestion['_id'] != Input::get('sight_id')) {
                 $filteredSuggestions['data'][] = ['id' => $suggestion['_id'], 'score' => $suggestion['_score']];
                 $suggestionAdded = true;
             }
         }
     }
     $maxScore = 0;
     foreach ($filteredSuggestions['data'] as $suggestion) {
         if ($suggestion['score'] > $maxScore) {
             $maxScore = $suggestion['score'];
         }
     }
     $filteredSuggestions['max_score'] = $maxScore;
     return $filteredSuggestions;
 }
 public function search($type, $query)
 {
     $params = ['index' => INDEX_NAME, 'type' => $type, 'body' => ['query' => ['match' => $query]]];
     $client = new Client();
     $result = $client->search($params);
     return ["result" => $result["hits"]["hits"]];
 }
 /**
  * Internal method to find a number of documents using an elasticsearch query.
  * A filter and pagination are optional.
  * @param array $query The query to find documents by
  * @param array $filter The filter to filter documents by
  * @param integer $from a from value to use pagination
  * @param integer $limit a limit value to use pagination
  * @return array entities that match the specified query and filter
  */
 protected function findByQuery($query, $filter = null, $from = null, $limit = null)
 {
     $esBody = array('query' => $query);
     if ($filter && is_array($filter)) {
         $esBody['filter'] = $filter;
     }
     if ($from) {
         $esBody['from'] = $from;
     }
     if ($limit) {
         $esBody['size'] = $limit;
     }
     $esQuery = array('index' => $this->index, 'type' => $this->getType(), 'body' => $esBody);
     $result = $this->elasticsearchClient->search($esQuery);
     $hits = $result['hits'];
     if ($hits['total']) {
         $results = $hits['hits'];
         $entities = array();
         foreach ($results as $r) {
             $e = $this->createEntityFromDocument($r);
             $entities[] = $e;
         }
         return $entities;
     } else {
         return array();
     }
 }
 /**
  * @param Orchestration $orchestration
  * @param int $offset
  * @param int $limit
  * @return  Metadata\Job[]
  */
 private function loadOrchestrationSuccessJobs(Orchestration $orchestration, $offset = 0, $limit = 25)
 {
     /**
      * @var ComponentIndex $config
      */
     $config = $this->getContainer()->get('syrup.elasticsearch.current_component_index');
     $orchestrations = $this->loadActiveOrchestrationIds();
     $filter = [];
     $filter[] = ['term' => ['status' => Metadata\Job::STATUS_SUCCESS]];
     $filter[] = ['terms' => ['params.orchestration.id' => array($orchestration->getId())]];
     $query = ['match_all' => []];
     $params = [];
     $params['index'] = $config->getIndexPrefix() . '_syrup_' . KeboolaOrchestratorBundle::SYRUP_COMPONENT_NAME;
     $params['body'] = ['from' => (int) $offset, 'size' => (int) $limit, 'query' => ['filtered' => ['filter' => ['bool' => ['must' => $filter]], 'query' => $query]], 'sort' => ['id' => ['order' => 'desc']]];
     $results = [];
     $hits = $this->elasticSearch->search($params);
     foreach ($hits['hits']['hits'] as $hit) {
         $res = $hit['_source'];
         $res['_index'] = $hit['_index'];
         $res['_type'] = $hit['_type'];
         $res['id'] = (int) $res['id'];
         $results[] = $res;
     }
     $objectEncryptor = $this->objectEncryptor;
     return array_map(function ($line) use($objectEncryptor) {
         return new Metadata\Job($objectEncryptor, $line, $line['_index'], $line['_type']);
     }, $results);
 }
Esempio n. 21
0
 /**
  * @param array $params array of searching params:
  * - projectId
  * - component
  * - runId
  * - query
  * - since
  * - until
  * - offset
  * - limit
  * - status
  * @return array
  */
 public function getJobs(array $params)
 {
     $projectId = null;
     $component = null;
     $runId = null;
     $query = null;
     $since = null;
     $until = null;
     $offset = 0;
     $limit = 100;
     $status = null;
     extract($params);
     $filter = [];
     if ($projectId != null) {
         $filter[] = ['term' => ['project.id' => $projectId]];
     }
     if ($runId != null) {
         $filter[] = ['term' => ['runId' => $runId]];
     }
     if ($status != null) {
         $filter[] = ['term' => ['status' => $status]];
     }
     $queryParam = ['match_all' => []];
     if ($query != null) {
         $queryParam = ['query_string' => ['allow_leading_wildcard' => 'false', 'default_operator' => 'AND', 'query' => $query]];
     }
     $rangeFilter = [];
     if ($since != null) {
         if ($until == null) {
             $until = 'now';
         }
         $rangeFilter = ['range' => ['createdTime' => ['gte' => date('c', strtotime($since)), 'lte' => date('c', strtotime($until))]]];
     }
     if (!empty($rangeFilter)) {
         $filter[] = $rangeFilter;
     }
     $params = ['index' => $this->indexPrefix . '_syrup_' . ($component ?: '*'), 'body' => ['from' => $offset, 'size' => $limit, 'query' => ['filtered' => ['filter' => ['bool' => ['must' => $filter]], 'query' => $queryParam]], 'sort' => ['id' => ['order' => 'desc']]]];
     $results = [];
     $i = 0;
     while ($i < 5) {
         try {
             $hits = $this->client->search($params);
             foreach ($hits['hits']['hits'] as $hit) {
                 $res = $hit['_source'];
                 $res['_index'] = $hit['_index'];
                 $res['_type'] = $hit['_type'];
                 $res['id'] = (int) $res['id'];
                 $results[] = $res;
             }
             return $results;
         } catch (ServerErrorResponseException $e) {
             // ES server error, try again
             $this->log('error', 'Elastic server error response', ['attemptNo' => $i, 'params' => $params, 'exception' => $e]);
         }
         sleep(1 + intval(pow(2, $i) / 2));
         $i++;
     }
     return [];
 }
Esempio n. 22
0
 /**
  * @param string $query
  * @param int    $limit
  *
  * @throws NoSearchResults
  * @return array
  */
 public function search($query, $limit = 10000)
 {
     $searchParams['index'] = self::ELASTICSEARCH_INDEX;
     $searchParams['size'] = $limit;
     $searchParams['body']['query']['query_string'] = ['default_field' => static::$defaultSearchField, 'query' => 'docType:"' . static::$entityName . '" AND ' . str_replace('/', '\\/', $query)];
     $result = $this->es->search($searchParams);
     $docIds = [];
     if (is_array($result)) {
         foreach ($result['hits']['hits'] as $hit) {
             $docIds[] = $hit['_id'];
         }
     }
     if (count($docIds) === 0) {
         throw new NoSearchResults('No ' . static::$entityName . "s matching '{$query}' were found");
     }
     return $docIds;
 }
Esempio n. 23
0
 /**
  * {@inheritdoc}
  */
 public function search(Criteria $criteria, ShopContextInterface $context)
 {
     $search = $this->buildSearch($criteria, $context);
     $index = $this->indexFactory->createShopIndex($context->getShop());
     $data = $this->client->search(['index' => $index->getName(), 'type' => ProductMapping::TYPE, 'body' => $search->toArray()]);
     $products = $this->createProducts($data);
     $result = new ProductNumberSearchResult($products, $data['hits']['total'], []);
     if (isset($data['hits']['max_score'])) {
         $result->addAttribute('elastic_search', new Attribute(['max_score' => $data['hits']['max_score']]));
     }
     foreach ($this->handlers as $handler) {
         if (!$handler instanceof ResultHydratorInterface) {
             continue;
         }
         $handler->hydrate($data, $result, $criteria, $context);
     }
     return $result;
 }
Esempio n. 24
0
 /**
  * @param array $params
  * @return mixed
  */
 public function aggregate(array $params)
 {
     $result = $this->client->search($params);
     //the resultset contains an array of aggregations.
     //if we only have one aggregation, we return an aggregation result,
     //if we have multiple, we'll return a collection of aggregation results.
     //but its always an array, so we can implement the same logic at first
     $aggregations = $result['aggregations'];
     return $aggregations;
 }
Esempio n. 25
0
 /**
  * Search documents in ElasticSearch by the specified criteria
  *
  * @param array $fields
  * @param int   $limit
  * @param bool  $returnPosts
  * @return array
  */
 public function search(array $fields, $limit = 10, $returnPosts = false)
 {
     $results = [];
     $searchParams = ['index' => $this->config->get('index', 'phosphorum'), 'type' => 'post', 'body' => ['fields' => ['id', 'karma'], 'query' => [], 'from' => 0, 'size' => intval($limit)]];
     if (count($fields) == 1) {
         $searchParams['body']['query']['match'] = $fields;
     } else {
         $terms = [];
         foreach ($fields as $field => $value) {
             $terms[] = ['term' => [$field => $value]];
         }
         $searchParams['body']['query']['bool'] = ['must' => $terms];
     }
     try {
         $queryResponse = $this->client->search($searchParams);
         $queryResponse = $this->parseElasticResponse($queryResponse);
         $d = 0.5;
         foreach ($queryResponse as $hit) {
             if (!isset($hit['fields']['id'][0])) {
                 continue;
             }
             $id = $hit['fields']['id'][0];
             $post = Posts::findFirstById($id);
             if (!$post || $post->deleted == Posts::IS_DELETED) {
                 continue;
             }
             if ($hit['fields']['karma'][0] > 0 && ($post->hasReplies() || $post->hasAcceptedAnswer())) {
                 $score = $hit['_score'] * 250 + $hit['fields']['karma'][0] + $d;
                 if (!$returnPosts) {
                     $results[$score] = $this->createPostArray($post);
                 } else {
                     $results[$score] = $post;
                 }
                 $d += 0.05;
             }
         }
     } catch (\Exception $e) {
         $this->logger->error("Indexer: {$e->getMessage()}. {$e->getFile()}:{$e->getLine()}");
     }
     krsort($results);
     return array_values($results);
 }
Esempio n. 26
0
 /**
  * Executes search query in the index.
  *
  * @param array $types             List of types to search in.
  * @param array $query             Query to execute.
  * @param array $queryStringParams Query parameters.
  *
  * @return array
  */
 public function search(array $types, array $query, array $queryStringParams = [])
 {
     $params = [];
     $params['index'] = $this->getIndexName();
     $params['type'] = implode(',', $types);
     $params['body'] = $query;
     if (!empty($queryStringParams)) {
         $params = array_merge($queryStringParams, $params);
     }
     return $this->client->search($params);
 }
 /**
  * @param array $query
  * @param integer $offset
  * @param integer $limit
  * @return Document[]
  */
 private function query(array $query, $offset, $limit)
 {
     $result = $this->client->search(['index' => $this->index, 'type' => $this->type, 'body' => ['query' => $query], 'from' => $offset, 'size' => $limit]);
     if (!array_key_exists('hits', $result)) {
         return [];
     }
     $documentClass = $this->documentClass;
     return array_map(function (array $hit) use($documentClass) {
         return $documentClass::deserialize($hit['_source']);
     }, $result['hits']['hits']);
 }
 /**
  * @Route("/")
  * @Template("DashboardMainBundle:Default:index.html.twig")
  */
 public function index()
 {
     $params = array();
     $params['hosts'] = array('127.0.0.1:9200');
     $client = new Elasticsearch\Client($params);
     $params = array("index" => "dash-mail-*", "type" => "mail", "body" => array("query" => array("filtered" => array("filter" => array("bool" => array("must" => array(array("missing" => array("field" => "flags")), array("term" => array("folderFullName" => "INBOX")))))))));
     $results_mail = $client->search($params);
     $params = array("index" => "dash-rss-*", "type" => "page");
     $results_rss = $client->count($params);
     $params = array("index" => "dash-twitter-*", "type" => "status");
     $results_twitter = $client->count($params);
     return array("mail_unread" => $results_mail['hits']['total'], "rss_total" => $results_rss['count'], "twitter_total" => $results_twitter['count']);
 }
Esempio n. 29
0
 public function search($params = array())
 {
     if (!isset($params['index'])) {
         $params['index'] = $this->getSearchIndex();
     }
     $this->requestToScreen($params, 'SEARCH');
     try {
         return parent::search($params);
     } catch (\Exception $e) {
         $this->registerErrorForException($e);
         return array();
     }
 }
Esempio n. 30
0
 /**
  * @param array $query
  * @param int $offset
  * @param int $limit
  * @return Document[]
  */
 private function query(array $query, int $offset, int $limit) : array
 {
     $params = $this->createParams();
     $params['body'] = ['query' => $query];
     $params['from'] = $offset;
     $params['size'] = $limit;
     $result = $this->client->search($params);
     if (empty($result['hits']['hits'])) {
         return [];
     }
     return array_map(function (array $hit) : Document {
         return $this->serializer->deserialize($this->serializer->serialize($hit['_source']), $this->documentClass);
     }, $result['hits']['hits']);
 }