コード例 #1
0
ファイル: WIDlist.php プロジェクト: Tjorriemorrie/app
 protected function getIds()
 {
     $client = new Solarium_Client($this->CONFIG);
     $select = $client->createSelect();
     $select->setRows(20000);
     $select->createFilterQuery('users')->setQuery('activeusers:[0 TO *]');
     $select->createFilterQuery('pages')->setQuery('wikipages:[500 TO *]');
     $select->createFilterQuery('words')->setQuery('words:[10 TO *]');
     $select->createFilterQuery('ns')->setQuery('ns:0');
     $select->createFilterQuery('wam')->setQuery('-(wam:0)');
     $select->createFilterQuery('dis')->setQuery('-(title_en:disambiguation)');
     $select->createFilterQuery('answer_host')->setQuery('-(host:*answers.wikia.com)');
     $select->createFilterQuery('answer')->setQuery('-(hub:Wikianswers)');
     //speedydeletion: 547090, scratchpad: 95, lyrics:43339, colors:32379
     $select->createFilterQuery('banned')->setQuery('-(wid:547090) AND -(wid:95) AND -(wid:43339) AND -(wid:32379)');
     // faceting would be less expensive
     $select->addParam('group', 'true');
     $select->addParam('group.field', 'wid');
     $select->addParam('group.ngroups', 'true');
     $result = $client->select($select);
     $ids = [];
     if (isset($result->getData()['grouped']['wid']['groups'])) {
         foreach ($result->getData()['grouped']['wid']['groups'] as $group) {
             $ids[] = $group['groupValue'];
         }
     }
     return $ids;
 }
コード例 #2
0
ファイル: SolrIndexer.php プロジェクト: KnpLabs/KnpBundles
 /**
  * Delete all bundles from index
  */
 public function deleteBundlesIndexes(Bundle $bundle = null)
 {
     $delete = $this->solarium->createUpdate();
     $delete->addDeleteQuery(null !== $bundle ? $bundle->getFullName() : '*:*');
     $delete->addCommit();
     $this->solarium->update($delete);
 }
コード例 #3
0
 /** Get the latest records back from solr
  *
  */
 public function latestRecordsPublications($q = '*:*', $fields = 'id,old_findID,objecttype,imagedir,filename,thumbnail,broadperiod,workflow', $start = 0, $limit = 4, $sort = 'id', $direction = 'desc')
 {
     $select = array('query' => $q, 'start' => $start, 'rows' => $limit, 'fields' => array($fields), 'sort' => array($sort => $direction), 'filterquery' => array());
     if (!in_array($this->getRole(), $this->_allowed)) {
         $select['filterquery']['workflow'] = array('query' => 'workflow:[3 TO 4]');
     }
     $select['filterquery']['images'] = array('query' => 'thumbnail:[1 TO *]');
     $cachekey = md5($q . $this->getRole() . 'biblio');
     if (!$this->_cache->test($cachekey)) {
         $query = $this->_solr->createSelect($select);
         $resultset = $this->_solr->select($query);
         $data = array();
         $data['numberFound'] = $resultset->getNumFound();
         foreach ($resultset as $doc) {
             $fields = array();
             foreach ($doc as $key => $value) {
                 $fields[$key] = $value;
             }
             $data['images'][] = $fields;
         }
         $this->_cache->save($data);
     } else {
         $data = $this->_cache->load($cachekey);
     }
     return $this->buildHtml($data);
 }
コード例 #4
0
 /** Display of publications with filtration
  */
 public function indexAction()
 {
     $limit = 20;
     $page = $this->_getParam('page');
     if (!isset($page)) {
         $start = 0;
     } else {
         unset($params['page']);
         $start = ($page - 1) * 20;
     }
     $config = array('adapteroptions' => array('host' => '127.0.0.1', 'port' => 8983, 'path' => '/solr/', 'core' => 'beopublications'));
     $select = array('query' => '*:*', 'start' => $start, 'rows' => $limit, 'fields' => array('*'), 'sort' => array('title' => 'asc'), 'filterquery' => array());
     $client = new Solarium_Client($config);
     // get a select query instance based on the config
     $query = $client->createSelect($select);
     $resultset = $client->select($query);
     $data = NULL;
     foreach ($resultset as $doc) {
         foreach ($doc as $key => $value) {
             $fields[$key] = $value;
         }
         $data[] = $fields;
     }
     $paginator = Zend_Paginator::factory($resultset->getNumFound());
     $paginator->setCurrentPageNumber($page)->setItemCountPerPage($limit)->setPageRange(20);
     $this->view->paginator = $paginator;
     $this->view->results = $data;
 }
コード例 #5
0
ファイル: Updater.php プロジェクト: rwebley/Beowulf---PAS
 /** Delete record by ID
  * 
  * @param $id
  */
 public function delete($id)
 {
     $solr = new Solarium_Client(array('adapteroptions' => array('host' => '127.0.0.1', 'port' => 8983, 'path' => '/solr/', 'core' => 'beowulf')));
     $update = $solr->createUpdate();
     $update->addDeleteById('findIdentifier-' . $id);
     $update->addCommit();
     $result = $solr->update($update);
 }
コード例 #6
0
 public function testPostCreateRequestUnalteredPostRequest()
 {
     $query = $this->_client->createUpdate();
     $query->addDeleteById(1);
     $requestOutput = $this->_client->createRequest($query);
     $requestInput = clone $requestOutput;
     $this->_plugin->postCreateRequest($query, $requestOutput);
     $this->assertEquals($requestInput, $requestOutput);
 }
コード例 #7
0
 function handle($args)
 {
     /*
      * Make sure we have a search term.
      */
     if (!isset($args['term']) || empty($args['term'])) {
         json_error('Search term not provided.');
         die;
     }
     /*
      * Clean up the search term.
      */
     $term = filter_var($args['term'], FILTER_SANITIZE_STRING);
     /*
      * Append an asterix to the search term, so that Solr can suggest autocomplete terms.
      */
     $term .= '*';
     /*
      * Intialize Solarium.
      */
     $client = new Solarium_Client($GLOBALS['solr_config']);
     /*
      * Set up our query.
      */
     $query = $client->createSuggester();
     $query->setHandler('suggest');
     $query->setQuery($term);
     $query->setOnlyMorePopular(TRUE);
     $query->setCount(5);
     $query->setCollate(TRUE);
     /*
      * Execute the query.
      */
     $search_results = $client->suggester($query);
     /*
      * If there are no results.
      */
     if (count($search_results) == 0) {
         $response->terms = FALSE;
     } else {
         $response->terms = array();
         foreach ($search_results as $term => $term_result) {
             $i = 0;
             foreach ($term_result as $suggestion) {
                 $response->terms[] = array('id' => $i, 'term' => $suggestion);
                 $i++;
             }
         }
     }
     $this->render($response, 'OK');
 }
コード例 #8
0
ファイル: MoreLikeThis.php プロジェクト: lesleyauk/findsorguk
 /** The constructor
  *
  */
 public function __construct()
 {
     $this->_cache = Zend_Registry::get('cache');
     $this->_config = Zend_Registry::get('config');
     $this->_solrConfig = array('adapteroptions' => $this->_config->solr->toArray());
     $this->_solr = new Solarium_Client($this->_solrConfig);
     $this->_solr->setAdapter('Solarium_Client_Adapter_ZendHttp');
     $loadbalancer = $this->_solr->getPlugin('loadbalancer');
     $master = $this->_config->solr->master->toArray();
     $slave = $this->_config->solr->slave->toArray();
     $loadbalancer->addServer('master', $master, 100);
     $loadbalancer->addServer('slave', $slave, 200);
     $loadbalancer->setFailoverEnabled(true);
 }
コード例 #9
0
 /** Get the solr data
  * @access public
  * @return array
  */
 public function getSolrResults()
 {
     $query = $this->_solr->createSelect();
     $query->setRows(0);
     $stats = $query->getStats();
     $stats->createField('quantity');
     $resultset = $this->_solr->select($query);
     $data = $resultset->getStats();
     $stats = array();
     // Create array of data for use in partial
     foreach ($data as $result) {
         $stats['total'] = $result->getSum();
         $stats['records'] = $result->getCount();
     }
     return $stats;
 }
コード例 #10
0
ファイル: SolrResponse.php プロジェクト: lesleyauk/findsorguk
 /** Get records from solr
  * @access public
  * @return array
  */
 public function getRecords($cursor = 0, $set, $from, $until)
 {
     $fields = array('id', 'old_findID', 'creator', 'description', 'broadperiod', 'thumbnail', 'imagedir', 'filename', 'created', 'institution', 'updated', 'objecttype', 'fourFigure', 'fromdate', 'todate', 'county', 'district', 'materialTerm', 'knownas', 'secondaryMaterialTerm', 'fourFigureLat', 'fourFigureLon');
     $select = array('query' => '*:*', 'start' => $cursor, 'rows' => self::LISTLIMIT, 'fields' => $fields, 'sort' => array('created' => 'asc'), 'filterquery' => array());
     if (!in_array($this->getRole(), $this->_allowed)) {
         $select['filterquery']['workflow'] = array('query' => 'workflow:[3 TO 4]');
     }
     if (isset($set)) {
         $select['filterquery']['set'] = array('query' => 'institution:' . $set);
     }
     if (isset($from)) {
         $select['filterquery']['from'] = array('query' => 'created:[' . $this->todatestamp($from) . ' TO * ]');
     }
     if (isset($until)) {
         $select['filterquery']['until'] = array('query' => 'created:[* TO ' . $this->todatestamp($until) . ']');
     }
     $query = $this->_solr->createSelect($select);
     $resultset = $this->_solr->select($query);
     $data = array();
     $data['numberFound'] = $resultset->getNumFound();
     foreach ($resultset as $doc) {
         $fields = array();
         foreach ($doc as $key => $value) {
             $fields[$key] = $value;
         }
         $data['finds'][] = $fields;
     }
     return $data;
 }
コード例 #11
0
 /** Find objects recorded with proximity to SMRs within a certain distance
  * of a lat lon pair, this is set up to work in kilometres from point. You
  * can adapt this for miles. This perhaps can be swapped out for a SOLR
  * based search in future.
  * @access public
  * @param double $lat
  * @param double $long
  * @param integer $distance
  * @return array
  */
 public function getSMRSNearbyFinds($lat, $lon, $distance)
 {
     $config = $this->_config->solr->asgard->toArray();
     $config['core'] = 'objects';
     $solr = new Solarium_Client(array('adapteroptions' => $config));
     $select = array('query' => '*:*', 'fields' => array('*'), 'filterquery' => array());
     $query = $solr->createSelect($select);
     $helper = $query->getHelper();
     $query->createFilterQuery('geofilt')->setQuery($helper->geofilt($lat, $lon, 'coordinates', $distance));
     $resultset = $solr->select($query);
     $data = array();
     foreach ($resultset as $document) {
         $data[] = array('id' => $document['id'], 'old_findID' => $document['old_findID'], 'county' => $document['county'], 'broadperiod' => $document['broadperiod']);
     }
     return $data;
 }
コード例 #12
0
ファイル: PingCommand.php プロジェクト: danquah/solr-tester
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->input = $input;
     $this->output = $output;
     $parts = parse_url($input->getArgument('url'));
     $config = array('adapteroptions' => array('host' => $parts['host'], 'port' => isset($parts['port']) ? $parts['port'] : 80, 'path' => $parts['path']));
     $client = new \Solarium_Client($config);
     $ping = $client->createPing();
     $q_start = microtime(TRUE);
     $response = $client->execute($ping);
     $client_query_time = round((microtime(TRUE) - $q_start) * 1000, 1) . 'ms';
     $body = $response->getResponse()->getBody();
     if (!empty($body)) {
         $data = json_decode($body);
         $status = isset($data->status) ? $data->status : 'Unknown';
         $server_query_time = isset($data->responseHeader->QTime) ? $data->responseHeader->QTime . 'ms' : 'Unknown';
         $output->writeln("Ping status {$status} completed in (client/server) {$client_query_time}/{$server_query_time}");
     }
 }
コード例 #13
0
 /**
  * @param integer $start
  * @param integer $count
  * @return array
  */
 public function listPageCounts($start, $count)
 {
     $query = $this->solariumClient->createSelect();
     $query->setQuery("(ns:0)");
     $query->getGrouping()->addField("wid");
     $query->setStart($start);
     $query->setRows($count);
     $query->addSort('wid', Solarium_Query_Select::SORT_ASC);
     $resultSet = $this->solariumClient->select($query);
     $results = [];
     foreach ($resultSet->getGrouping()->getGroups() as $group) {
         /** @var Solarium_Result_Select_Grouping_FieldGroup $group */
         foreach ($group as $groupElement) {
             /** @var Solarium_Result_Select_Grouping_ValueGroup $groupElement */
             $results[] = new WikiPageCountModel($groupElement->getValue(), $groupElement->getNumFound());
         }
     }
     return $results;
 }
コード例 #14
0
 public function testCreateQueryPostPlugin()
 {
     $type = Solarium_Client::QUERYTYPE_SELECT;
     $options = array('optionA' => 1, 'optionB' => 2);
     $query = $this->_client->createQuery($type, $options);
     $observer = $this->getMock('Solarium_Plugin_Abstract', array(), array($this->_client, array()));
     $observer->expects($this->once())->method('postCreateQuery')->with($this->equalTo($type), $this->equalTo($options), $this->equalTo($query));
     $this->_client->registerPlugin('testplugin', $observer);
     $this->_client->createQuery($type, $options);
 }
コード例 #15
0
 /** List of the papers available
  * @access public
  * @return void
  */
 public function indexAction()
 {
     $ping = $this->_solr->createPing();
     if (!$this->_solr->ping($ping)) {
         echo '<h2>Search engine system error</h2>';
         echo '<p>Solr service not responding.</p>';
     } else {
         $form = new SolrForm();
         $form->removeElement('thumbnail');
         $this->view->form = $form;
         if ($this->_request->isPost()) {
             $data = $this->getAllParams();
             if ($form->isValid($data)) {
                 $this->redirect($this->view->url(array('module' => 'search', 'controller' => 'results', 'action' => 'index', 'q' => $data['q'])));
             } else {
                 $form->populate($form->getValues());
             }
         }
     }
 }
コード例 #16
0
ファイル: Handler.php プロジェクト: lesleyauk/findsorguk
 /** Get the solr object for querying cores
  * @access public
  * @return \Solarium_Client
  */
 public function getSolr()
 {
     $this->_solr = new Solarium_Client($this->getSolrConfig());
     $this->_solr->setAdapter('Solarium_Client_Adapter_ZendHttp');
     $this->_solr->getAdapter()->getZendHttp();
     $loadbalancer = $this->_solr->getPlugin('loadbalancer');
     $master = $this->getConfig()->solr->master->toArray();
     $asgard = $this->getConfig()->solr->asgard->toArray();
     $valhalla = $this->getConfig()->solr->valhalla->toArray();
     $loadbalancer->addServer('objects', $master, 100);
     $loadbalancer->addServer('asgard', $asgard, 200);
     $loadbalancer->addServer('valhalla', $valhalla, 150);
     $loadbalancer->setFailoverEnabled(true);
     $this->_solr->getAdapter()->getZendHttp();
     $this->_loadbalancer = $loadbalancer;
     return $this->_solr;
 }
コード例 #17
0
 public function testFailoverMaxRetries()
 {
     $this->_plugin = new TestLoadbalancer();
     // special loadbalancer that returns servers in fixed order
     $this->_client = new Solarium_Client();
     $adapter = new TestAdapterForFailover();
     $adapter->setFailCount(10);
     $this->_client->setAdapter($adapter);
     // set special mock that fails for all servers
     $this->_plugin->init($this->_client, array());
     $request = new Solarium_Client_Request();
     $servers = array('s1' => array('options' => $this->_serverOptions, 'weight' => 1), 's2' => array('options' => $this->_serverOptions, 'weight' => 1));
     $this->_plugin->setServers($servers);
     $this->_plugin->setFailoverEnabled(true);
     $query = new Solarium_Query_Select();
     $this->_plugin->preCreateRequest($query);
     $this->setExpectedException('Solarium_Exception', 'Maximum number of loadbalancer retries reached');
     $this->_plugin->preExecuteRequest($request);
 }
コード例 #18
0
 /**
  * @desc Searches for a song lyrics in Solr index
  *
  * @param LyricsApiSearchParams $searchParams
  *
  * @return array|null
  */
 public function searchLyrics(LyricsApiSearchParams $searchParams)
 {
     $query = $this->newQueryFromSearch(['type: %1%' => LyricsUtils::TYPE_SONG, 'lyrics: %P2%' => $searchParams->getField(LyricsApiController::PARAM_QUERY)]);
     $query->setStart($searchParams->getOffset());
     $query->setRows($searchParams->getLimit());
     $hl = $query->getHighlighting();
     $hl->setFields(self::INDEX_FIELD_NAME_LYRICS);
     $hl->setSimplePrefix(self::HIGHLIGHT_PREFIX);
     $hl->setSimplePostfix(self::HIGHLIGHT_POSTFIX);
     $solrSongs = $this->client->select($query);
     if ($solrSongs->getNumFound() <= 0) {
         return null;
     }
     $songs = [];
     $highlighting = $solrSongs->getHighlighting();
     /** @var Solarium_Document_ReadOnly $solrSong */
     foreach ($solrSongs as $solrSong) {
         $fields = $solrSong->getFields();
         $songs[] = $this->getOutputSong($solrSong, $highlighting->getResult($fields['id']), true);
     }
     return $songs;
 }
コード例 #19
0
 /**
  * Utilizes Solr's MoreLikeThis component to return similar pages
  * @see    WikiaSearchTest::testMoreLikeThis
  * @param  WikiaSearchConfig $searchConfig
  * @return WikiaSearchResultSet
  */
 private function moreLikeThis(WikiaSearchConfig $searchConfig)
 {
     $query = $searchConfig->getQuery(WikiaSearchConfig::QUERY_RAW);
     $streamBody = $searchConfig->getStreamBody();
     $streamUrl = $searchConfig->getStreamUrl();
     if (!($query || $streamBody || $streamUrl)) {
         throw new Exception("A query, url, or stream is required.");
     }
     $mlt = $this->client->createMoreLikeThis();
     $mlt->setMltFields(implode(',', $searchConfig->getMltFields()))->setFields($searchConfig->getRequestedFields())->addParam('mlt.match.include', 'false')->setStart($searchConfig->getStart())->setRows($searchConfig->getRows())->setDocumentClass('WikiaSearchResult');
     if ($searchConfig->getInterestingTerms() == 'list') {
         $mlt->setInterestingTerms('list');
     }
     if ($searchConfig->getMltFilterQuery()) {
         $mlt->addFilterQuery(array('query' => $searchConfig->getMltFilterQuery(), 'key' => 'mltfilterquery'));
     }
     if ($query !== null) {
         $mlt->setQuery($query);
     } else {
         if ($streamBody) {
             $mlt->addParam('stream.body', $streamBody);
         } else {
             if ($streamUrl) {
                 $mlt->addParam('stream.url', $streamUrl);
             }
         }
     }
     try {
         $mltResult = $this->client->moreLikeThis($mlt);
     } catch (Exception $e) {
         $mltResult = F::build('Solarium_Result_Select_Empty');
         Wikia::Log(__METHOD__, '', $e);
     }
     $results = F::build('WikiaSearchResultSet', array($mltResult, $searchConfig));
     return $results;
 }
コード例 #20
0
<?php

require 'init.php';
htmlHeader();
// This example shows how to manually execute the query flow.
// By doing this manually you can customize data in between any step (although a plugin might be better for this)
// And you can use only a part of the flow. You could for instance use the query object and request builder,
// but execute the request in your own code.
// create a client instance
$client = new Solarium_Client($config);
// create a select query instance
$query = $client->createSelect();
// manually create a request for the query
$request = $client->createRequest($query);
// you can now use the request object for getting an uri (ie. to use in you own code)
// or you could modify the request object
echo 'Request URI: ' . $request->getUri() . '<br/>';
// you can still execute the request using the client and get a 'raw' response object
$response = $client->executeRequest($request);
// and finally you can convert the response into a result
$result = $client->createResult($query, $response);
// display the total number of documents found by solr
echo 'NumFound: ' . $result->getNumFound();
// show documents using the resultset iterator
foreach ($result as $document) {
    echo '<hr/><table>';
    // the documents are also iterable, to get all fields
    foreach ($document as $field => $value) {
        // this converts multivalue fields to a comma-separated string
        if (is_array($value)) {
            $value = implode(', ', $value);
コード例 #21
0
ファイル: solr.php プロジェクト: parvbhullar/test
//        'localhost' => array(
//            'host' => '188.40.100.77',
//            'port' => 8080,
//            'path' => '/solr',
//            'timeout'=> 50,
//            'core' => 'collectionv2',
//        )
//    )
//);
$server = "178.63.79.68";
//$server = "188.40.100.77";
$config = array('adapteroptions' => array('host' => $server, 'port' => 8080, 'path' => '/solr/', 'core' => 'collectionv2'));
$limit = 10;
$offset = 0;
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
$keyword = isset($argv[1]) ? $argv[1] : "*";
//$keyword = str_replace(" ", "*", $keyword);
//$matchingText = explode(" ",trim($keyword));
//for($i=0; $i<count($matchingText);$i++){
//    if($i == 0){
//        $keyword = $matchingText[$i]."+".$matchingText[$i]."*";
//    }else{
//        $keyword = $keyword."+".$matchingText[$i]."+".$matchingText[$i]."*";
//    }
//}
// apply settings using the API
//$query->setQuery($q);
//$query->setStart($offset)->setRows($limit);
コード例 #22
0
<?php

require 'init.php';
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get an update query instance
$update = $client->createUpdate();
// add the delete query and a commit command to the update query
$update->addDeleteQuery('name:testdoc*');
$update->addCommit();
// this executes the query and returns the result
$result = $client->update($update);
echo '<b>Update query executed<b><br/>';
echo 'Query status: ' . $result->getStatus() . '<br/>';
echo 'Query time: ' . $result->getQueryTime();
htmlFooter();
コード例 #23
0
<?php

require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
require 'init.php';
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// set the adapter to curl
$client->setAdapter('Solarium_Client_Adapter_Curl');
// get a select query instance
$query = $client->createSelect();
// this executes the query and returns the result
$resultset = $client->select($query);
// display the total number of documents found by solr
echo 'NumFound: ' . $resultset->getNumFound();
// show documents using the resultset iterator
foreach ($resultset as $document) {
    echo '<hr/><table>';
    // the documents are also iterable, to get all fields
    foreach ($document as $field => $value) {
        // this converts multivalue fields to a comma-separated string
        if (is_array($value)) {
            $value = implode(', ', $value);
        }
        echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>';
    }
    echo '</table>';
}
htmlFooter();
コード例 #24
0
<?php

require 'init.php';
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a suggester query instance
$query = $client->createSuggester();
$query->setQuery('ap ip v');
//multiple terms
$query->setDictionary('suggest');
$query->setOnlyMorePopular(true);
$query->setCount(10);
$query->setCollate(true);
// this executes the query and returns the result
$resultset = $client->suggester($query);
echo '<b>Query:</b> ' . $query->getQuery() . '<hr/>';
// display results for each term
foreach ($resultset as $term => $termResult) {
    echo '<h3>' . $term . '</h3>';
    echo 'NumFound: ' . $termResult->getNumFound() . '<br/>';
    echo 'StartOffset: ' . $termResult->getStartOffset() . '<br/>';
    echo 'EndOffset: ' . $termResult->getEndOffset() . '<br/>';
    echo 'Suggestions:<br/>';
    foreach ($termResult as $result) {
        echo '- ' . $result . '<br/>';
    }
    echo '<hr/>';
}
// display collation
echo 'Collation: ' . $resultset->getCollation();
コード例 #25
0
<?php

require 'init.php';
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// search input string, this value fails without escaping because of the double-quote
$input = 'ATA "133';
// in this case phrase escaping is used (most common) but you can also do term escaping, see the manual
$helper = $query->getHelper();
$query->setQuery('features:' . $helper->escapePhrase($input));
// this executes the query and returns the result
$resultset = $client->select($query);
// display the total number of documents found by solr
echo 'NumFound: ' . $resultset->getNumFound();
// show documents using the resultset iterator
foreach ($resultset as $document) {
    echo '<hr/><table>';
    // the documents are also iterable, to get all fields
    foreach ($document as $field => $value) {
        // this converts multivalue fields to a comma-separated string
        if (is_array($value)) {
            $value = implode(', ', $value);
        }
        echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>';
    }
    echo '</table>';
}
htmlFooter();
コード例 #26
0
 /**
  * Get a collection of the laws most similar to the present law.
  */
 function get_related()
 {
     /*
      * The number of results to return. The default is 5.
      */
     if (!isset($this->num_results)) {
         $this->num_results = 5;
     }
     /*
      * Intialize Solarium.
      */
     $client = new Solarium_Client($GLOBALS['solr_config']);
     if ($client === FALSE) {
         return FALSE;
     }
     /*
      * Create a MoreLikeThis query instance.
      */
     $query = $client->createMoreLikeThis();
     /*
      * Note that we have to escape colons in this query.
      */
     $query->setQuery('section:' . str_replace(':', '\\:', $this->section_number));
     $query->setMltFields('text,tags,catch_line');
     $query->setMatchInclude(TRUE);
     $query->setStart(0)->setRows($this->num_results);
     /*
      * Execute the query and return the result.
      */
     $results = $client->select($query);
     /*
      * If our query fails.
      */
     if ($results === FALSE) {
         return FALSE;
     }
     /*
      * Create a new, blank object to store our related sections.
      */
     $related = new StdClass();
     /*
      * Iterate through the returned documents
      */
     $i = 0;
     foreach ($results as $document) {
         $law = new Law();
         $law->law_id = $document->id;
         $law->get_law();
         $related->{$i} = $law;
         $i++;
     }
     return TRUE;
 }
コード例 #27
0
ファイル: AbstractSelect.php プロジェクト: Tjorriemorrie/app
 /**
  * This allows internal manipulation of the specific core being queried by this service.
  * There is probably a better way to do this, but this is the least disruptive way to handle this somewhat circular dependency.
  * @return \Wikia\Search\QueryService\Select\AbstractSelect
  */
 protected function setCoreInClient()
 {
     $options = $this->client->getOptions();
     $options['adapteroptions']['path'] = '/solr/' . $this->core;
     $this->client->setOptions($options, true);
     $this->coreSetInClient = true;
     return $this;
 }
コード例 #28
0
<?php

require 'init.php';
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a morelikethis query instance
$query = $client->createMoreLikeThis();
$query->setQuery('id:SP2514N');
$query->setMltFields('manu,cat');
$query->setMinimumDocumentFrequency(1);
$query->setMinimumTermFrequency(1);
$query->createFilterQuery('stock')->setQuery('inStock:true');
$query->setInterestingTerms('details');
$query->setMatchInclude(true);
// this executes the query and returns the result
$resultset = $client->select($query);
echo 'Document used for matching:<br/><table>';
foreach ($resultset->getMatch() as $field => $value) {
    // this converts multivalue fields to a comma-separated string
    if (is_array($value)) {
        $value = implode(', ', $value);
    }
    echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>';
}
echo '</table><hr/>';
// display the total number of MLT documents found by solr
echo 'Number of MLT matches found: ' . $resultset->getNumFound() . '<br/><br/>';
echo '<b>Listing of matched docs:</b>';
// show MLT documents using the resultset iterator
foreach ($resultset as $document) {
コード例 #29
0
<?php

require 'init.php';
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get an analysis document query
$query = $client->createAnalysisField();
$query->setShowMatch(true);
$query->setFieldName('cat,title');
$query->setFieldType('text_general');
$query->setFieldValue('Apple 60 GB iPod with Video Playback Black');
$query->setQuery('ipod');
// this executes the query and returns the result
$results = $client->analyze($query);
// show the results
foreach ($results as $result) {
    echo '<hr><h2>Result list: ' . $result->getName() . '</h2>';
    foreach ($result as $item) {
        echo '<h3>Item: ' . $item->getName() . '</h3>';
        $indexAnalysis = $item->getIndexAnalysis();
        if (!empty($indexAnalysis)) {
            echo '<h4>Index Analysis</h4>';
            foreach ($indexAnalysis as $classes) {
                echo '<h5>' . $classes->getName() . '</h5>';
                foreach ($classes as $result) {
                    echo 'Text: ' . $result->getText() . '<br/>';
                    echo 'Raw text: ' . $result->getRawText() . '<br/>';
                    echo 'Start: ' . $result->getStart() . '<br/>';
                    echo 'End: ' . $result->getEnd() . '<br/>';
                    echo 'Position: ' . $result->getPosition() . '<br/>';
コード例 #30
0
<?php

require 'init.php';
htmlHeader();
// create a client instance and get a select query instance
$client = new Solarium_Client($config);
// first an example manually defining dereferenced params
$query = $client->createSelect();
$helper = $query->getHelper();
$join = $helper->qparser('join', array('from' => 'manu_id', 'to' => 'id'), true);
$queryString = $join . 'id:1';
$query->setQuery($queryString);
$request = $client->createRequest($query);
// output resulting url with dereferenced params
echo urldecode($request->getUri()) . '<hr/>';
// this second example gives the exact same result, using the special join helper
$query = $client->createSelect();
$helper = $query->getHelper();
$join = $helper->join('manu_id', 'id', true);
$queryString = $join . 'id:1';
$query->setQuery($queryString);
$request = $client->createRequest($query);
echo urldecode($request->getUri());
htmlFooter();