Skip to content

Retrieving Data ​

After creating a bridge and its associated search index, you are ready to start retrieving data. You can think of each bridge as a powerful query builder allowing you to fluently query the index associated with the bridge.

The all Method ​

The all method retrieves the first page of documents from the bridge's index using a match_all query and cursor pagination.

Bounded, not "everything"

all() returns a single bounded page (default 15 records) — it does not load the entire index into memory. This prevents accidentally exceeding Elasticsearch's max_result_window. To walk the whole dataset, use the returned collection's links() cursors or see Pagination.

Signature ​

php
public static function all(int $perPage = 15)

Parameters ​

  • $perPage (int, optional): The number of records to retrieve per page. Default is 15.

Usage Examples ​

Basic Usage:

php
use App\Bridges\HotelRoom;

// Retrieve the first page of hotel rooms (15 per page)
foreach (HotelRoom::all() as $hotelRoom) {
    echo $hotelRoom->price;
}

Custom Page Size:

php
// Retrieve the first page with 50 records
foreach (HotelRoom::all(50) as $hotelRoom) {
    echo $hotelRoom->name . ': $' . $hotelRoom->price;
}

Working with the Collection:

php
$rooms = HotelRoom::all(25);

// Total number of matching documents
echo 'Total: ' . $rooms->total();

// Cursor links for the next/previous page (see Pagination)
// ['previous' => [...], 'next' => [...], 'total' => 123]
$links = $rooms->links();

// Iterate through the results
$rooms->each(function ($room) {
    echo $room->name;
});

When to Use ​

Use the all method when you want a quick first page of documents without additional constraints. For filtered queries, use the query builder:

php
$filteredRooms = HotelRoom::asBoolean()
    ->mustMatch('advertiser', 'booking.com')
    ->filterByRange('price', 100, 'gt')
    ->get();

Building Queries ​

Each bridge serves as a query builder that allows you to add additional constraints to queries and then invoke the get method to retrieve the results.

php
use App\Bridges\HotelRoom;

$rooms = HotelRoom::asBoolean()
    ->mustMatch('advertiser', 'booking.com')
    ->orderBy('price', 'ASC')
    ->take(10)
    ->get(['price', 'advertiser']); // select fields

// Inspect the generated body (array or JSON)
$asArray = HotelRoom::asRaw()->matchAll()->toQuery();
$asJson = HotelRoom::asRaw()->matchAll()->toQuery(asJson: true);

Retrieving Single Bridges ​

The find Method ​

The find method allows you to retrieve one or more documents by their _id values.

How It Works ​

  1. Uses the ids query type
  2. Returns a single bridge instance if you pass a single ID
  3. Returns a collection of bridge instances if you pass an array of IDs
  4. Returns null (or an empty collection) if no matching documents are found

Usage Examples ​

Retrieving a Single Document:

php
use App\Bridges\HotelRoom;

$room = HotelRoom::find(1);

if ($room) {
    echo $room->name;
    echo $room->price;
}

Retrieving Multiple Documents:

php
use App\Bridges\HotelRoom;

$rooms = HotelRoom::find([1, 2, 3, 42]);

foreach ($rooms as $room) {
    echo $room->name . ': $' . $room->price . PHP_EOL;
}

echo 'Found ' . $rooms->count() . ' rooms';

Working with String IDs:

php
use App\Bridges\Log;

// Search engines often use UUID or hash-based IDs
$log = Log::find('9cac02e7-d063-456f-90ad-0b145bb04fde');

Chaining with Collection Methods:

php
$expensiveRooms = HotelRoom::find([1, 2, 3, 4, 5])
    ->filter(fn ($room) => $room->price > 200)
    ->sortBy('price')
    ->values();

Performance Considerations ​

Retrieving documents by ID is one of the fastest operations available. When finding multiple IDs, all documents are retrieved in a single request. Select only the fields you need for a lighter response:

php
$rooms = HotelRoom::asIds()
    ->withValues([1, 2, 3])
    ->get(['name', 'price']);

Retrieving Aggregates ​

When interacting with bridges you may use count, sum, max, min, avg aggregate methods. These return scalar values. stats returns a Stats object and histogram returns a collection of Bucket objects.

php
use App\Bridges\HotelRoom;

echo HotelRoom::count();      // total documents in the index
echo HotelRoom::min('price');
echo HotelRoom::max('price');
echo HotelRoom::avg('price');
echo HotelRoom::sum('price');

// aggregate scoped to a query
echo HotelRoom::asBoolean()
    ->mustMatch('advertiser', 'booking.com')
    ->sum('price');

IMPORTANT

Aggregates can also be attached to a query using withAggregate, letting you retrieve both documents and aggregate results. Access the aggregate via a camel-cased method on the returned collection: <field><Aggregate> e.g. priceAvg().


Changed in v2

Aggregation results are now stored on the returned collection instance instead of a global Collection macro. The call syntax is unchanged ($rooms->priceAvg()), but multiple aggregations on one response now coexist, and results no longer leak across requests in long-lived workers (Octane, queues).

php
use App\Bridges\HotelRoom;

$rooms = HotelRoom::asBoolean()
     ->mustMatch('advertiser', 'booking.com')
     ->withAggregate('avg', 'price')
     ->get();

foreach ($rooms as $room) {
    echo $room->price;
}

// access the aggregate value
echo $rooms->priceAvg();

Stats ​

Call stats to return the stats aggregate as a Lacasera\ElasticBridge\DTO\Stats instance:

php
$stats = HotelRoom::asBoolean()
     ->mustMatch('advertiser', 'booking.com')
     ->stats('price');

echo $stats->count();
echo $stats->avg();
echo $stats->max();
echo $stats->min();
echo $stats->sum();

$stats->toArray();
$stats->toCollection();

Histogram and Ranges ​

php
// ranges aggregate query
$rooms = HotelRoom::asBoolean()
    ->shouldMatch('advertiser', 'booking.com')
    ->withAggregate('range', 'price', [
        'ranges' => [
            ['from' => 50, 'to' => 500],
        ],
    ])
    ->get();

dump($rooms->priceRange());

// histogram aggregate query
$rooms = HotelRoom::asBoolean()
    ->shouldMatch('advertiser', 'booking.com')
    ->withAggregate('histogram', 'price', [
        'interval' => 300,
    ])
    ->get();

dump($rooms->priceHistogram());

Ordering, Limit and Offset ​

Ordering ​

The orderBy method sorts the results by a given field. The second argument is the direction, either asc or desc:

php
$rooms = HotelRoom::asBoolean()
    ->mustMatch('advertiser', 'booking.com')
    ->orderBy('price', 'desc')
    ->get();

Changed in v2

An invalid sort direction now throws Lacasera\ElasticBridge\Exceptions\InvalidQuery (only asc / desc are accepted, case-insensitively).

Sort by multiple fields by invoking orderBy repeatedly:

php
$rooms = HotelRoom::asBoolean()
    ->mustMatch('advertiser', 'booking.com')
    ->orderBy('price', 'desc')
    ->orderBy('created', 'asc')
    ->get();

The skip and take Methods ​

Use skip and take to limit or skip results:

php
$rooms = HotelRoom::asBoolean()
    ->mustMatch('advertiser', 'booking.com')
    ->skip(10)
    ->take(5)
    ->get();

limit and offset are functionally equivalent to take and skip:

php
$rooms = HotelRoom::asBoolean()
    ->mustMatch('advertiser', 'booking.com')
    ->offset(5)
    ->limit(10)
    ->get();

Released under the MIT License.