source: sandbox/expresso-solr/expressoMail1_2/solrclient/examples/2.1.7-query-reuse.php @ 7588

Revision 7588, 2.0 KB checked in by adir, 11 years ago (diff)

Ticket #000 - Adicionando a integracao de buscas com Solr na base a ser isnerida na comunidade

Line 
1<?php
2
3require('init.php');
4htmlHeader();
5
6// create a client instance
7$client = new Solarium_Client($config);
8
9
10// first create a base query as a query class
11class PriceQuery extends Solarium_Query_Select
12{
13    protected function _init()
14    {
15        // set a query (all prices starting from 12)
16        $this->setQuery('price:[12 TO *]');
17
18        // set start and rows param (comparable to SQL limit) using fluent interface
19        $this->setStart(2)->setRows(20);
20
21        // set fields to fetch (this overrides the default setting 'all fields')
22        $this->setFields(array('id','name','price'));
23
24        // sort the results by price ascending
25        $this->addSort('price', self::SORT_ASC);
26    }
27}
28
29// the query instance easily be altered based on user input
30// try calling this page with "?start=10" added to the url.
31$query = new PriceQuery();
32if(isset($_GET['start']) && is_numeric($_GET['start'])){
33    $query->setStart($_GET['start']);
34}
35
36// alternatively you can use class inheritance to create query inheritance
37// in this example this class isn't actually used, but you can simple replace
38// the var $query with an instance of this class...
39class LowerPriceQuery extends PriceQuery{
40    protected function _init()
41    {
42        // this call makes sure we get all the settings of the parent class
43        parent::_init();
44
45        $this->setQuery('price:[5 TO *]');
46    }
47}
48
49// this executes the query and returns the result
50$resultset = $client->select($query);
51
52// display the total number of documents found by solr
53echo 'NumFound: '.$resultset->getNumFound();
54
55// show documents using the resultset iterator
56foreach ($resultset as $document) {
57
58    echo '<hr/><table>';
59
60    // the documents are also iterable, to get all fields
61    foreach($document AS $field => $value)
62    {
63        // this converts multivalue fields to a comma-separated string
64        if(is_array($value)) $value = implode(', ', $value);
65
66        echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>';
67    }
68
69    echo '</table>';
70}
71
72htmlFooter();
Note: See TracBrowser for help on using the repository browser.