Skip to content
mayorandrew edited this page Feb 7, 2015 · 6 revisions

Basic search

Call the search function on the model and grab the results:

$results = Husband::search('query_string')->getResults();

This will search through all available fields. The results variable is a rich wrapper around the hits that Elasticsearch returned. It extends from the Laravel Collection class and thus supports all the collection methods.

foreach($results as $result)
{
    // Convenience functions
    $result->getId();
    $result->getType();
    $result->getIndex();
    $result->getScore();
    $result->getSource();
    $result->getHit();

    // Get results directly from the hit
    // Object notation
    $result->wife

    // Array notation
    $result['_source.wife.name']
}

Custom search

You can always pass a query array or JSON structure to the Elasticsearch client. This way you have total freedom over how to construct the query.

$query['query']['match']['name'] = 'Raymundo';
$husband = Husband::search(null, ['query' => $query])->getResults();

$wife = Wife::search(null, ['json' => ['query' => ['match' => ['name' => 'Lisa']]]])->getResults();

There is also a convenience function to use an Elasticsearch query directly:

$query['query']['match']['name'] = 'Raymundo';

$husband = Husband::searchByQuery($query)->getResults();

Single document search

You can use the following function if you just want to retrieve a document based on the Elasticsearch identifier:

Husband::searchById('1234')->getSource();

Scoping

It is possible to specify which fields to search on:

$results = Husband::search('query_string', ['fields' => ['wife.name']])->getResults();

And also which fields to return in the response:

$results = Husband::search('query_string', [
        'fields' => ['wife.name'],
        'select' => ['name']
    ])->getResults();

$name = $results->first()->getFields(['name']);

Highlighting

$results = Husband::search('query_string', ['fields' => ['name'], 'highlight' => true])->getResults();

$highlights = $results->first()->getHighlights(['name']);

Suggestions

$results = Husband::search('query_string', ['fields' => ['name'], 'suggest' => true])->getResults();

$suggestios = $results->first()->getSuggestions(['name']);

Aggregations

$response = Husband::search('query_string',
        'aggs' => [
            'agg_name' => [
                'type' => 'terms',
                'field' => 'name'
            ]
        ]
    );

$results = $response->getResults();
$aggregations = $response->getAggregations('agg_name');

Autocomplete

// Autocomplete on all fields
$results = Husband::search('query_string', ['autocomplete' => true])->getResults();

// Autocomplete on specific fields
// IMPORTANT: you need to index the model with the 'word_start' analyzer on the correct field, otherwise // you won't get any results
$results = Husband::search('query_string', ['fields' => ['wife.name' => 'word_start']])->getResults();