Skip to content

Commit

Permalink
Merge pull request #26 from mhh1422/master
Browse files Browse the repository at this point in the history
Update the phpDoc and README
  • Loading branch information
mhh1422 committed Mar 22, 2016
2 parents d8f1c27 + d00cdbe commit a5e8f24
Show file tree
Hide file tree
Showing 10 changed files with 682 additions and 111 deletions.
59 changes: 57 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
#ElasticSearch Mapper (es-mapper)
This is a simple ORM mapper for ElasticSearch on PHP.
This is a simple ORM mapper for ElasticSearch for PHP.

ElasticSearch DSL query builder for PHP.

##Requirements
- PHP 5.4+
- Elasticsearch PHP SDK v>=1 and <2
- ElasticSearch server 1.6. ES2 is not tested, so use with care.

##Installation
###Composer
```composer require itvisionsy/php-es-orm```

please note it requires Elasticsearch PHP SDK v>=1 and <2
###Manual download
Head to the latest version [here](https://github.com/itvisionsy/php-es-mapper/releases/latest) then download using one download button.

##How to use?

**For the Query Builder, [read this README instead](./query_biulder_README.md)**

That is simple:

### Per index query:
Expand All @@ -29,6 +40,50 @@ Methods' parameters are mapped to original elasticsearch methods and parameters
* `::find(scalar)` and `::find(scalar[])` methods are mapped to [get](https://github.com/elastic/elasticsearch-php/blob/master/src/Elasticsearch/Client.php#L167) and [mget](https://github.com/elastic/elasticsearch-php/blob/master/src/Elasticsearch/Client.php#L671) methods respectively.
* `::query` method is mapped to the [search](https://github.com/elastic/elasticsearch-php/blob/master/src/Elasticsearch/Client.php#L1002) method, and the $query param will be passed as is after appending the index and type parameters to it.

###Querying for data
The query class is just a simple interface allows you to send DSL queries, or perform other ElasticSearch requests.
The `::query()` method for example will expect to receive an assoc-array with a well-formed DSL query.

However, you can use the query builder to builder the query and get a well-formed DSL array out of it.

You can use a type-query query builder to build the query and execute it directly:
```PHP
$result = TypeQuery::builder()
->where('key1','some value')
->where('key2',$intValue,'>')
->where('key3','value','!=')
->where('key4', ['value1','value2'])
->execute();
//$result is a \ItvisionSy\EsMapper\Result instance
```

Or you can use a generic query builder to build the query then you can modify it using other tools:
```PHP
//init a builder object
$builder = \ItvisionSy\EsMapper\QueryBuilder::make();

//build the query using different methods
$query = $builder
->where('key1','some value') //term clause
->where('key2',$intValue,'>') //range clause
->where('key3','value','!=') //must_not term clause
->where('key4', ['value1','value2']) //terms clause
->where('email', '@hotmail.com', '*=') //wildcard search for all @hotmail.com emails
->sort('key1','asc') //first sort option
->sort('key2',['order'=>'asc','mode'=>'avg']) //second sort option
->from(20)->size(20) //results from 20 to 39
->toArray();

//modify the query as you need
$query['aggs']=['company'=>['terms'=>['field'=>'company']]];

//then execute it against a type query
$result = TypeQuery::query($query);
//$result is a \ItvisionSy\EsMapper\Result instance
```

Please refer to [this file](./query_builder_README.md) for more detailed information.

##Retrieving results
The returned result set implements the ArrayAccess interface to access specific document inside the result. i.e.
```PHP
Expand Down
147 changes: 147 additions & 0 deletions query_builder_README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
#ElasticSearch DSL Query Builder Class
This is a simple Query Builder for ElasticSearch DSL language

##Installation
It comes with the [php-es-mapper package](http://github.com/itvisionsy/php-es-mapper).
Read about it [here](./README.md).

##How to use
There are two ways to instantiate a builder object.

###Generic query builder
The query builder is not related to a specific TypeQuery class, it helps to build the query array and retrieve it.
The built array will be then explicitly sent to some query class for execution.
```PHP
//init a builder object
$builder = \ItvisionSy\EsMapper\QueryBuilder::make();

//build the query using different methods
$query = $builder
->where('key1','some value') //term clause
->where('key2',$intValue,'>') //range clause
->where('key3','value','!=') //must_not term clause
->where('key4', ['value1','value2']) //terms clause
->where('email', '@hotmail.com', '*=') //wildcard search for all @hotmail.com emails
->sort('key1','asc') //first sort option
->sort('key2',['order'=>'asc','mode'=>'avg']) //second sort option
->from(20)->size(20) //results from 20 to 39
->toArray();

//modify the query as you need
$query['aggs']=['company'=>['terms'=>['field'=>'company']]];

//then execute it against a type query
$result = TypeQuery::query($query);
//$result is a \ItvisionSy\EsMapper\Result instance
```

###Auto implicit query builder
This type is implicitly created using a `TypeQuery::builder()` method.

It acts like the generic query builder, but in addition to everything the generic query builder can do,
it allows you to execute the result query directly from within the query builder instant itself.

```PHP
$result = TypeQuery::builder()
->where('key1','some value') //term clause
->where('key2',$intValue,'>') //range clause
->where('key3','value','!=') //must_not term clause
->where('key4', ['value1','value2']) //terms clause
->where('email', '@hotmail.com', '*=') //wildcard search for all @hotmail.com emails
->sort('key1','asc') //first sort option
->sort('key2',['order'=>'asc','mode'=>'avg']) //second sort option
->from(20)->size(20) //results from 20 to 39
->execute();
//$result is a \ItvisionSy\EsMapper\Result instance
```

##Building a query

###The available ElasticSearch methods
The query builder allows the main filter/query clauses: `term`, `match`, `wildcard`, `range`, and `prefix`.
Each of these methods can be used against a key, or multiple keys, or a value, or multiple values, giving
flexible way to build up a really complex queries.

###The smart `where` method
The `::where($key, $value, $compare, $filter)` method is also provided, which will scan, detect, and convert
itself to one of the previous available methods. You can use the $compare to tell it what you are looking for,
and the $filter to enforce a filter or query clause.

###Sorting
The `::sort($key, $order)` allows you to add multiple sort levels.

The `$order` parameter can be a simple 'desc' or 'asc' value, or can be an assoc array as per ElasticSearch [sort documentation](https://www.elastic.co/guide/en/elasticsearch/reference/1.6/search-request-sort.html).

The third `$override` parameter allows you to clear the sort section before adding the sort terms.


###Pagination
You can use `from`, and/or `size` for detailed control, or use the `page($size, $from)` which will make two different calls to each method alone.

###Extra methods
If you need to add extra clauses, there are several methods which allow you to:
`raw`, `rawMustFilter`, `rawMustQuery`, `rawMustNotFilter`, `rawMustNotQuery`, `rawShouldFilter`, and `rawShouldQuery`.

The raw query allows you to add any query/filter clause as an assoc-array to one of the filter/query [bool](https://www.elastic.co/guide/en/elasticsearch/reference/1.6/query-dsl-bool-query.html) clause sections.

###Sub queries

Sub queries will be automatically created when needed. However, you can add subqueries using the `andWhere` and/or `orWhere` methods.

Each of the two methods will start a new subquery, and returns a new query builder object of class `\ItvisionSy\EsMapper\SubQueryBuilder` where you can add extra filter clauses as you want.

When you are done with the subquery, you can finish it and return to the main query by calling the `->endSubQuery()` method.

For now, the subqueries can only be added to the filter bool clause sections.

##Finish the query

###Get the final query array/JSON
Once done, call the `->toArray()` or `->toJSON()` to get the final query array or JSON string.

###Empty the query
You can also empty the query and start a new query. This is handy if you have a main base query and you want to execute it multiple time with some minor changes.
```PHP
$baseQuery = [
'query'=>[
'filtered'=>[
'filter'=>[
'bool'=>[
//some complex base query
]
]
]
]
];
$builder = CustomersTypeQuery::builder($baseQuery);
$page1 = $builder->page(10,0)->execute();
$page2 = $builder->emptyQuery($baseQuery)->page(10,10)->execute();
```
This is just a sample to show you how the empty query works. You can come up with different use cases and scenarios.

###Execute the query
If the main query builder is instantiated from within a `TypeQueryInterface` compliant query class, then you can execute the query directly using the `->execute()` method.

This method is going to call the instanciator TypeQuery `query` method passing the final query array as a parameter.

##Sample
```PHP
$result = CustomersQuery::builder() //all customers
->where('email','@hotmail.com', '*=') //who have hotmail.com emails
->where(['created','updated'],['today','yesterday']) //and were active today or yesterday
->orWhere() //starts a subquery
->where('country',['UAE','KSA','TUR']) //where country is UAE, KSA, or TUR
->where('age', [10,20], '<=>=') //or the age is between 10 and 20 years
->endSubQuery() //ends the sub query to the main query
->rawMustNotFilter([ //add a raw nested must-not filter
'nested'=>[
'path'=>'visits',
'filter'=>[
'term'=>['ip'=>'192.168.0.5']
]
]
]) //where none of their visits from a specific ip
->sort('updated','desc') //most recent first
->page(10, 20) //10 results starting from 20
->execute();
```
13 changes: 13 additions & 0 deletions src/ArrayObject.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
<?php

/**
* Copyright (c) 2015, Muhannad Shelleh
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

namespace ItvisionSy\EsMapper;

use ArrayObject as PHPArrayObject;

/**
* A simple model holder which is an implemnetation of the ArrayObject PHP class
*
* @package ItvisionSy\EsMapper
* @author Muhannad Shelleh <[email protected]>
*/
class ArrayObject extends PHPArrayObject implements IModel {
Expand Down
33 changes: 20 additions & 13 deletions src/AutoQueryBuilder.php
Original file line number Diff line number Diff line change
@@ -1,48 +1,55 @@
<?php

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
/**
* Copyright (c) 2015, Muhannad Shelleh
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

namespace ItvisionSy\EsMapper;

use BadMethodCallException;

/**
* Description of AutoQueryBuilder
* A DSL query builder class with a support of execution against a Query class.
*
* @author muhannad
* @package ItvisionSy\EsMapper
* @author Muhannad Shelleh <[email protected]>
*/
class AutoQueryBuilder extends QueryBuilder {

protected $queryInstance;

/**
* Sets the query instance to be used
*
* @param Query $instance
* @return AutoQueryBuilder
*/
public function setQueryInstance(Query $instance){
public function setQueryInstance(Query $instance) {
$this->queryInstance = $instance;
return $this;
}

/**
* Executes the query against the passed query instance
*
* @return Result
* @throws BadMethodCallException
*/
public function execute(){
if(!$this->queryInstance){
public function execute() {
if (!$this->queryInstance) {
throw new BadMethodCallException("Query instance is not passed. Consider calling \$object->setQueryInstance(\$istance) first");
}
return $this->queryInstance->query($this->toArray());
}

/**
* Initiates a new query builder for a specific Query instance
*
Expand All @@ -54,7 +61,7 @@ public function execute(){
* @param array $query
* @return AutoQueryBuilder
*/
public static function makeForQueryInstance(Query $instance, array $query = []){
public static function makeForQueryInstance(Query $instance, array $query = []) {
$query = static::make($query);
return $query->setQueryInstance($instance);
}
Expand Down
18 changes: 17 additions & 1 deletion src/IModel.php
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
<?php

/**
* Copyright (c) 2015, Muhannad Shelleh
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

namespace ItvisionSy\EsMapper;

use ArrayAccess;
use Iterator;

/**
* Interface for any result model class
*
* @package ItvisionSy\EsMapper
* @author Muhannad Shelleh <[email protected]>
*/
interface IModel {
interface IModel extends ArrayAccess, Iterator {

public static function make(array $array);
}
Loading

0 comments on commit a5e8f24

Please sign in to comment.