コード例 #1
0
 /**
  * Run the search based on the specified search string.
  *
  * @param string $string The string to run the search on.
  * @param int $limit The number of results to limit to.
  * @param int $start The starting result index to search from.
  * @param array $conditions An array of conditions to add to the search filter.
  * @return array An array of search results.
  */
 public function run($string, $limit = 10, $start = 0, array $conditions = array())
 {
     /* sanitize string */
     $string = str_replace(array('!'), '', $string);
     /* @var SolrQuery $query */
     $query = new SolrQuery();
     $query->setQuery($string);
     $query->setStart($start);
     $query->setRows($limit);
     // turn board array into solr-compatible OR argument
     if (isset($conditions['board']) && is_array($conditions['board'])) {
         $c = array();
         foreach ($conditions['board'] as $board) {
             $c[] = $board['id'];
         }
         $conditions['board'] = '(' . implode(' OR ', $c) . ')';
     }
     // @todo rectify this workaround
     // convert author (id) lookup to username (name) lookup
     if (isset($conditions['author']) && isset($_REQUEST['user'])) {
         unset($conditions['author']);
         $conditions['username'] = trim($_REQUEST['user']);
     }
     // allow for non-default Solr requestHandler
     if (isset($this->_searchOptions['requestHandler']) && !empty($this->_searchOptions['requestHandler'])) {
         $this->client->setServlet(SolrClient::SEARCH_SERVLET_TYPE, $this->_searchOptions['requestHandler']);
     } else {
         $query->addField('id')->addField('title')->addField('message')->addField('thread')->addField('board')->addField('category')->addField('author')->addField('username')->addField('replies')->addField('createdon')->addField('board_name')->addField('url')->addField('private');
     }
     foreach ($conditions as $k => $v) {
         $query->addFilterQuery($k . ':' . $v);
     }
     $response = array('total' => 0, 'start' => $start, 'limit' => $limit, 'status' => 0, 'query_time' => 0, 'results' => array());
     try {
         $queryResponse = $this->client->query($query);
         $responseObject = $queryResponse->getResponse();
         if ($responseObject) {
             $response['total'] = $responseObject->response->numFound;
             $response['query_time'] = $responseObject->responseHeader->QTime;
             $response['status'] = $responseObject->responseHeader->status;
             $response['results'] = array();
             if (!empty($responseObject->response->docs)) {
                 foreach ($responseObject->response->docs as $doc) {
                     $d = array();
                     foreach ($doc as $k => $v) {
                         if ($k == 'createdon') {
                             $v = strftime($this->discuss->dateFormat, strtotime($v));
                         }
                         $d[$k] = $v;
                     }
                     $response['results'][] = $d;
                 }
             }
         }
     } catch (Exception $e) {
         $this->modx->log(xPDO::LOG_LEVEL_ERROR, 'Error running query on Solr server: ' . $e->getMessage());
     }
     return $response;
 }
コード例 #2
0
 public function testAutoUpdate()
 {
     $s = new Entity\TestAutoUpdate();
     $s->setContent('Lorem');
     $this->em->persist($s);
     $this->em->flush();
     $query = new \SolrQuery();
     $query->setQuery("id:" . $s->getSolrId());
     $response = $this->client->query($query)->getResponse();
     $this->assertEquals(1, $response->response->numFound);
     $s->setContent('Ipsum');
     $this->em->persist($s);
     $this->em->flush();
     $query = new \SolrQuery();
     $query->setQuery("content:Ipsum");
     $response = $this->client->query($query)->getResponse();
     $this->assertGreaterThanOrEqual(1, $response->response->numFound);
     $query = new \SolrQuery();
     $query->setQuery("id:" . $s->getSolrId());
     $this->em->remove($s);
     $this->em->flush();
     $response = $this->client->query($query)->getResponse();
     $this->assertEquals(0, $response->response->numFound);
 }
コード例 #3
0
ファイル: TK.php プロジェクト: jbree857/Techknowledgy
function getResults($userQuery)
{
    $core = 'techknowledgy_core';
    $options = array('hostname' => 'localhost', 'port' => 8983, 'timeout' => 10, 'path' => '/solr/' . $core);
    $client = new SolrClient($options);
    #if (!$client->ping()) {
    #	exit('Solr service not responding.');
    #}
    #else{
    #	print "Worked!";
    #}
    $query = new SolrQuery();
    $query->setQuery($userQuery);
    $query->setStart(0);
    $query->setRows(1000);
    $query->addField('url')->addField('title')->addField('host')->addField('content');
    $query_response = $client->query($query);
    $response = $query_response->getResponse();
    #print_r($response);
    return $response;
}
コード例 #4
0
ファイル: SolrFacade.php プロジェクト: rmzamora/SolrBundle
 /**
  * @return array found entities
  */
 public function query(AbstractQuery $query)
 {
     $solrQuery = $query->getSolrQuery();
     try {
         $response = $this->solrClient->query($solrQuery);
     } catch (\Exception $e) {
         return array();
     }
     $response = $response->getResponse();
     if (!array_key_exists('response', $response)) {
         return array();
     }
     if ($response['response']['docs'] == false) {
         return array();
     }
     $targetEntity = $query->getEntity();
     $mappedEntities = array();
     foreach ($response['response']['docs'] as $document) {
         $mappedEntities[] = $this->entityMapper->toEntity($document, $targetEntity);
     }
     return $mappedEntities;
 }
コード例 #5
0
<?php

include "bootstrap.php";
$options = array('hostname' => SOLR_SERVER_HOSTNAME, 'login' => SOLR_SERVER_USERNAME, 'password' => SOLR_SERVER_PASSWORD, 'port' => SOLR_SERVER_PORT, 'path' => SOLR_SERVER_PATH);
$client = new SolrClient($options);
$query = new SolrQuery();
$query->setQuery('manu:"Apple Computer Inc." OR text:apple');
$query->setStart(0);
$query->setRows(50);
$query->addField('cat')->addField('features')->addField('id')->addField('timestamp');
$query_response = $client->query($query);
$response = $query_response->getResponse();
print_r($response);
コード例 #6
0
<?php

include "bootstrap.php";
$options = array('hostname' => SOLR_SERVER_HOSTNAME, 'login' => SOLR_SERVER_USERNAME, 'password' => SOLR_SERVER_PASSWORD, 'port' => SOLR_SERVER_PORT, 'path' => SOLR_SERVER_PATH);
$client = new SolrClient($options);
$query = new SolrQuery();
$query->setTerms(true);
$query->setTermsField('cat');
$updateResponse = $client->query($query);
print_r($updateResponse->getResponse());
コード例 #7
0
ファイル: engine.php プロジェクト: kevin-bruton/moodle
 /**
  * Prepares a Solr query, applies filters and executes it returning its results.
  *
  * @throws \core_search\engine_exception
  * @param  stdClass     $filters Containing query and filters.
  * @param  array        $usercontexts Contexts where the user has access. True if the user can access all contexts.
  * @return \core_search\document[] Results or false if no results
  */
 public function execute_query($filters, $usercontexts)
 {
     // Let's keep these changes internal.
     $data = clone $filters;
     // If there is any problem we trigger the exception as soon as possible.
     $this->client = $this->get_search_client();
     $serverstatus = $this->is_server_ready();
     if ($serverstatus !== true) {
         throw new \core_search\engine_exception('engineserverstatus', 'search');
     }
     $query = new \SolrQuery();
     $this->set_query($query, $data->q);
     $this->add_fields($query);
     // Search filters applied, we don't cache these filters as we don't want to pollute the cache with tmp filters
     // we are really interested in caching contexts filters instead.
     if (!empty($data->title)) {
         $query->addFilterQuery('{!field cache=false f=title}' . $data->title);
     }
     if (!empty($data->areaid)) {
         // Even if it is only supposed to contain PARAM_ALPHANUMEXT, better to prevent.
         $query->addFilterQuery('{!field cache=false f=areaid}' . $data->areaid);
     }
     if (!empty($data->timestart) or !empty($data->timeend)) {
         if (empty($data->timestart)) {
             $data->timestart = '*';
         } else {
             $data->timestart = \search_solr\document::format_time_for_engine($data->timestart);
         }
         if (empty($data->timeend)) {
             $data->timeend = '*';
         } else {
             $data->timeend = \search_solr\document::format_time_for_engine($data->timeend);
         }
         // No cache.
         $query->addFilterQuery('{!cache=false}modified:[' . $data->timestart . ' TO ' . $data->timeend . ']');
     }
     // And finally restrict it to the context where the user can access, we want this one cached.
     // If the user can access all contexts $usercontexts value is just true, we don't need to filter
     // in that case.
     if ($usercontexts && is_array($usercontexts)) {
         if (!empty($data->areaid)) {
             $query->addFilterQuery('contextid:(' . implode(' OR ', $usercontexts[$data->areaid]) . ')');
         } else {
             // Join all area contexts into a single array and implode.
             $allcontexts = array();
             foreach ($usercontexts as $areacontexts) {
                 foreach ($areacontexts as $contextid) {
                     // Ensure they are unique.
                     $allcontexts[$contextid] = $contextid;
                 }
             }
             $query->addFilterQuery('contextid:(' . implode(' OR ', $allcontexts) . ')');
         }
     }
     try {
         return $this->query_response($this->client->query($query));
     } catch (\SolrClientException $ex) {
         debugging('Error executing the provided query: ' . $ex->getMessage(), DEBUG_DEVELOPER);
         $this->queryerror = $ex->getMessage();
         return array();
     } catch (\SolrServerException $ex) {
         debugging('Error executing the provided query: ' . $ex->getMessage(), DEBUG_DEVELOPER);
         $this->queryerror = $ex->getMessage();
         return array();
     }
 }
コード例 #8
0
 public function facet_date()
 {
     $options = array('hostname' => SOLR_SERVER_HOSTNAME, 'port' => SOLR_SERVER_PORT);
     $client = new SolrClient($options);
     $query = new SolrQuery('*:*');
     //$query->setQuery('input_datetime:[2010-01-01T00:00:00Z TO 2010-06-01T00:00:00Z]');
     $query->setFacet(TRUE);
     $query->setFacetSort(SolrQuery::FACET_SORT_INDEX);
     $query->setFacetLimit(20000);
     $query->addFacetDateField('input_datetime');
     //$query->setFacetDateStart('2010-06-01T00:00:00Z');
     $query->setFacetDateStart('2008-06-01T00:00:00Z');
     $query->setFacetDateEnd('2010-12-01T00:00:00Z');
     $query->setFacetDateGap('+1MONTH');
     $query->setFacetDateHardEnd(TRUE);
     //$query->setFacetMinCount(2);
     $query->setFacetOffset(0);
     //$query->setFacetDateStart('2012-01-01T00:00:00:Z', 'input_date');
     //$query->setFacetPrefix('c');
     $updateResponse = $client->query($query);
     $response_array = $updateResponse->getResponse();
     $facet_datas = $response_array->facet_counts->facet_fields;
     echo '<pre>';
     print_r($response_array->facet_counts);
 }
コード例 #9
0
<?php

include "bootstrap.php";
$options = array('hostname' => SOLR_SERVER_HOSTNAME, 'login' => SOLR_SERVER_USERNAME, 'password' => SOLR_SERVER_PASSWORD, 'port' => SOLR_SERVER_PORT, 'path' => SOLR_SERVER_PATH);
$client = new SolrClient($options);
$query = new SolrQuery('*:*');
$collapseFunction = new SolrCollapseFunction('manu_id_s');
$collapseFunction->setSize(2)->setNullPolicy(SolrCollapseFunction::NULLPOLICY_IGNORE);
// $collapseFunction->setMax('sum(cscore(),field(A))');
$query->collapse($collapseFunction)->setRows(4);
$queryResponse = $client->query($query);
$response = $queryResponse->getResponse();
print_r($response);
コード例 #10
0
 public static function buildStringCondition(&$conditions, &$values, $field, $param, $model, $join = array(null, null))
 {
     $has_result = false;
     $has_id = false;
     $nb_result = 0;
     $join_result = null;
     $param = urldecode($param);
     if (strlen($param) > 2) {
         if (sfConfig::get('app_solr_enable') == true) {
             /* init solr 
              */
             $max_row = sfConfig::get('app_solr_maxrow');
             $options = array('hostname' => sfConfig::get('app_solr_host'), 'port' => sfConfig::get('app_solr_port'), 'path' => sfConfig::get('app_solr_path'), 'timeout' => sfConfig::get('app_solr_timeout'));
             $client = new SolrClient($options);
             try {
                 // 1st search : exact search
                 $query_solr_exact = new SolrQuery();
                 $query_solr_exact->setQuery('*' . $param . '*');
                 $query_solr_exact->setRows($max_row);
                 if ($model == 'User' || $model == 'UserPrivateData') {
                     if (!sfContext::getInstance()->getUser()->isConnected()) {
                         $query_solr_exact->addFilterQuery('user_private_public:true');
                     }
                 }
                 $query_solr_exact->addFilterQuery('module:' . strtolower($model) . 's');
                 $query_solr_exact->addField('name')->addField('module')->addField('id_doc');
                 $res_exact = $client->query($query_solr_exact)->getResponse();
                 if ($res_exact['response']['numFound'] > 0) {
                     for ($i = 0; $i < $res_exact['response']['numFound']; $i++) {
                         $ids_tmp[]['id'] = $res_exact['response']['docs'][$i]['id_doc'];
                     }
                 } else {
                     // No exact serach ... so try fuzzy search
                     $query_solr = new SolrQuery();
                     // Fuzzy search word > 3 letters
                     $query_words = explode(" ", $param);
                     foreach ($query_words as &$word) {
                         switch (true) {
                             case in_array(strlen($word), range(0, 3)):
                                 $word = $word;
                                 break;
                             case in_array(strlen($word), range(4, 5)):
                                 $word = $word . '~1';
                                 break;
                             case in_array(strlen($word), range(6, 7)):
                                 $word = $word . '~2';
                                 break;
                             case in_array(strlen($word), range(8, 9)):
                                 $word = $word . '~3';
                                 break;
                             default:
                                 $word = $word . '~4';
                                 break;
                         }
                     }
                     $query_search_fuzzy = implode(' ', $query_words);
                     $query_search = "({$param})^20 OR ({$query_search_fuzzy})^5";
                     c2cTools::log(" solr request : " . $query_search);
                     $query_solr->setQuery($query_search);
                     $query_solr->setRows($max_row);
                     if ($model == 'User' || $model == 'UserPrivateData') {
                         if (!sfContext::getInstance()->getUser()->isConnected()) {
                             $query_solr->addFilterQuery('user_private_public:true');
                         }
                     }
                     $query_solr->addFilterQuery('module:' . strtolower($model) . 's');
                     $query_solr->addField('name')->addField('module')->addField('id_doc');
                     $res = $client->query($query_solr)->getResponse();
                     for ($i = 0; $i < $res['response']['numFound']; $i++) {
                         $ids_tmp[]['id'] = $res['response']['docs'][$i]['id_doc'];
                     }
                 }
             } catch (Exception $e) {
                 c2cTools::log(" exception solr : " . $e);
                 $ids_tmp = self::idSearchByName($param, $model);
             }
         } else {
             $ids_tmp = self::idSearchByName($param, $model);
         }
         if (count($ids_tmp)) {
             $ids = array();
             foreach ($ids_tmp as $id) {
                 $ids[] = $id['id'];
             }
             $conditions[] = $field[0] . ' IN (' . implode(',', $ids) . ')';
             $has_result = true;
             $nb_result = count($ids);
             $join_result = $join[0];
             if (!$join[0]) {
                 $has_id = true;
             }
         }
     } else {
         $conditions[] = $field[1] . ' LIKE make_search_name(?)||\'%\'';
         $values[] = $param;
         $has_result = true;
         if ($join[1]) {
             $join_result = $join[1];
         }
     }
     return array('has_result' => $has_result, 'has_id' => $has_id, 'nb_result' => $nb_result, 'join' => $join_result);
 }
コード例 #11
0
<?php

include "bootstrap.php";
$options = array('hostname' => SOLR_SERVER_HOSTNAME, 'login' => SOLR_SERVER_USERNAME, 'password' => SOLR_SERVER_PASSWORD, 'port' => SOLR_SERVER_PORT, 'path' => SOLR_SERVER_PATH);
$client = new SolrClient($options);
$disMaxQuery = new SolrDisMaxQuery();
$disMaxQuery->setStart(0)->setQuery('solr')->setTimeAllowed(500)->setRows(17);
$disMaxQuery->addSortField('price', 0);
$disMaxQuery->setQueryAlt('*:*')->addQueryField('text', 1.5)->addQueryField('title', 5)->addBoostQuery('cat', 'electronics', 2)->setQueryPhraseSlop(1)->setBigramPhraseSlop(3)->addBigramPhraseField('text', 2.5)->addBigramPhraseField('type', 3, 4)->setTrigramPhraseFields('content^0.5 anchor~4^1.5 title^1.2 site^1.5');
$queryResponse = $client->query($disMaxQuery);
$response = $queryResponse->getResponse();
if ($response->response->numFound > 0) {
    $docs = $response->response->docs;
    print_r($docs);
} else {
    echo "No Documents Found" . PHP_EOL;
}