Commit 4b7859c4 authored by Albert Casademont's avatar Albert Casademont

Merge branch 'release/2.0.0' of https://github.com/basdenooijer/solarium

parents 200e6067 77ee7bcc
config.php
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// check solarium version available
echo 'Solarium library version: ' . Solarium_Version::VERSION . ' - ';
// create a client instance
$client = new Solarium_Client($config);
// create a ping query
$ping = $client->createPing();
// execute the ping query
try{
$client->ping($ping);
echo 'Ping query succesful';
}catch(Solarium_Exception $e){
echo 'Ping query failed';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// 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();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
if ($_POST) {
// if data is posted add it to solr
// create a new document for the data
// please note that any type of validation is missing in this example to keep it simple!
$doc = new Solarium_Document_ReadWrite();
$doc->id = $_POST['id'];
$doc->name = $_POST['name'];
$doc->price = $_POST['price'];
// create a client instance
$client = new Solarium_Client($config);
// get an update query instance
$update = $client->createUpdate();
// add the document and a commit command to the update query
$update->addDocument($doc);
$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();
} else {
// if no data is posted show a form
?>
<form method="POST">
Id: <input type="text" name="id"/> <br/>
Name: <input type="text" name="name"/> <br/>
Price: <input type="text" name="price"/> <br/>
<input type="submit" value="Add"/>
</form>
<?php
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// set a query (all prices starting from 12)
$query->setQuery('price:[12 TO *]');
// set start and rows param (comparable to SQL limit) using fluent interface
$query->setStart(2)->setRows(20);
// set fields to fetch (this overrides the default setting 'all fields')
$query->setFields(array('id','name','price'));
// sort the results by price ascending
$query->addSort('price', Solarium_Query_Select::SORT_ASC);
// 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();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// this is the custom result document class
class myDoc extends Solarium_Document_ReadOnly{
public function getSpecialPrice()
{
return round(($this->price * .95), 2);
}
}
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// set the custom resultclass
$query->setDocumentClass('myDoc');
// 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>';
echo '<tr><th>id</th><td>' . $document->id . '</td></tr>';
echo '<tr><th>name</th><td>' . $document->name . '</td></tr>';
echo '<tr><th>price</th><td>' . $document->price . '</td></tr>';
// this method is added by the custom class
echo '<tr><th>offer price</th><td>' . $document->getSpecialPrice() . '</td></tr>';
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// create a filterquery
$fq = $query->createFilterQuery();
$fq->setKey('maxprice');
$fq->setQuery('price:[1 TO 300]');
// add it to the query
$query->addFilterQuery($fq);
// 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>';
echo '<tr><th>id</th><td>' . $document->id . '</td></tr>';
echo '<tr><th>name</th><td>' . $document->name . '</td></tr>';
echo '<tr><th>price</th><td>' . $document->price . '</td></tr>';
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// get the facetset component
$facetSet = $query->getFacetSet();
// create a facet field instance and set options
$facet = $facetSet->createFacetField();
$facet->setKey('stock');
$facet->setField('inStock');
// add the facet instance to the facetset
$facetSet->addFacet($facet);
// 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();
// display facet counts
echo '<hr/>Facet counts for field "inStock":<br/>';
$facet = $resultset->getFacetSet()->getFacet('stock');
foreach($facet as $value => $count) {
echo $value . ' [' . $count . ']<br/>';
}
// show documents using the resultset iterator
foreach ($resultset as $document) {
echo '<hr/><table>';
echo '<tr><th>id</th><td>' . $document->id . '</td></tr>';
echo '<tr><th>name</th><td>' . $document->name . '</td></tr>';
echo '<tr><th>price</th><td>' . $document->price . '</td></tr>';
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// get the facetset component
$facetSet = $query->getFacetSet();
// create a facet query instance and set options
$facet = $facetSet->createFacetQuery();
$facet->setKey('stock');
$facet->setQuery('inStock: true');
// add the facet instance to the facetset
$facetSet->addFacet($facet);
// 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();
// display facet query count
$count = $resultset->getFacetSet()->getFacet('stock')->getValue();
echo '<hr/>Facet query count : ' . $count;
// show documents using the resultset iterator
foreach ($resultset as $document) {
echo '<hr/><table>';
echo '<tr><th>id</th><td>' . $document->id . '</td></tr>';
echo '<tr><th>name</th><td>' . $document->name . '</td></tr>';
echo '<tr><th>price</th><td>' . $document->price . '</td></tr>';
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// get the facetset component
$facetSet = $query->getFacetSet();
// create a facet query instance and set options
$facet = $facetSet->createFacetMultiQuery();
$facet->setKey('stock');
$facet->createQuery('stock_pricecat1', 'inStock:true AND price:[1 TO 300]');
$facet->createQuery('nostock_pricecat1', 'inStock:false AND price:[1 TO 300]');
$facet->createQuery('stock_pricecat2', 'inStock:true AND price:[300 TO *]');
$facet->createQuery('nostock_pricecat2', 'inStock:false AND price:[300 TO *]');
// add the facet instance to the facetset
$facetSet->addFacet($facet);
// 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();
// display facet counts
echo '<hr/>Multiquery facet counts:<br/>';
$facet = $resultset->getFacetSet()->getFacet('stock');
foreach($facet as $key => $count) {
echo $key . ' [' . $count . ']<br/>';
}
// show documents using the resultset iterator
foreach ($resultset as $document) {
echo '<hr/><table>';
echo '<tr><th>id</th><td>' . $document->id . '</td></tr>';
echo '<tr><th>name</th><td>' . $document->name . '</td></tr>';
echo '<tr><th>price</th><td>' . $document->price . '</td></tr>';
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// get the facetset component
$facetSet = $query->getFacetSet();
// create a facet field instance and set options
$facet = $facetSet->createFacetRange();
$facet->setKey('priceranges');
$facet->setField('price');
$facet->setStart(1);
$facet->setGap(100);
$facet->setEnd(1000);
// add the facet instance to the facetset
$facetSet->addFacet($facet);
// 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();
// display facet counts
echo '<hr/>Facet ranges:<br/>';
$facet = $resultset->getFacetSet()->getFacet('priceranges');
foreach($facet as $range => $count) {
echo $range . ' to ' . ($range + 100) . ' [' . $count . ']<br/>';
}
// show documents using the resultset iterator
foreach ($resultset as $document) {
echo '<hr/><table>';
echo '<tr><th>id</th><td>' . $document->id . '</td></tr>';
echo '<tr><th>name</th><td>' . $document->name . '</td></tr>';
echo '<tr><th>price</th><td>' . $document->price . '</td></tr>';
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// add a query and morelikethis settings (using fluent interface)
$query->setQuery('apache')
->getMoreLikeThis()
->setFields('manu,cat')
->setMinimumDocumentFrequency(1)
->setMinimumTermFrequency(1);
// this executes the query and returns the result
$resultset = $client->select($query);
$mlt = $resultset->getMoreLikeThis();
// 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><br/><b>MLT results:</b><br/>';
// mlt results can be fetched by document id (the field defined as uniquekey in this schema)
$mltResult = $mlt->getResult($document->id);
if($mltResult){
echo 'Max score: '.$mltResult->getMaximumScore().'<br/>';
echo 'NumFound: '.$mltResult->getNumFound().'<br/>';
echo 'Num. fetched: '.count($mltResult).'<br/>';
foreach($mltResult AS $mltDoc) {
echo 'MLT result doc: '. $mltDoc->name . ' (id='. $mltDoc->id . ')<br/>';
}
}else{
echo 'No MLT results';
}
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
$query->setQuery('memory');
// get highlighting component and apply settings
$hl = $query->getHighlighting();
$hl->setFields('name, features');
$hl->setSimplePrefix('<b>');
$hl->setSimplePostfix('</b>');
// this executes the query and returns the result
$resultset = $client->select($query);
$highlighting = $resultset->getHighlighting();
// 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><br/><b>Highlighting results:</b><br/>';
// highlighting results can be fetched by document id (the field defined as uniquekey in this schema)
$highlightedDoc = $highlighting->getResult($document->id);
if($highlightedDoc){
foreach($highlightedDoc as $field => $highlight) {
echo implode(' (...) ', $highlight) . '<br/>';
}
}
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// get the dismax component and set a boost query
$dismax = $query->getDisMax();
$dismax->setBoostQuery('cat:"graphics card"^2');
// this query is now a dismax query
$query->setQuery('memory -printer');
// 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();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance and a query helper instance
$query = $client->createSelect();
$helper = $query->getHelper();
// add a filterquery on a price range, using the helper to generate the range
$fqPrice = $query->createFilterQuery();
$fqPrice->setKey('price');
$fqPrice->setQuery($helper->rangeQuery('price', 10, 300));
$query->addFilterQuery($fqPrice);
// add a filterquery to find products in a range of 5km, using the helper to generate the 'geofilt' filter
$fqRegion = $query->createFilterQuery();
$fqRegion->setKey('region');
$fqRegion->setQuery($helper->geofilt(45.15, -93.85, 'store', 5));
$query->addFilterQuery($fqRegion);
// 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();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a new document for the data
$doc1 = new Solarium_Document_ReadWrite();
$doc1->id = 123;
$doc1->name = 'testdoc-1';
$doc1->price = 364;
// and a second one
$doc2 = new Solarium_Document_ReadWrite();
$doc2->id = 124;
$doc2->name = 'testdoc-2';
$doc2->price = 340;
// create a client instance
$client = new Solarium_Client($config);
// get an update query instance
$update = $client->createUpdate();
// add the documents and a commit command to the update query
$update->addDocuments(array($doc1, $doc2));
$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();
\ No newline at end of file
<?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();
\ No newline at end of file
<?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 id and a commit command to the update query
$update->addDeleteById(123);
$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();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get an update query instance
$update = $client->createUpdate();
// optimize the index
$update->addOptimize(true, false, 5);
// 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();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get an update query instance
$update = $client->createUpdate();
// rollback any uncommitted changes on the Solr server
$update->addRollback();
// 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();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance
$query = $client->createSelect();
// apply settings using the API
$query->setQuery('*:*');
$query->setStart(2)->setRows(20);
$query->setFields(array('id','name','price'));
$query->addSort('price', Solarium_Query_Select::SORT_ASC);
// create a filterquery using the API
$fq = $query->createFilterQuery();
$fq->setKey('maxprice');
$fq->setQuery('price:[1 TO 300]');
// and add it to the query
$query->addFilterQuery($fq);
// create a facet field instance and set options using the API
$facetSet = $query->getFacetSet();
$facet = $facetSet->createFacetField();
$facet->setKey('stock');
$facet->setField('inStock');
$facetSet->addFacet($facet);
// 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();
// display facet counts
echo '<hr/>Facet counts for field "inStock":<br/>';
$facet = $resultset->getFacetSet()->getFacet('stock');
foreach($facet as $value => $count) {
echo $value . ' [' . $count . ']<br/>';
}
// show documents using the resultset iterator
foreach ($resultset as $document) {
echo '<hr/><table>';
echo '<tr><th>id</th><td>' . $document->id . '</td></tr>';
echo '<tr><th>name</th><td>' . $document->name . '</td></tr>';
echo '<tr><th>price</th><td>' . $document->price . '</td></tr>';
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// In this case an array is used for configuration to keep the example simple.
// For an easier to use config file you are probably better of with another format, like Zend_Config_Ini
// See the documentation for more info about this.
$select = array(
'query' => '*:*',
'start' => 2,
'rows' => 20,
'fields' => array('id','name','price'),
'sort' => array('price' => 'asc'),
'filterquery' => array(
'maxprice' => array(
'query' => 'price:[1 TO 300]'
),
),
'component' => array(
'facetset' => array(
'facet' => array(
// notice this config uses an inline key value, instead of array key like the filterquery
array('type' => 'field', 'key' => 'stock', 'field' => 'inStock'),
)
),
),
);
// create a client instance
$client = new Solarium_Client($config);
// get a select query instance based on the config
$query = $client->createSelect($select);
// 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();
// display facet counts
echo '<hr/>Facet counts for field "inStock":<br/>';
$facet = $resultset->getFacetSet()->getFacet('stock');
foreach($facet as $value => $count) {
echo $value . ' [' . $count . ']<br/>';
}
// show documents using the resultset iterator
foreach ($resultset as $document) {
echo '<hr/><table>';
echo '<tr><th>id</th><td>' . $document->id . '</td></tr>';
echo '<tr><th>name</th><td>' . $document->name . '</td></tr>';
echo '<tr><th>price</th><td>' . $document->price . '</td></tr>';
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// In most cases using the API or config is advisable, however in some cases it can make sense to extend classes.
// This makes it possible to create 'query inheritance' like in this example
class ProductQuery extends Solarium_Query_Select{
protected function _init()
{
parent::_init();
// basic params
$this->setQuery('*:*');
$this->setStart(2)->setRows(20);
$this->setFields(array('id','name','price'));
$this->addSort('price', Solarium_Query_Select::SORT_ASC);
// create a facet field instance and set options
$facetSet = $this->getFacetSet();
$facet = $facetSet->createFacetField();
$facet->setKey('stock');
$facet->setField('inStock');
$facetSet->addFacet($facet);
}
}
// This query inherits all of the query params of it's parent (using parent::_init) and adds some more
// Ofcourse it could also alter or remove settings
class ProductPriceLimitedQuery extends ProductQuery{
protected function _init()
{
parent::_init();
// create a filterquery
$fq = $this->createFilterQuery();
$fq->setKey('maxprice');
$fq->setQuery('price:[1 TO 300]');
// and add it
$this->addFilterQuery($fq);
}
}
// create a client instance
$client = new Solarium_Client($config);
// create a query instance
$query = new ProductPriceLimitedQuery;
// 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();
// display facet counts
echo '<hr/>Facet counts for field "inStock":<br/>';
$facet = $resultset->getFacetSet()->getFacet('stock');
foreach($facet as $value => $count) {
echo $value . ' [' . $count . ']<br/>';
}
// show documents using the resultset iterator
foreach ($resultset as $document) {
echo '<hr/><table>';
echo '<tr><th>id</th><td>' . $document->id . '</td></tr>';
echo '<tr><th>name</th><td>' . $document->name . '</td></tr>';
echo '<tr><th>price</th><td>' . $document->price . '</td></tr>';
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?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);
echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>';
}
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
// This is a custom query class that could have some customized logic
class MyQuery extends Solarium_Query_Select
{
// ...customization here...
}
// And this is the extended client, that modifies the default query mapping
// for select queries to our custom query class.
// BTW, the same could also be done using a plugin, see example 5.3.2
class MyClient extends Solarium_Client
{
/**
* Querytype mappings
*/
protected $_queryTypes = array(
self::QUERYTYPE_SELECT => array(
'query' => 'MyQuery',
'requestbuilder' => 'Solarium_Client_RequestBuilder_Select',
'responseparser' => 'Solarium_Client_ResponseParser_Select'
),
self::QUERYTYPE_UPDATE => array(
'query' => 'Solarium_Query_Update',
'requestbuilder' => 'Solarium_Client_RequestBuilder_Update',
'responseparser' => 'Solarium_Client_ResponseParser_Update'
),
self::QUERYTYPE_PING => array(
'query' => 'Solarium_Query_Ping',
'requestbuilder' => 'Solarium_Client_RequestBuilder_Ping',
'responseparser' => 'Solarium_Client_ResponseParser_Ping'
),
);
}
// create a client instance
$client = new MyClient($config);
// create a select query instance
$query = $client->createSelect();
// check the query class, it should be our custom query class
echo 'Query class: ' . get_class($query) . '<br/>';
// execute query
$result = $client->execute($query);
// 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);
echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>';
}
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
// this very simple plugin shows a timing for each event and display some request debug info
class basicDebug extends Solarium_Plugin_Abstract
{
protected $_start;
protected $_output = array();
public function _initPlugin()
{
$this->_start = microtime(true);
}
protected function _timer($event)
{
$time = round(microtime(true) - $this->_start, 5);
$this->_output[] = '['.$time.'] ' . $event;
}
public function display()
{
echo implode('<br/>', $this->_output);
}
public function preCreateRequest()
{
$this->_timer('preCreateRequest');
}
public function postCreateRequest()
{
$this->_timer('postCreateRequest');
}
// This method uses the aviable param(s) (see plugin abstract class)
// You can access or modify data this way
public function preExecuteRequest($request)
{
$this->_timer('preExecuteRequest');
// this dummy param will be visible in the debug output but will also be used in the actual Solr request
$request->addParam('dummyparam', 'dummyvalue');
$this->_output[] = 'Request URI: ' . $request->getUri();
}
public function postExecuteRequest()
{
$this->_timer('postExecuteRequest');
}
public function preCreateResult()
{
$this->_timer('preCreateResult');
}
public function postCreateResult()
{
$this->_timer('postCreateResult');
}
public function preExecute()
{
$this->_timer('preExecute');
}
public function postExecute()
{
$this->_timer('postExecute');
}
public function preCreateQuery()
{
$this->_timer('preCreateResult');
}
public function postCreateQuery()
{
$this->_timer('postCreateResult');
}
}
htmlHeader();
// create a client instance and register the plugin
$plugin = new basicDebug();
$client = new Solarium_Client($config);
$client->registerPlugin('debugger', $plugin);
// execute a select query and display the results
$query = $client->createSelect();
$resultset = $client->select($query);
echo 'NumFound: '.$resultset->getNumFound();
foreach ($resultset as $document) {
echo '<hr/><table>';
foreach($document AS $field => $value)
{
if(is_array($value)) $value = implode(', ', $value);
echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>';
}
echo '</table>';
}
// display the debug plugin output
echo '<hr/><h1>Plugin output</h1>';
$plugin->display();
htmlFooter();
\ No newline at end of file
<?php
require('init.php');
// This is a custom query class that could have some customized logic
class MyQuery extends Solarium_Query_Select
{
// ...customization here...
}
// this very simple plugin that modifies the default querytype mapping
class queryCustomizer extends Solarium_Plugin_Abstract
{
protected function _initPlugin()
{
$this->_client->registerQueryType(
Solarium_Client::QUERYTYPE_SELECT,
'MyQuery',
'Solarium_Client_RequestBuilder_Select',
'Solarium_Client_ResponseParser_Select'
);
}
}
htmlHeader();
// create a client instance and register the plugin
$client = new Solarium_Client($config);
$client->registerPlugin('querycustomizer', 'queryCustomizer');
// create a select query instance
$query = $client->createSelect();
// check the query class, it should be our custom query class
echo 'Query class: ' . get_class($query) . '<br/>';
// execute the query and display the results
$resultset = $client->select($query);
echo 'NumFound: '.$resultset->getNumFound();
foreach ($resultset as $document) {
echo '<hr/><table>';
foreach($document AS $field => $value)
{
if(is_array($value)) $value = implode(', ', $value);
echo '<tr><th>' . $field . '</th><td>' . $value . '</td></tr>';
}
echo '</table>';
}
htmlFooter();
\ No newline at end of file
<?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 zendhttp and get a zendhttp client instance reference
$client->setAdapter('Solarium_Client_Adapter_ZendHttp');
$zendHttp = $client->getAdapter()->getZendHttp();
// you can use any of the zend_http features, like http-authentication
$zendHttp->setAuth('user', 'password!', Zend_Http_Client::AUTH_BASIC);
// 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();
\ No newline at end of file
<?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();
\ No newline at end of file
<?php
require('init.php');
htmlHeader();
echo 'TODO';
htmlFooter();
\ No newline at end of file
<?php
require('../library/Solarium/Autoloader.php');
Solarium_Autoloader::register();
\ No newline at end of file
<?php
$config = array(
'adapteroptions' => array(
'host' => '127.0.0.1',
'port' => 8983,
'path' => '/solr/',
)
);
<html>
<head>
<title>Solarium examples</title>
</head>
<body>
<h1>Solarium examples</h1>
<p>
In this folder you can find various examples for the Solarium PHP Solr client library, to be used on a Solr 'example' index as distributed with Solr.<br/>
Only the code is included, for more details about the examples and how to get them working please see the manual on the project website: <a href="http://www.solarium-project.org" target="_blank">http://www.solarium-project.org</a>
</p>
<p>
If examples for some Solarium functionality are missing please request them by opening an issue in the issue tracker: <a href="http://github.com/basdenooijer/solarium/issues" target="_blank">http://github.com/basdenooijer/solarium/issues</a>
</p>
<p>
<b>Important:</b> This code is intended to demonstrate the usage of Solarium. It is not intended for real-world use. For instance user input validation is missing or very limited, as the best way to do this will depend on your application and is not Solarium functionality.<br>
It's advised not to deploy the examples to a public environment, or at least make sure the example directory is not available via your webserver.
</p>
<ul style="list-style:none;">
<li>1. Basic usage</li>
<ul style="list-style:none;">
<li><a href="1.1-check-solarium-and-ping.php">1.1 Check solarium availability and ping Solr</a></li>
<li><a href="1.2-basic-select.php">1.2 Basic select</a></li>
<li><a href="1.3-basic-update.php">1.3 Basic update - add document</a></li>
</ul>
<li>2. Select query</li>
<ul style="list-style:none;">
<li><a href="2.1-query-params.php">2.1 Select query params</a></li>
<li><a href="2.2-custom-result-document.php">2.2 Custom result document</a></li>
<li><a href="2.3-filterquery.php">2.3 Filterquery</a></li>
<li>2.4 Components</li>
<ul style="list-style:none;">
<li>2.5.1 FacetSet</li>
<ul style="list-style:none;">
<li><a href="2.5.1.1-facet-field.php">2.5.1.1 Facet field</a></li>
<li><a href="2.5.1.2-facet-query.php">2.5.1.2 Facet query</a></li>
<li><a href="2.5.1.3-facet-multiquery.php">2.5.1.3 Facet multiquery</a></li>
<li><a href="2.5.1.4-facet-range.php">2.5.1.4 Facet range</a></li>
</ul>
<li><a href="2.5.2-morelikethis.php">2.5.2 MoreLikeThis</a></li>
<li><a href="2.5.3-highlighting.php">2.5.3 Highlighting</a></li>
<li><a href="2.5.4-dismax.php">2.5.4 Dismax</a></li>
</ul>
<li><a href="2.6-helper-functions.php">2.6 Helper functions</a></li>
</ul>
<li>3. Update query</li>
<ul style="list-style:none;">
<li><a href="3.1-add-docs.php">3.1 Add docs</a></li>
<li><a href="3.2-delete-by-query.php">3.2 Delete by query</a></li>
<li><a href="3.3-delete-by-id.php">3.3 Delete by ID</a></li>
<li><a href="3.4-optimize.php">3.4 Optimize index</a></li>
<li><a href="3.5-rollback.php">3.5 Rollback</a></li>
</ul>
<li>4. Usage modes</li>
<ul style="list-style:none;">
<li><a href="4.1-api-usage.php">4.1 API</a></li>
<li><a href="4.2-configuration-usage.php">4.2 Configuration</a></li>
<li><a href="4.3-extending-usage.php">4.3 Extending</a></li>
</ul>
<li>5. Customization</li>
<ul style="list-style:none;">
<li><a href="5.1-partial-usage.php">5.1 Partial usage</a></li>
<li><a href="5.2-extending.php">5.2 Extending</a></li>
<li>5.3 Plugin system</li>
<ul style="list-style:none;">
<li><a href="5.3.1-plugin-event-hooks.php">5.3.1 Event hooks</a></li>
<li><a href="5.3.2-plugin-solarium-presets.php">5.3.2 Modifying Solarium presets</a></li>
</ul>
</ul>
<li>6. Miscellaneous</li>
<ul style="list-style:none;">
<li><a href="6.1-zend-http-adapter.php">6.1 Zend_Http adapter</a></li>
<li><a href="6.2-escaping.php">6.2 Escaping</a></li>
<li><a href="6.3-demo-app.php">2.7 Demo search (mini) application</a></li>
</ul>
</ul>
</body>
</html>
\ No newline at end of file
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
require('autoload.php');
if (file_exists('config.php')) {
require('config.php');
} else {
require('config.dist.php');
}
function htmlHeader(){
echo '<html><head><title>Solarium examples</title></head><body>';
}
function htmlFooter(){
echo '</body></html>';
}
\ No newline at end of file
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
*/ */
...@@ -39,7 +40,7 @@ ...@@ -39,7 +40,7 @@
* *
* This class is included to allow for easy usage of Solarium. If you already * This class is included to allow for easy usage of Solarium. If you already
* have your own autoloader that follows the Zend Framework class/file naming * have your own autoloader that follows the Zend Framework class/file naming
* you don't need this. * you can use that to autoload Solarium (for instance Zend_Loader).
* *
* @package Solarium * @package Solarium
*/ */
......
This diff is collapsed.
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
...@@ -56,58 +57,175 @@ ...@@ -56,58 +57,175 @@
*/ */
abstract class Solarium_Client_Adapter extends Solarium_Configurable abstract class Solarium_Client_Adapter extends Solarium_Configurable
{ {
/**
* Default options
*
* The defaults match a standard Solr example instance as distributed by
* the Apache Lucene Solr project.
*
* @var array
*/
protected $_options = array(
'host' => '127.0.0.1',
'port' => 8983,
'path' => '/solr',
'core' => null,
'timeout' => 5,
);
/**
* Initialization hook
*
* In this case the path needs to be cleaned of trailing slashes.
* @see setPath()
*/
protected function _init()
{
foreach ($this->_options AS $name => $value) {
switch ($name) {
case 'path':
$this->setPath($value);
break;
}
}
}
/**
* Set host option
*
* @param string $host This can be a hostname or an IP address
* @return Solarium_Client Provides fluent interface
*/
public function setHost($host)
{
return $this->_setOption('host', $host);
}
/**
* Get host option
*
* @return string
*/
public function getHost()
{
return $this->getOption('host');
}
/**
* Set port option
*
* @param int $port Common values are 80, 8080 and 8983
* @return Solarium_Client Provides fluent interface
*/
public function setPort($port)
{
return $this->_setOption('port', $port);
}
/**
* Get port option
*
* @return int
*/
public function getPort()
{
return $this->getOption('port');
}
/** /**
* Set options * Set path option
* *
* Overrides any existing values * If the path has a trailing slash it will be removed.
*
* @param string $path
* @return Solarium_Client Provides fluent interface
*/
public function setPath($path)
{
if (substr($path, -1) == '/') $path = substr($path, 0, -1);
return $this->_setOption('path', $path);
}
/**
* Get path option
* *
* @param array $options
* @return void * @return void
*/ */
public function setOptions($options) public function getPath()
{ {
$this->_setOptions($options, true); return $this->getOption('path');
} }
/** /**
* Execute a select query * Set core option
* *
* Abstract method to require an implementation inside all adapters. * @param string $core
* If the adapter cannot support this method it should implement a method * @return Solarium_Client Provides fluent interface
* that throws an exception. */
public function setCore($core)
{
return $this->_setOption('core', $core);
}
/**
* Get core option
* *
* @abstract * @return string
* @param Solarium_Query_Select $query
* @return Solarium_Result_Select
*/ */
abstract public function select($query); public function getCore()
{
return $this->getOption('core');
}
/** /**
* Execute a ping query * Set timeout option
* *
* Abstract method to require an implementation inside all adapters. * @param int $timeout
* If the adapter cannot support this method it should implement a method * @return Solarium_Client Provides fluent interface
* that throws an exception. */
public function setTimeout($timeout)
{
return $this->_setOption('timeout', $timeout);
}
/**
* Get timeout option
* *
* @abstract * @return string
* @param Solarium_Query_Ping $query
* @return boolean
*/ */
abstract public function ping($query); public function getTimeout()
{
return $this->getOption('timeout');
}
/** /**
* Execute an update query * Execute a request
* *
* Abstract method to require an implementation inside all adapters. * Abstract method to require an implementation inside all adapters.
* If the adapter cannot support this method it should implement a method
* that throws an exception.
* *
* @abstract * @abstract
* @param Solarium_Query_Update $query * @param Solarium_Client_Request $request
* @return Solarium_Result_Update * @return Solarium_Client_Response
*/
abstract public function execute($request);
/**
* Get the base url for all requests
*
* Based on host, path, port and core options.
*
* @return void
*/ */
abstract public function update($query); public function getBaseUri()
{
$uri = 'http://' . $this->getHost() . ':' . $this->getPort() . $this->getPath() . '/';
$core = $this->getCore();
if (!empty($core)) {
$uri .= $core.'/';
}
return $uri;
}
} }
\ No newline at end of file
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
...@@ -45,66 +46,58 @@ class Solarium_Client_Adapter_Http extends Solarium_Client_Adapter ...@@ -45,66 +46,58 @@ class Solarium_Client_Adapter_Http extends Solarium_Client_Adapter
{ {
/** /**
* Executes a select query * Handle Solr communication
*
* @param Solarium_Query_Select $query
* @return Solarium_Result_Select
*/
public function select($query)
{
$request = new Solarium_Client_Request_Select($this->_options, $query);
$data = $this->_handleRequest($request);
$response = new Solarium_Client_Response_Select($query, $data);
return $response->getResult();
}
/**
* Executes a ping query
* *
* @param Solarium_Query_Ping $query * @throws Solarium_Exception
* @return boolean * @param Solarium_Client_Request $request
* @return Solarium_Client_Response
*/ */
public function ping($query) public function execute($request)
{ {
$request = new Solarium_Client_Request_Ping($this->_options, $query); $context = $this->createContext($request);
return (boolean)$this->_handleRequest($request); $uri = $this->getBaseUri() . $request->getUri();
list($data, $headers) = $this->_getData($uri, $context);
$this->check($data, $headers);
return new Solarium_Client_Response($data, $headers);
} }
/** /**
* Executes an update query * Check result of a request
* *
* @param Solarium_Query_Update $query * @throws Solarium_Client_HttpException
* @return Solarium_Result_Update * @param string $data
* @param array $headers
* @return void
*/ */
public function update($query) public function check($data, $headers)
{ {
$request = new Solarium_Client_Request_Update($this->_options, $query); // if there is no data and there are no headers it's a total failure,
$data = $this->_handleRequest($request); // a connection to the host was impossible.
if (false === $data && count($headers) == 0) {
$response = new Solarium_Client_Response_Update($query, $data); throw new Solarium_Client_HttpException("HTTP request failed");
return $response->getResult(); }
} }
/** /**
* Handle Solr communication * Create a stream context for a request
* *
* @throws Solarium_Exception * @param Solarium_Client_Request $request
* @param Solarium_Client_Request * @return resource
* @return array
*/ */
protected function _handleRequest($request) public function createContext($request)
{ {
$method = $request->getMethod(); $method = $request->getMethod();
$context = stream_context_create( $context = stream_context_create(
array('http' => array( array('http' => array(
'method' => $method, 'method' => $method,
'timeout' => $this->getOption('timeout') 'timeout' => $this->getTimeout()
)) ))
); );
if ($method == Solarium_Client_Request::POST) { if ($method == Solarium_Client_Request::METHOD_POST) {
$data = $request->getRawData(); $data = $request->getRawData();
if (null !== $data) { if (null !== $data) {
stream_context_set_option( stream_context_set_option(
...@@ -113,94 +106,44 @@ class Solarium_Client_Adapter_Http extends Solarium_Client_Adapter ...@@ -113,94 +106,44 @@ class Solarium_Client_Adapter_Http extends Solarium_Client_Adapter
'content', 'content',
$data $data
); );
stream_context_set_option(
$context, $request->addHeader('Content-Type: text/xml; charset=UTF-8');
'http',
'header',
'Content-Type: text/xml; charset=UTF-8'
);
} }
} }
$data = @file_get_contents($request->getUri(), false, $context); $headers = $request->getHeaders();
if (count($headers) > 0) {
// if there is no data and there are no headers it's a total failure, stream_context_set_option(
// a connection to the host was impossible. $context,
if (false === $data && !isset($http_response_header)) { 'http',
throw new Solarium_Client_HttpException("HTTP request failed"); 'header',
implode("\r\n", $headers)
);
} }
$this->_checkHeaders($http_response_header); return $context;
if ($method == Solarium_Client_Request::HEAD) {
// HEAD request has no result data
return true;
} else {
if (false === $data) {
$error = error_get_last();
throw new Solarium_Exception($error['message']);
}
return $this->_jsonDecode($data);
}
} }
/** /**
* Check HTTP headers * Execute request
* *
* The status header is parsed, an exception will be thrown for an error * @param string $uri
* code. * @param resource $context
* * @return array
* @throws Solarium_Client_HttpException
* @param array $headers
* @return void
*/ */
protected function _checkHeaders($headers) protected function _getData($uri, $context)
{ {
// get the status header // @codeCoverageIgnoreStart
$statusHeader = null; $data = @file_get_contents($uri, false, $context);
foreach ($headers AS $header) {
if (substr($header, 0, 4) == 'HTTP') {
$statusHeader = $header;
break;
}
}
if (null == $statusHeader) { if (isset($http_response_header)) {
throw new Solarium_Client_HttpException("No HTTP status found"); $headers = $http_response_header;
} else {
$headers = array();
} }
// parse header like "$statusInfo[1]" into code and message return array($data, $headers);
// $statusInfo[1] = the HTTP response code // @codeCoverageIgnoreEnd
// $statusInfo[2] = the response message
$statusInfo = explode(' ', $statusHeader, 3);
// check status for error (range of 400 and 500)
$statusNum = floor($statusInfo[1] / 100);
if ($statusNum == 4 || $statusNum == 5) {
throw new Solarium_Client_HttpException(
$statusInfo[2],
$statusInfo[1]
);
}
} }
/**
* Decode json response data
*
* @throws Solarium_Exception
* @param string $data
* @return string
*/
protected function _jsonDecode($data)
{
$data = json_decode($data, true);
if (null === $data) {
throw new Solarium_Exception(
'Solr JSON response could not be decoded'
);
}
return $data;
}
} }
\ No newline at end of file
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
...@@ -42,13 +43,12 @@ ...@@ -42,13 +43,12 @@
* configuration options. For more info see the manual at * configuration options. For more info see the manual at
* {@link http://framework.zend.com/manual/en/zend.http.html} * {@link http://framework.zend.com/manual/en/zend.http.html}
* *
* To use this adapter you need to have the Zend Framework in your include path, * To use this adapter you need to have the Zend Framework available (autoloading)
* autoloader or manually included.
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
*/ */
class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter
{ {
/** /**
...@@ -63,7 +63,7 @@ class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http ...@@ -63,7 +63,7 @@ class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http
* *
* Overrides any existing values. * Overrides any existing values.
* *
* If the options array has an 'adapteroptions' entry it is forwarded to the * If the options array has an 'options' entry it is forwarded to the
* Zend_Http_Client. See the Zend_Http_Clientdocs for the many config * Zend_Http_Client. See the Zend_Http_Clientdocs for the many config
* options available. * options available.
* *
...@@ -71,24 +71,25 @@ class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http ...@@ -71,24 +71,25 @@ class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http
* method, like Zend_Config * method, like Zend_Config
* *
* @param array|object $options * @param array|object $options
* @param boolean $overwrite
* @return Solarium_Client_Adapter_ZendHttp Provides fluent interface * @return Solarium_Client_Adapter_ZendHttp Provides fluent interface
*/ */
public function setOptions($options) public function setOptions($options, $overwrite = false)
{ {
parent::setOptions($options); parent::setOptions($options, $overwrite);
// forward options to zendHttp instance // forward options to zendHttp instance
if (null !== $this->_zendHttp) { if (null !== $this->_zendHttp) {
// forward timeout setting // forward timeout setting
$this->_zendHttp->setConfig( $adapterOptions = array('timeout' => $this->getTimeout());
array('timeout' => $this->getOption('timeout'))
);
// forward adapter options if available // forward adapter options if available
if (isset($this->_options['adapteroptions'])) { if (isset($this->_options['options'])) {
$this->_zendHttp->setConfig($this->_options['adapteroptions']); $adapterOptions = array_merge($adapterOptions, $this->_options['options']);
} }
$this->_zendHttp->setConfig($adapterOptions);
} }
return $this; return $this;
...@@ -126,10 +127,12 @@ class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http ...@@ -126,10 +127,12 @@ class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http
{ {
if (null == $this->_zendHttp) { if (null == $this->_zendHttp) {
$options = array('timeout' => $this->getOption('timeout')); $options = array('timeout' => $this->getOption('timeout'));
if (isset($this->_options['adapteroptions'])) {
// forward zendhttp options
if (isset($this->_options['options'])) {
$options = array_merge( $options = array_merge(
$options, $options,
$this->_options['adapteroptions'] $this->_options['options']
); );
} }
...@@ -143,14 +146,14 @@ class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http ...@@ -143,14 +146,14 @@ class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http
* Execute a Solr request using the Zend_Http_Client instance * Execute a Solr request using the Zend_Http_Client instance
* *
* @param Solarium_Client_Request $request * @param Solarium_Client_Request $request
* @return string * @return Solarium_Client_Response
*/ */
protected function _handleRequest($request) public function execute($request)
{ {
$client = $this->getZendHttp(); $client = $this->getZendHttp();
$client->setMethod($request->getMethod()); $client->setMethod($request->getMethod());
$client->setUri($request->getUri()); $client->setUri($this->getBaseUri() . $request->getUri());
$client->setRawData($request->getRawData()); $client->setRawData($request->getRawData());
$response = $client->request(); $response = $client->request();
...@@ -163,23 +166,16 @@ class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http ...@@ -163,23 +166,16 @@ class Solarium_Client_Adapter_ZendHttp extends Solarium_Client_Adapter_Http
); );
} }
if ($request->getMethod() == Solarium_Client_Request::HEAD) { if ($request->getMethod() == Solarium_Client_Request::METHOD_HEAD) {
return true; $data = '';
} else { } else {
$data = $response->getBody(); $data = $response->getBody();
$type = $response->getHeader('Content-Type');
switch ($type) {
case 'text/plain; charset=utf-8':
return $this->_jsonDecode($data);
break;
default:
throw new Solarium_Exception(
'Unknown Content-Type in ZendHttp adapter: ' . $type
);
break;
}
} }
// this is used because getHeaders doesn't return the HTTP header...
$headers = explode("\n", $response->getHeadersAsString());
return new Solarium_Client_Response($data, $headers);
} }
} }
\ No newline at end of file
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
...@@ -78,7 +79,7 @@ class Solarium_Client_HttpException extends Solarium_Exception ...@@ -78,7 +79,7 @@ class Solarium_Client_HttpException extends Solarium_Exception
{ {
$this->_statusMessage = $statusMessage; $this->_statusMessage = $statusMessage;
$message = 'Solr HTTP error, ' . $statusMessage; $message = 'Solr HTTP error: ' . $statusMessage;
if (null !== $code) { if (null !== $code) {
$message .= ' (' . $code . ')'; $message .= ' (' . $code . ')';
} }
......
This diff is collapsed.
<?php
/**
* Copyright 2011 Bas de Nooijer. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this listof conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the copyright holder.
*
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
*
* @package Solarium
* @subpackage Client
*/
/**
* Class for building Solarium client requests
*
* @package Solarium
* @subpackage Client
*/
abstract class Solarium_Client_RequestBuilder
{
/**
* Render a param with localParams
*
* LocalParams can be use in various Solr GET params.
* @link http://wiki.apache.org/solr/LocalParams
*
* @param string $value
* @param array $localParams in key => value format
* @return string with Solr localparams syntax
*/
public function renderLocalParams($value, $localParams = array())
{
$params = '';
foreach ($localParams AS $paramName => $paramValue) {
if (empty($paramValue)) continue;
if (is_array($paramValue)) {
$paramValue = implode($paramValue, ',');
}
$params .= $paramName . '=' . $paramValue . ' ';
}
if ($params !== '') {
$value = '{!' . trim($params) . '}' . $value;
}
return $value;
}
/**
* Render a boolean attribute
*
* For use in building XML messages
*
* @param string $name
* @param boolean $value
* @return string
*/
public function boolAttrib($name, $value)
{
if (null !== $value) {
$value = (true == $value) ? 'true' : 'false';
return $this->attrib($name, $value);
} else {
return '';
}
}
/**
* Render an attribute
*
* For use in building XML messages
*
* @param string $name
* @param striung $value
* @return string
*/
public function attrib($name, $value)
{
if (null !== $value) {
return ' ' . $name . '="' . $value . '"';
} else {
return '';
}
}
}
\ No newline at end of file
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
...@@ -41,31 +42,22 @@ ...@@ -41,31 +42,22 @@
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
*/ */
class Solarium_Client_Request_Ping extends Solarium_Client_Request class Solarium_Client_RequestBuilder_Ping extends Solarium_Client_RequestBuilder
{ {
/** /**
* Get uri * Build request for a ping query
* *
* Uses the default {@link buildUri()} method, no special uri needed in this * @param Solarium_Query_Ping $query
* case. * @return Solarium_Client_Request
*
* @return string
*/ */
public function getUri() public function build($query)
{ {
return $this->buildUri(); $request = new Solarium_Client_Request;
} $request->setHandler($query->getHandler());
$request->setMethod(Solarium_Client_Request::METHOD_HEAD);
/** return $request;
* Get HTTP request method
*
* Ping has no useful result data, so a more optimal HEAD request is used.
*
* @return string
*/
public function getMethod()
{
return self::HEAD;
} }
} }
\ No newline at end of file
<?php
/**
* Copyright 2011 Bas de Nooijer. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this listof conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the copyright holder.
*
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
*
* @package Solarium
* @subpackage Client
*/
/**
* Build a select request
*
* @package Solarium
* @subpackage Client
*/
class Solarium_Client_RequestBuilder_Select extends Solarium_Client_RequestBuilder
{
/**
* Build request for a select query
*
* @param Solarium_Query_Select $query
* @return Solarium_Client_Request
*/
public function build($query)
{
$request = new Solarium_Client_Request;
$request->setHandler($query->getHandler());
// add basic params to request
$request->addParam('q', $query->getQuery());
$request->addParam('start', $query->getStart());
$request->addParam('rows', $query->getRows());
$request->addParam('fl', implode(',', $query->getFields()));
$request->addParam('wt', 'json');
// add sort fields to request
$sort = array();
foreach ($query->getSorts() AS $field => $order) {
$sort[] = $field . ' ' . $order;
}
if (count($sort) !== 0) {
$request->addParam('sort', implode(',', $sort));
}
// add filterqueries to request
$filterQueries = $query->getFilterQueries();
if (count($filterQueries) !== 0) {
foreach ($filterQueries AS $filterQuery) {
$fq = $this->renderLocalParams(
$filterQuery->getQuery(),
array('tag' => $filterQuery->getTags())
);
$request->addParam('fq', $fq);
}
}
// add components to request
$types = $query->getComponentTypes();
foreach ($query->getComponents() as $component) {
$componentBuilderClass = $types[$component->getType()]['requestbuilder'];
if (!empty($componentBuilderClass)) {
$componentBuilder = new $componentBuilderClass;
$request = $componentBuilder->build($component, $request);
}
}
return $request;
}
}
\ No newline at end of file
<?php
/**
* Copyright 2011 Bas de Nooijer. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this listof conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the copyright holder.
*
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
*
* @package Solarium
* @subpackage Client
*/
/**
* Add select component dismax to the request
*
* @package Solarium
* @subpackage Client
*/
class Solarium_Client_RequestBuilder_Select_Component_DisMax
{
/**
* Add request settings for Dismax
*
* @param Solarium_Query_Select_Component_Dismax $component
* @param Solarium_Client_Request $request
* @return Solarium_Client_Request
*/
public function build($component, $request)
{
// enable dismax
$request->addParam('defType', 'dismax');
$request->addParam('q.alt', $component->getQueryAlternative());
$request->addParam('qf', $component->getQueryFields());
$request->addParam('mm', $component->getMinimumMatch());
$request->addParam('pf', $component->getPhraseFields());
$request->addParam('ps', $component->getPhraseSlop());
$request->addParam('qs', $component->getQueryPhraseSlop());
$request->addParam('tie', $component->getTie());
$request->addParam('bq', $component->getBoostQuery());
$request->addParam('bf', $component->getBoostFunctions());
return $request;
}
}
\ No newline at end of file
...@@ -30,71 +30,57 @@ ...@@ -30,71 +30,57 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
*/ */
/** /**
* Build a select request * Add select component FacetSet to the request
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
*/ */
class Solarium_Client_Request_Select extends Solarium_Client_Request class Solarium_Client_RequestBuilder_Select_Component_FacetSet extends Solarium_Client_RequestBuilder
{ {
/** /**
* Get uri * Add request settings for FacetSet
*
* Builds a complex uri based on the query settings
* *
* @throws Solarium_Exception * @param Solarium_Query_Select_Component_FacetSet $component
* @return string * @param Solarium_Client_Request $request
* @return Solarium_Client_Request
*/ */
public function getUri() public function build($component, $request)
{ {
$this->_params = array( $facets = $component->getFacets();
'q' => $this->_query->getQuery(),
'start' => $this->_query->getStart(),
'rows' => $this->_query->getRows(),
'fl' => implode(',', $this->_query->getFields()),
'wt' => 'json',
);
$sort = array();
foreach ($this->_query->getSortFields() AS $field => $order) {
$sort[] = $field . ' ' . $order;
}
if (count($sort) !== 0) {
$this->addParam('sort', implode(',', $sort));
}
$filterQueries = $this->_query->getFilterQueries();
if (count($filterQueries) !== 0) {
foreach ($filterQueries AS $filterQuery) {
$fq = $this->renderLocalParams(
$filterQuery->getQuery(),
array('tag' => $filterQuery->getTags())
);
$this->addParam('fq', $fq);
}
}
$facets = $this->_query->getFacets();
if (count($facets) !== 0) { if (count($facets) !== 0) {
// enable faceting // enable faceting
$this->_params['facet'] = 'true'; $request->addParam('facet', 'true');
// global facet params
$request->addParam('facet.sort', $component->getSort());
$request->addParam('facet.prefix', $component->getPrefix());
$request->addParam('facet.missing', $component->getMissing());
$request->addParam('facet.mincount', $component->getMinCount());
$request->addParam('facet.limit', $component->getLimit());
foreach ($facets AS $facet) { foreach ($facets AS $facet) {
switch ($facet->getType()) switch ($facet->getType())
{ {
case Solarium_Query_Select_Facet::FIELD: case Solarium_Query_Select_Component_FacetSet::FACET_FIELD:
$this->addFacetField($facet); $this->addFacetField($request, $facet);
break;
case Solarium_Query_Select_Component_FacetSet::FACET_QUERY:
$this->addFacetQuery($request, $facet);
break;
case Solarium_Query_Select_Component_FacetSet::FACET_MULTIQUERY:
$this->addFacetMultiQuery($request, $facet);
break; break;
case Solarium_Query_Select_Facet::QUERY: case Solarium_Query_Select_Component_FacetSet::FACET_RANGE:
$this->addFacetQuery($facet); $this->addFacetRange($request, $facet);
break; break;
default: default:
throw new Solarium_Exception('Unknown facet type'); throw new Solarium_Exception('Unknown facet type');
...@@ -102,20 +88,21 @@ class Solarium_Client_Request_Select extends Solarium_Client_Request ...@@ -102,20 +88,21 @@ class Solarium_Client_Request_Select extends Solarium_Client_Request
} }
} }
return $this->buildUri(); return $request;
} }
/** /**
* Add params for a field facet to request * Add params for a field facet to request
* *
* @param mixed $facet * @param Solarium_Client_Request $request
* @param Solarium_Query_Select_Component_Facet_Field $facet
* @return void * @return void
*/ */
public function addFacetField($facet) public function addFacetField($request, $facet)
{ {
$field = $facet->getField(); $field = $facet->getField();
$this->addParam( $request->addParam(
'facet.field', 'facet.field',
$this->renderLocalParams( $this->renderLocalParams(
$field, $field,
...@@ -123,24 +110,25 @@ class Solarium_Client_Request_Select extends Solarium_Client_Request ...@@ -123,24 +110,25 @@ class Solarium_Client_Request_Select extends Solarium_Client_Request
) )
); );
$this->addParam("f.$field.facet.limit", $facet->getLimit()); $request->addParam("f.$field.facet.limit", $facet->getLimit());
$this->addParam("f.$field.facet.sort", $facet->getSort()); $request->addParam("f.$field.facet.sort", $facet->getSort());
$this->addParam("f.$field.facet.prefix", $facet->getPrefix()); $request->addParam("f.$field.facet.prefix", $facet->getPrefix());
$this->addParam("f.$field.facet.offset", $facet->getOffset()); $request->addParam("f.$field.facet.offset", $facet->getOffset());
$this->addParam("f.$field.facet.mincount", $facet->getMinCount()); $request->addParam("f.$field.facet.mincount", $facet->getMinCount());
$this->addParam("f.$field.facet.missing", $facet->getMissing()); $request->addParam("f.$field.facet.missing", $facet->getMissing());
$this->addParam("f.$field.facet.method", $facet->getMethod()); $request->addParam("f.$field.facet.method", $facet->getMethod());
} }
/** /**
* Add params for a field query to request * Add params for a facet query to request
* *
* @param mixed $facet * @param Solarium_Client_Request $request
* @param Solarium_Query_Select_Component_Facet_Query $facet
* @return void * @return void
*/ */
public function addFacetQuery($facet) public function addFacetQuery($request, $facet)
{ {
$this->addParam( $request->addParam(
'facet.query', 'facet.query',
$this->renderLocalParams( $this->renderLocalParams(
$facet->getQuery(), $facet->getQuery(),
...@@ -149,4 +137,52 @@ class Solarium_Client_Request_Select extends Solarium_Client_Request ...@@ -149,4 +137,52 @@ class Solarium_Client_Request_Select extends Solarium_Client_Request
); );
} }
/**
* Add params for a multiquery facet to request
*
* @param Solarium_Client_Request $request
* @param Solarium_Query_Select_Component_Facet_MultiQuery $facet
* @return void
*/
public function addFacetMultiQuery($request, $facet)
{
foreach ($facet->getQueries() AS $facetQuery) {
$this->addFacetQuery($request, $facetQuery);
}
}
/**
* Add params for a range facet to request
*
* @param Solarium_Client_Request $request
* @param Solarium_Query_Select_Component_Facet_Range $facet
* @return void
*/
public function addFacetRange($request, $facet)
{
$field = $facet->getField();
$request->addParam(
'facet.range',
$this->renderLocalParams(
$field,
array('key' => $facet->getKey(), 'ex' => $facet->getExcludes())
)
);
$request->addParam("f.$field.facet.range.start", $facet->getStart());
$request->addParam("f.$field.facet.range.end", $facet->getEnd());
$request->addParam("f.$field.facet.range.gap", $facet->getGap());
$request->addParam("f.$field.facet.range.hardend", $facet->getHardend());
$other = explode(',', $facet->getOther());
foreach ($other AS $otherValue) {
$request->addParam("f.$field.facet.range.other", trim($otherValue));
}
$include = explode(',', $facet->getInclude());
foreach ($include AS $includeValue) {
$request->addParam("f.$field.facet.range.include", trim($includeValue));
}
}
} }
\ No newline at end of file
<?php
/**
* Copyright 2011 Bas de Nooijer. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this listof conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the copyright holder.
*
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
*
* @package Solarium
* @subpackage Client
*/
/**
* Add select component Highlighting to the request
*
* @package Solarium
* @subpackage Client
*/
class Solarium_Client_RequestBuilder_Select_Component_Highlighting
{
/**
* Add request settings for Highlighting
*
* @param Solarium_Query_Select_Component_Highlighting $component
* @param Solarium_Client_Request $request
* @return Solarium_Client_Request
*/
public function build($component, $request)
{
// enable highlighting
$request->addParam('hl', 'true');
$request->addParam('hl.fl', $component->getFields());
$request->addParam('hl.snippets', $component->getSnippets());
$request->addParam('hl.fragsize', $component->getFragSize());
$request->addParam('hl.mergeContiguous', $component->getMergeContiguous());
$request->addParam('hl.requireFieldMatch', $component->getRequireFieldMatch());
$request->addParam('hl.maxAnalyzedChars', $component->getMaxAnalyzedChars());
$request->addParam('hl.alternateField', $component->getAlternateField());
$request->addParam('hl.maxAlternateFieldLength', $component->getMaxAlternateFieldLength());
$request->addParam('hl.formatter', $component->getFormatter());
$request->addParam('hl.simple.pre', $component->getSimplePrefix());
$request->addParam('hl.simple.post', $component->getSimplePostfix());
$request->addParam('hl.fragmenter', $component->getFragmenter());
$request->addParam('hl.fragListBuilder', $component->getFragListBuilder());
$request->addParam('hl.fragmentsBuilder', $component->getFragmentsBuilder());
$request->addParam('hl.useFastVectorHighlighter', $component->getUseFastVectorHighlighter());
$request->addParam('hl.usePhraseHighlighter', $component->getUsePhraseHighlighter());
$request->addParam('hl.highlightMultiTerm', $component->getHighlightMultiTerm());
$request->addParam('hl.regex.slop', $component->getRegexSlop());
$request->addParam('hl.regex.pattern', $component->getRegexPattern());
$request->addParam('hl.regex.maxAnalyzedChars', $component->getRegexMaxAnalyzedChars());
return $request;
}
}
\ No newline at end of file
<?php
/**
* Copyright 2011 Bas de Nooijer. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this listof conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the copyright holder.
*
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
*
* @package Solarium
* @subpackage Client
*/
/**
* Add select component morelikethis to the request
*
* @package Solarium
* @subpackage Client
*/
class Solarium_Client_RequestBuilder_Select_Component_MoreLikeThis
{
/**
* Add request settings for morelikethis
*
* @param Solarium_Query_Select_Component_MoreLikeThis $component
* @param Solarium_Client_Request $request
* @return Solarium_Client_Request
*/
public function build($component, $request)
{
// enable morelikethis
$request->addParam('mlt', 'true');
$request->addParam('mlt.fl', $component->getFields());
$request->addParam('mlt.mintf', $component->getMinimumTermFrequency());
$request->addParam('mlt.mindf', $component->getMinimumDocumentFrequency());
$request->addParam('mlt.minwl', $component->getMinimumWordLength());
$request->addParam('mlt.maxwl', $component->getMaximumWordLength());
$request->addParam('mlt.maxqt', $component->getMaximumQueryTerms());
$request->addParam('mlt.maxntp', $component->getMaximumNumberOfTokens());
$request->addParam('mlt.boost', $component->getBoost());
$request->addParam('mlt.qf', $component->getQueryFields());
$request->addParam('mlt.count', $component->getCount());
return $request;
}
}
\ No newline at end of file
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
...@@ -41,34 +42,24 @@ ...@@ -41,34 +42,24 @@
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
*/ */
class Solarium_Client_Request_Update extends Solarium_Client_Request class Solarium_Client_RequestBuilder_Update extends Solarium_Client_RequestBuilder
{ {
/** /**
* Get HTTP request method * Build request for an update query
* *
* Update uses raw POST data so a POST method has to be used. * @param Solarium_Query_Update $query
* * @return Solarium_Client_Request
* @return string
*/ */
public function getMethod() public function build($query)
{ {
return self::POST; $request = new Solarium_Client_Request;
} $request->setHandler($query->getHandler());
$request->setMethod(Solarium_Client_Request::METHOD_POST);
/** $request->addParam('wt', 'json');
* Get uri $request->setRawData($this->getRawData($query));
*
* Return the default url with the addition of the wt param. return $request;
* This enables a JSON response, that is the easiest and most efficient
* format to decode in the response handler.
*
* @return string
*/
public function getUri()
{
$this->_params = array('wt' => 'json');
return $this->buildUri();
} }
/** /**
...@@ -76,27 +67,28 @@ class Solarium_Client_Request_Update extends Solarium_Client_Request ...@@ -76,27 +67,28 @@ class Solarium_Client_Request_Update extends Solarium_Client_Request
* *
* Each commandtype is delegated to a separate builder method. * Each commandtype is delegated to a separate builder method.
* *
* @param Solarium_Query_Update $query
* @throws Solarium_Exception * @throws Solarium_Exception
* @return string * @return string
*/ */
public function getRawData() public function getRawData($query)
{ {
$xml = '<update>'; $xml = '<update>';
foreach ($this->_query->getCommands() AS $command) { foreach ($query->getCommands() AS $command) {
switch ($command->getType()) { switch ($command->getType()) {
case Solarium_Query_Update_Command::ADD: case Solarium_Query_Update::COMMAND_ADD:
$xml .= $this->buildAddXml($command); $xml .= $this->buildAddXml($command);
break; break;
case Solarium_Query_Update_Command::DELETE: case Solarium_Query_Update::COMMAND_DELETE:
$xml .= $this->buildDeleteXml($command); $xml .= $this->buildDeleteXml($command);
break; break;
case Solarium_Query_Update_Command::OPTIMIZE: case Solarium_Query_Update::COMMAND_OPTIMIZE:
$xml .= $this->buildOptimizeXml($command); $xml .= $this->buildOptimizeXml($command);
break; break;
case Solarium_Query_Update_Command::COMMIT: case Solarium_Query_Update::COMMAND_COMMIT:
$xml .= $this->buildCommitXml($command); $xml .= $this->buildCommitXml($command);
break; break;
case Solarium_Query_Update_Command::ROLLBACK: case Solarium_Query_Update::COMMAND_ROLLBACK:
$xml .= $this->buildRollbackXml(); $xml .= $this->buildRollbackXml();
break; break;
default: default:
...@@ -129,8 +121,7 @@ class Solarium_Client_Request_Update extends Solarium_Client_Request ...@@ -129,8 +121,7 @@ class Solarium_Client_Request_Update extends Solarium_Client_Request
foreach ($doc->getFields() AS $name => $value) { foreach ($doc->getFields() AS $name => $value) {
$boost = $doc->getFieldBoost($name); $boost = $doc->getFieldBoost($name);
if(is_array($value)) if (is_array($value)) {
{
foreach ($value AS $multival) { foreach ($value AS $multival) {
$xml .= $this->_buildFieldXml($name, $boost, $multival); $xml .= $this->_buildFieldXml($name, $boost, $multival);
} }
......
...@@ -30,69 +30,131 @@ ...@@ -30,69 +30,131 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
*/ */
/** /**
* Base class for handling Solr HTTP responses * Class for describing a response
*
* Most {@link Solarium_Client_Adapter} implementations will use HTTP for
* communicating with Solr. While the HTTP part is adapter-specific, the parsing
* of the response into Solarium_Result classes is not. This abstract class is
* the base for several response handlers that do just that for the various
* querytypes.
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
*/ */
abstract class Solarium_Client_Response class Solarium_Client_Response
{ {
/** /**
* Query instance * Headers
* *
* The query that was used for executing a request that led to this * @var array
* response. The query holds important settings for generating the right */
* result, like the resultclass and documentclass settings. protected $_headers;
/**
* Body
* *
* @var Solarium_Query * @var string
*/ */
protected $_query; protected $_body;
/** /**
* Response data * HTTP response code
* *
* A (json)decoded HTTP response body data array. * @var int
*/
protected $_statusCode;
/**
* HTTP response message
* *
* @var array * @var string
*/ */
protected $_data; protected $_statusMessage;
/** /**
* Constructor * Constructor
* *
* @param Solarium_Query $query Query instance that was used for the request * @param string $body
* @param array $data Decoded data array of the HTTP response * @param array $headers
*/ */
public function __construct($query, $data = null) public function __construct($body, $headers = array())
{ {
$this->_query = $query; $this->_body = $body;
$this->_data = $data; $this->_headers = $headers;
$this->_setHeaders($headers);
} }
/** /**
* Get a Solarium_Result instance for the response * Get body data
* *
* When this method is called the actual response parsing is started. * @return string
*/
public function getBody()
{
return $this->_body;
}
/**
* Get response headers
* *
* @internal Must be implemented in descendents because this parsing is * @return array
* query specific. */
public function getHeaders()
{
return $this->_headers;
}
/**
* Get status code
* *
* @abstract * @return int
* @return mixed
*/ */
abstract function getResult(); public function getStatusCode()
{
return $this->_statusCode;
}
/**
* Get status message
*
* @return string
*/
public function getStatusMessage()
{
return $this->_statusMessage;
}
/**
* Set headers
*
* @param array $headers
* @return void
*/
public function _setHeaders($headers)
{
$this->_headers = $headers;
// get the status header
$statusHeader = null;
foreach ($headers AS $header) {
if (substr($header, 0, 4) == 'HTTP') {
$statusHeader = $header;
break;
}
}
if (null == $statusHeader) {
throw new Solarium_Client_HttpException("No HTTP status found");
}
// parse header like "$statusInfo[1]" into code and message
// $statusInfo[1] = the HTTP response code
// $statusInfo[2] = the response message
$statusInfo = explode(' ', $statusHeader, 3);
$this->_statusCode = $statusInfo[1];
$this->_statusMessage = $statusInfo[2];
}
} }
\ No newline at end of file
<?php
/**
* Copyright 2011 Bas de Nooijer. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this listof conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the copyright holder.
*
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
*
* @package Solarium
* @subpackage Client
*/
/**
* Base class for handling Solr response data
*
* Most {@link Solarium_Client_Adapter} implementations will use HTTP for
* communicating with Solr. While the HTTP part is adapter-specific, the parsing
* of the response into Solarium_Result classes is not. This abstract class is
* the base for several response handlers that do just that for the various
* querytypes.
*
* @package Solarium
* @subpackage Client
*/
abstract class Solarium_Client_ResponseParser
{
/**
* Get a Solarium_Result instance for the given data
*
* When this method is called the actual response parsing is started.
*
* @internal Must be implemented in descendents because this parsing is
* query specific.
*
* @abstract
*
* @param Solarium_Result $result
* @return mixed
*/
abstract function parse($result);
}
\ No newline at end of file
...@@ -30,62 +30,60 @@ ...@@ -30,62 +30,60 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client
*/ */
/** /**
* Escape data for usage in a Solr query * Parse select response data
*
* Any (user) input for a query can be passed to one of the escape methods to
* prevent any issues with special characters.
*
* Do mind that you cannot build a complete query first and then pass it to
* this method, the whole query will be escaped. You need to escape only the
* 'content' of your query.
* *
* @package Solarium * @package Solarium
* @subpackage Client
*/ */
class Solarium_Escape class Solarium_Client_ResponseParser_Select extends Solarium_Client_ResponseParser
{ {
/** /**
* Escape a term * Get result data for the response
*
* A term is a single word.
* All characters that have a special meaning in a Solr query are escaped.
* *
* If you want to use the input as a phrase please use the {@link phrase()} * @param Solarium_Result_Select $result
* method, because a phrase requires much less escaping.\ * @return array
*
* @link http://lucene.apache.org/java/docs/queryparsersyntax.html#Escaping%20Special%20Characters
*
* @param string $input
* @return string
*/ */
static public function term($input) public function parse($result)
{ {
$pattern = '/(\+|-|&&|\|\||!|\(|\)|\{|}|\[|]|\^|"|~|\*|\?|:|\\\)/'; $data = $result->getData();
$query = $result->getQuery();
return preg_replace($pattern, '\\\$1', $input); // create document instances
} $documentClass = $query->getOption('documentclass');
$documents = array();
if (isset($data['response']['docs'])) {
foreach ($data['response']['docs'] AS $doc) {
$fields = (array)$doc;
$documents[] = new $documentClass($fields);
}
}
/** // component results
* Escape a phrase $components = array();
* $types = $query->getComponentTypes();
* A phrase is a group of words. foreach ($query->getComponents() as $component) {
* Special characters will be escaped and the phrase will be surrounded by $componentParserClass = $types[$component->getType()]['responseparser'];
* double quotes to group the input into a single phrase. So don't put if (!empty($componentParserClass)) {
* quotes around the input. $componentParser = new $componentParserClass;
* $components[$component->getType()] = $componentParser->parse($query, $component, $data);
* @param string $input }
* @return string }
*/
static public function phrase($input) return array(
{ 'status' => $data['responseHeader']['status'],
return '"' . preg_replace('/("|\\\)/', '\\\$1', $input) . '"'; 'queryTime' => $data['responseHeader']['QTime'],
'numfound' => $data['response']['numFound'],
'documents' => $documents,
'components' => $components,
);
} }
} }
\ No newline at end of file
...@@ -30,90 +30,81 @@ ...@@ -30,90 +30,81 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
*/ */
/** /**
* Parse select response data * Parse select component FacetSet result from the data
*
* Will create a result object based on response data of the type
* {@Solarium_Result_Select} (or your own resultclass setting)
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
*/ */
class Solarium_Client_Response_Select extends Solarium_Client_Response class Solarium_Client_ResponseParser_Select_Component_FacetSet
{ {
/** /**
* Facet results * Parse result data into result objects
*
* Filled by the _addFacet* methods (for instance {@_addFacetField()})
* *
* @var array * @param Solarium_Query_Select $query
* @param Solarium_Query_Select_Component_FacetSet $facetSet
* @param array $data
* @return Solarium_Result_Select_FacetSet
*/ */
protected $_facets = array(); public function parse($query, $facetSet, $data)
/**
* Get a result instance for the response
*
* When this method is called the actual response parsing is done.
*
* @return mixed
*/
public function getResult()
{ {
// create document instances $facets = array();
$documentClass = $this->_query->getOption('documentclass'); foreach ($facetSet->getFacets() AS $key => $facet) {
$documents = array();
if (isset($this->_data['response']['docs'])) {
foreach ($this->_data['response']['docs'] AS $doc) {
$fields = (array)$doc;
$documents[] = new $documentClass($fields);
}
}
// create facet results
foreach ($this->_query->getFacets() AS $facet) {
switch ($facet->getType()) { switch ($facet->getType()) {
case Solarium_Query_Select_Facet::FIELD: case Solarium_Query_Select_Component_FacetSet::FACET_FIELD:
$this->_addFacetField($facet); $result = $this->_facetField($facet, $data);
break;
case Solarium_Query_Select_Component_FacetSet::FACET_QUERY:
$result = $this->_facetQuery($facet, $data);
break; break;
case Solarium_Query_Select_Facet::QUERY: case Solarium_Query_Select_Component_FacetSet::FACET_MULTIQUERY:
$this->_addFacetQuery($facet); $result = $this->_facetMultiQuery($facet, $data);
break;
case Solarium_Query_Select_Component_FacetSet::FACET_RANGE:
$result = $this->_facetRange($facet, $data);
break; break;
default: default:
throw new Solarium_Exception('Unknown facet type'); throw new Solarium_Exception('Unknown facet type');
} }
if($result !== null) $facets[$key] = $result;
} }
// add general data return $this->_createFacetSet($facets);
$status = $this->_data['responseHeader']['status']; }
$queryTime = $this->_data['responseHeader']['QTime'];
$numFound = $this->_data['response']['numFound'];
// create the result instance that combines all data /**
$resultClass = $this->_query->getOption('resultclass'); * Create a facetset result object
return new $resultClass( *
$status, $queryTime, $numFound, $documents, $this->_facets * @param array $facets
); * @return Solarium_Result_Select_FacetSet
*/
protected function _createFacetSet($facets)
{
return new Solarium_Result_Select_FacetSet($facets);
} }
/** /**
* Add a facet result for a field facet * Add a facet result for a field facet
* *
* @param mixed $facet * @param Solarium_Query_Select_Component_Facet_Field $facet
* @param array $data
* @return void * @return void
*/ */
protected function _addFacetField($facet) protected function _facetField($facet, $data)
{ {
$key = $facet->getKey(); $key = $facet->getKey();
if (isset($this->_data['facet_counts']['facet_fields'][$key])) { if (isset($data['facet_counts']['facet_fields'][$key])) {
$values = array_chunk( $values = array_chunk(
$this->_data['facet_counts']['facet_fields'][$key], $data['facet_counts']['facet_fields'][$key],
2 2
); );
...@@ -122,25 +113,71 @@ class Solarium_Client_Response_Select extends Solarium_Client_Response ...@@ -122,25 +113,71 @@ class Solarium_Client_Response_Select extends Solarium_Client_Response
$facetValues[$value[0]] = $value[1]; $facetValues[$value[0]] = $value[1];
} }
$this->_facets[$key] = return new Solarium_Result_Select_Facet_Field($facetValues);
new Solarium_Result_Select_Facet_Field($facetValues);
} }
} }
/** /**
* Add a facet result for a field query * Add a facet result for a facet query
* *
* @param mixed $facet * @param Solarium_Query_Select_Component_Facet_Query $facet
* @param array $data
* @return void * @return void
*/ */
protected function _addFacetQuery($facet) protected function _facetQuery($facet, $data)
{ {
$key = $facet->getKey(); $key = $facet->getKey();
if (isset($this->_data['facet_counts']['facet_queries'][$key])) { if (isset($data['facet_counts']['facet_queries'][$key])) {
$value = $this->_data['facet_counts']['facet_queries'][$key]; $value = $data['facet_counts']['facet_queries'][$key];
$this->_facets[$key] = return new Solarium_Result_Select_Facet_Query($value);
new Solarium_Result_Select_Facet_Query($value);
} }
} }
/**
* Add a facet result for a multiquery facet
*
* @param Solarium_Query_Select_Component_Facet_MultiQuery $facet
* @param array $data
* @return void
*/
protected function _facetMultiQuery($facet, $data)
{
$values = array();
foreach ($facet->getQueries() AS $query) {
$key = $query->getKey();
if (isset($data['facet_counts']['facet_queries'][$key])) {
$count = $data['facet_counts']['facet_queries'][$key];
$values[$key] = $count;
}
}
if (count($values) > 0) {
return new Solarium_Result_Select_Facet_MultiQuery($values);
}
}
/**
* Add a facet result for a range facet
*
* @param Solarium_Query_Select_Component_Facet_Range $facet
* @param array $data
* @return void
*/
protected function _facetRange($facet, $data)
{
$key = $facet->getKey();
if (isset($data['facet_counts']['facet_ranges'][$key])) {
$data = $data['facet_counts']['facet_ranges'][$key];
$before = (isset($data['before'])) ? $data['before'] : null;
$after = (isset($data['after'])) ? $data['after'] : null;
$between = (isset($data['between'])) ? $data['between'] : null;
return new Solarium_Result_Select_Facet_Range($data['counts'], $before, $after, $between);
}
}
} }
\ No newline at end of file
<?php
/**
* Copyright 2011 Bas de Nooijer. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this listof conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the copyright holder.
*
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
*
* @package Solarium
* @subpackage Client
*/
/**
* Parse select component Highlighting result from the data
*
* @package Solarium
* @subpackage Client
*/
class Solarium_Client_ResponseParser_Select_Component_Highlighting
{
/**
* Parse result data into result objects
*
* @param Solarium_Query_Select $query
* @param Solarium_Query_Select_Component_Highlighting $highlighting
* @param array $data
* @return Solarium_Result_Select_Highlighting
*/
public function parse($query, $highlighting, $data)
{
$results = array();
if (isset($data['highlighting'])) {
$highlightResults = $data['highlighting'];
foreach ($highlightResults AS $key => $result) {
$results[$key] = new Solarium_Result_Select_Highlighting_Result(
$result
);
}
}
return new Solarium_Result_Select_Highlighting($results);
}
}
\ No newline at end of file
<?php
/**
* Copyright 2011 Bas de Nooijer. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this listof conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of the copyright holder.
*
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
*
* @package Solarium
* @subpackage Client
*/
/**
* Parse select component MoreLikeThis result from the data
*
* @package Solarium
* @subpackage Client
*/
class Solarium_Client_ResponseParser_Select_Component_MoreLikeThis
{
/**
* Parse result data into result objects
*
* @param Solarium_Query_Select $query
* @param Solarium_Query_Select_Component_MoreLikeThis $moreLikeThis
* @param array $data
* @return Solarium_Result_Select_MoreLikeThis
*/
public function parse($query, $moreLikeThis, $data)
{
$results = array();
if (isset($data['moreLikeThis'])) {
$documentClass = $query->getOption('documentclass');
$searchResults = $data['moreLikeThis'];
foreach ($searchResults AS $key => $result) {
// create document instances
$docs = array();
foreach ($result['docs'] AS $fields) {
$docs[] = new $documentClass($fields);
}
$results[$key] = new Solarium_Result_Select_MoreLikeThis_Result(
$result['numFound'],
$result['maxScore'],
$docs
);
}
}
return new Solarium_Result_Select_MoreLikeThis($results);
}
}
\ No newline at end of file
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
...@@ -38,29 +39,25 @@ ...@@ -38,29 +39,25 @@
/** /**
* Parse update response data * Parse update response data
* *
* Will create a result object based on response data of the type
* {@Solarium_Result_Update} (or your own resultclass setting)
*
* @package Solarium * @package Solarium
* @subpackage Client * @subpackage Client
*/ */
class Solarium_Client_Response_Update extends Solarium_Client_Response class Solarium_Client_ResponseParser_Update extends Solarium_Client_ResponseParser
{ {
/** /**
* Get a result instance for the response * Parse response data
*
* When this method is called the actual response parsing is done.
* *
* @return mixed * @param Solarium_Result_Update $result
* @return array
*/ */
public function getResult() public function parse($result)
{ {
$resultClass = $this->_query->getOption('resultclass'); $data = $result->getData();
return new $resultClass( return array(
$this->_data['responseHeader']['status'], 'status' => $data['responseHeader']['status'],
$this->_data['responseHeader']['QTime'] 'queryTime' => $data['responseHeader']['QTime'],
); );
} }
......
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
*/ */
...@@ -58,7 +59,7 @@ class Solarium_Configurable ...@@ -58,7 +59,7 @@ class Solarium_Configurable
* Constructor * Constructor
* *
* If options are passed they will be merged with {@link $_options} using * If options are passed they will be merged with {@link $_options} using
* the {@link _setOptions()} method. * the {@link setOptions()} method.
* *
* After handling the options the {@link _init()} method is called. * After handling the options the {@link _init()} method is called.
* *
...@@ -68,9 +69,11 @@ class Solarium_Configurable ...@@ -68,9 +69,11 @@ class Solarium_Configurable
*/ */
public function __construct($options = null) public function __construct($options = null)
{ {
$this->_setOptions($options); if (null !== $options) {
$this->setOptions($options);
$this->_init(); } else {
$this->_init();
}
} }
/** /**
...@@ -87,7 +90,7 @@ class Solarium_Configurable ...@@ -87,7 +90,7 @@ class Solarium_Configurable
* *
* @return void * @return void
*/ */
protected function _setOptions($options, $overwrite = false) public function setOptions($options, $overwrite = false)
{ {
if (null !== $options) { if (null !== $options) {
// first convert to array if needed // first convert to array if needed
...@@ -105,6 +108,9 @@ class Solarium_Configurable ...@@ -105,6 +108,9 @@ class Solarium_Configurable
} else { } else {
$this->_options = array_merge($this->_options, $options); $this->_options = array_merge($this->_options, $options);
} }
// re-init for new options
$this->_init();
} }
} }
......
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Document * @subpackage Document
......
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Document * @subpackage Document
...@@ -123,7 +124,7 @@ class Solarium_Document_ReadWrite extends Solarium_Document_ReadOnly ...@@ -123,7 +124,7 @@ class Solarium_Document_ReadWrite extends Solarium_Document_ReadOnly
*/ */
public function setField($key, $value, $boost = null) public function setField($key, $value, $boost = null)
{ {
if ($value == null) { if ($value === null) {
$this->removeField($key); $this->removeField($key);
} else { } else {
$this->_fields[$key] = $value; $this->_fields[$key] = $value;
...@@ -202,6 +203,19 @@ class Solarium_Document_ReadWrite extends Solarium_Document_ReadOnly ...@@ -202,6 +203,19 @@ class Solarium_Document_ReadWrite extends Solarium_Document_ReadOnly
return $this->_boost; return $this->_boost;
} }
/**
* Clear all fields
*
* @return Solarium_Document_ReadWrite Provides fluent interface
**/
public function clear()
{
$this->_fields = array();
$this->_fieldBoosts = array();
return $this;
}
/** /**
* Set field value * Set field value
* *
......
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
*/ */
......
This diff is collapsed.
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Query * @subpackage Query
...@@ -41,8 +42,22 @@ ...@@ -41,8 +42,22 @@
* @package Solarium * @package Solarium
* @subpackage Query * @subpackage Query
*/ */
class Solarium_Query extends Solarium_Configurable abstract class Solarium_Query extends Solarium_Configurable
{ {
/**
* Helper instance
*
* @var Solarium_Query_Helper
*/
protected $_helper;
/**
* Get type for this query
*
* @return string
*/
abstract public function getType();
/** /**
* Set handler option * Set handler option
...@@ -93,4 +108,20 @@ class Solarium_Query extends Solarium_Configurable ...@@ -93,4 +108,20 @@ class Solarium_Query extends Solarium_Configurable
return $this->getOption('resultclass'); return $this->getOption('resultclass');
} }
/**
* Get a helper instance
*
* Uses lazy loading: the helper is instantiated on first use
*
* @return Solarium_Query_Helper
*/
public function getHelper()
{
if (null === $this->_helper) {
$this->_helper = new Solarium_Query_Helper;
}
return $this->_helper;
}
} }
\ No newline at end of file
This diff is collapsed.
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Query * @subpackage Query
...@@ -48,12 +49,23 @@ ...@@ -48,12 +49,23 @@
class Solarium_Query_Ping extends Solarium_Query class Solarium_Query_Ping extends Solarium_Query
{ {
/**
* Get type for this query
*
* @return string
*/
public function getType()
{
return Solarium_Client::QUERYTYPE_PING;
}
/** /**
* Default options * Default options
* *
* @var array * @var array
*/ */
protected $_options = array( protected $_options = array(
'resultclass' => 'Solarium_Result_Ping',
'handler' => 'admin/ping', 'handler' => 'admin/ping',
); );
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Query * @subpackage Query
...@@ -43,7 +44,7 @@ ...@@ -43,7 +44,7 @@
* @package Solarium * @package Solarium
* @subpackage Query * @subpackage Query
*/ */
class Solarium_Query_Select_Facet_Query extends Solarium_Query_Select_Facet class Solarium_Query_Select_Component_Facet_Query extends Solarium_Query_Select_Component_Facet
{ {
/** /**
...@@ -62,7 +63,7 @@ class Solarium_Query_Select_Facet_Query extends Solarium_Query_Select_Facet ...@@ -62,7 +63,7 @@ class Solarium_Query_Select_Facet_Query extends Solarium_Query_Select_Facet
*/ */
public function getType() public function getType()
{ {
return self::QUERY; return Solarium_Query_Select_Component_FacetSet::FACET_QUERY;
} }
/** /**
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
* *
* @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl> * @copyright Copyright 2011 Bas de Nooijer <solarium@raspberry.nl>
* @license http://github.com/basdenooijer/solarium/raw/master/COPYING * @license http://github.com/basdenooijer/solarium/raw/master/COPYING
* @link http://www.solarium-project.org/
* *
* @package Solarium * @package Solarium
* @subpackage Query * @subpackage Query
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment