How to connect PHP to the Elasticsearch database requires specific code examples
1. Background introduction
Elasticsearch is an open source search engine based on Lucene, which provides a A distributed, multi-tenant full-text search engine that can implement functions such as real-time data analysis, data search, and data storage. When building web applications, connecting to Elasticsearch provides efficient data query and retrieval capabilities. This article explains how to connect to an Elasticsearch database in PHP and provides specific code examples.
2. Installation and Settings
"require": { "elasticsearch/elasticsearch": "~7.0" }
3. Connect to Elasticsearch
To connect to the Elasticsearch database in PHP, you need to use the classes and methods provided by the Elasticsearch PHP client library. The following is a simple example:
require 'vendor/autoload.php'; use ElasticsearchClientBuilder; $client = ClientBuilder::create()->setHosts(['localhost:9200'])->build(); $params = [ 'index' => 'my_index', // 索引名称 'id' => '1', // 文档 ID ]; $response = $client->get($params); print_r($response);
In the above code example, we first introduced the Elasticsearch PHP client library and created an Elasticsearch client (client). When creating the client, we need to specify the host and port number of Elasticsearch (the default "localhost:9200" is used in this example).
4. Specific operations
$params = [ 'index' => 'my_index', // 索引名称 'id' => 1, // 文档 ID 'body' => [ 'title' => "PHP Elasticsearch", 'content' => "Elasticsearch 是一个强大的搜索引擎。", 'tags' => ['php', 'elasticsearch'] ] ]; $response = $client->index($params);
$params = [ 'index' => 'my_index', // 索引名称 'id' => 1 // 文档 ID ]; $response = $client->get($params); print_r($response);
$params = [ 'index' => 'my_index', // 索引名称 'id' => 1, // 文档 ID 'body' => [ 'doc' => [ 'title' => "Updated Title" ] ] ]; $response = $client->update($params);
$params = [ 'index' => 'my_index', // 索引名称 'id' => 1 // 文档 ID ]; $response = $client->delete($params);
5. Summary
This article introduces how to connect to the Elasticsearch database in PHP and provides specific code example. By using the Elasticsearch PHP client library, we can easily perform data addition, deletion, modification and query operations. I hope this article has provided some help for everyone using Elasticsearch in PHP. If you have any questions or concerns, please leave a message to discuss.
The above is the detailed content of How to connect PHP to Elasticsearch database. For more information, please follow other related articles on the PHP Chinese website!