Arrays of Objectsedit

Another common pattern in Elasticsearch DSL is an array of objects. For example, consider adding a sort to your query:

{
    "query" : {
        "match" : { "content" : "quick brown fox" }
    },
    "sort" : [  
        {"time" : {"order" : "desc"}},
        {"popularity" : {"order" : "desc"}}
    ]
}

"sort" contains an array of JSON objects

This arrangement is very common, but the construction in PHP can be tricky since it requires nesting arrays. The verbosity of PHP tends to obscure what is actually going on. To construct an array of objects, you actually need an array of arrays:

$params['body'] = array(
    'query' => array(
        'match' => array(
            'content' => 'quick brown fox'
        )
    ),
    'sort' => array(    
        array('time' => array('order' => 'desc')),  
        array('popularity' => array('order' => 'desc')) 
    )
);
$results = $client->search($params);

This array encodes the "sort" : [] array

This array encodes the {"time" : {"order" : "desc"}} object

This array encodes the {"popularity" : {"order" : "desc"}} object

If you are on PHP 5.4+, I would strongly encourage you to use the short array syntax. It makes these nested arrays much simpler to read:

$params['body'] = [
    'query' => [
        'match' => [
            'content' => 'quick brown fox'
        ]
    ],
    'sort' => [
        ['time' => ['order' => 'desc']],
        ['popularity' => ['order' => 'desc']]
    ]
];
$results = $client->search($params);