Empty Objects

edit

The Elasticsearch API uses empty JSON objects in several locations, and this can cause problems for PHP. Unlike other languages, PHP does not have a "short" notation for empty objects and so many developers are unaware how to specify an empty object.

Consider adding a Highlight to a query:

{
    "query" : {
        "match" : {
            "content" : "quick brown fox"
        }
    },
    "highlight" : {
        "fields" : {
            "content" : {} 
        }
    }
}

This empty JSON object is what causes problems.

The problem is that PHP will automatically convert "content" : {} into "content" : [], which is no longer valid Elasticsearch DSL. We need to tell PHP that the empty object is explicitly an object, not an array. To define this query in PHP, you would do:

$params['body'] = array(
    'query' => array(
        'match' => array(
            'content' => 'quick brown fox'
        )
    ),
    'highlight' => array(
        'fields' => array(
            'content' => new \stdClass() 
        )
    )
);
$results = $client->search($params);

We use the generic PHP stdClass object to represent an empty object. The JSON will now encode correctly.

By using an explicit stdClass object, we can force the json_encode parser to correctly output an empty object, instead of an empty array. Sadly, this verbose solution is the only way to accomplish the goal in PHP…​there is no "short" version of an empty object.