REST API endpoint for elasticpress autosuggest

After some inspecting the WP_REST_Request, it turned out, that the get_body() method was the one I’m looking for. Anyhow, this is what I ended up with:

add_action( 'rest_api_init', function() {
    register_rest_route( 'ep', '/as/', [
        'methods' => \WP_REST_Server::CREATABLE,
        'callback' => 'ep_autosuggest',
    ] );
} );
function ep_autosuggest( WP_REST_Request $data ) {
    // Elasticsearch PHP Client
    $client = ClientBuilder::create()->build();
    $params = [
        'index' => 'ep-test',
        'type' => 'post',
        'body' => $data->get_body()
    ];
    $response = $client->search( $params );
    return $response;
}

For anyone interested, I made a plugin out of it:

https://github.com/grossherr/elasticpress-autosuggest-endpoint

Leave a Comment