Search-documents
Search documents
With some documents in the index we can start searching. A basic search is executing a query against elasticsearch. The result of a query then can be filtered by defining some filters. Additionally you can aggregate Documents to create metadata or graphs based on filters. For further information check out the Query DSL and the Aggregations reference. In this example we don’t use all possible options to keep it simple.
Search
The Search
class is one of most flexible entry points in Elastica to query elasticsearch form your PHP application. Other classes which can execute queries are: Index
, Type
, Bulk
and even Client
for raw queries.
Search
class provides useful methods and constants to configure your search query.
1
|
|
Add indices and types
1 2 3 4 5 6 |
|
Add search options
1 2 3 |
|
Query
You may have noticed that the most important part of a search query is actually missing: the query. Because this is the most complicated (and fun) part of elasticsearch, Elastica provides a bunch of classes to help you creating that part of your search query.
Query
is dedicated to the “body” of request body search. It provides a method for every configuration field:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Also it’s possible to provide an array to create a new search. This array follows Elasticsearch request structure, e.g.:
1 2 3 4 5 6 7 |
|
For further information check out the official documentation.
And for very basic searches it’s also possible to just search for a term:
1 2 3 4 5 |
|
QueryBuilder
In order to set query
, aggregation
, suggest
and facet
query parts, you can create the corresponding classes like
1 2 3 4 5 6 7 |
|
to create more complex queries use QueryBuilder to construct all of the different parts of your query. QueryBuilder
is going to check, whether the method you want to use is available in your current elasticsearch version or not.
1 2 3 4 5 6 7 |
|
Now just start to write your query as you would write the raw JSON. If your IDE is configured correctly you should experience a handy way to access all available methods in elasticsearch.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 |
|
1 2 3 |
|
Facets are not supported by QueryBuilder. You should really have a look into aggregations, they are much powerful then facets!
Retrieve results
To execute your search query just choose one of the following methods:
count API
1
|
|
search API
1
|
|
scroll API
1 2 3 |
|
In $resultSet
all the resulting documents are stored. You can get them together with some statistics easily.
1 2 3 4 5 6 |
|
or process aggregation result
1 2 3 4 5 6 7 8 |
|