Elasticsearch PHP构造函数传参错误求助:数组替代Transport实例
Hey there, I get it—diving into a new tech stack (Elasticsearch + PHP) and hitting errors right off the bat can be frustrating. Let's sort out this TypeError you're seeing.
What's Going Wrong?
The error is telling you that the Elasticsearch\Client constructor expects a Transport object, but you're passing an array instead. This is because starting with Elasticsearch PHP client version 6.x, they changed how you initialize the client—you can't just pass a config array directly to the constructor anymore.
Your Current (Problematic) Code
I bet your init.php line 5 looks something like this:
$client = new Elasticsearch\Client(['hosts' => ['localhost:9200']]);
This was the way to do it in older client versions (like 5.x), but it's not compatible with 6.x.
The Fix: Use ClientBuilder
Instead, you need to use the ClientBuilder class to create your client instance. This takes care of setting up the required Transport object for you. Here's the corrected code:
// First, make sure you're importing the ClientBuilder class use Elasticsearch\ClientBuilder; // Now build the client properly $client = ClientBuilder::create() ->setHosts(['localhost:9200']) // Add your Elasticsearch host(s) here ->build();
Quick Checks to Ensure Everything Works
- Verify Client Version: Make sure your PHP client matches your Elasticsearch server version (6.2). Check your
composer.json—it should have"elasticsearch/elasticsearch": "^6.2"listed. - Elasticsearch is Running: Confirm Elasticsearch is up and accessible at
localhost:9200(visit that URL in your browser; you should see a JSON response with cluster details).
That should fix the TypeError and get your client up and running. Let me know if you hit any other snags!
内容的提问来源于stack exchange,提问作者Ole

