thinkphp6框架怎么使用ElasticSearch
时间: 2024-02-23 17:59:09 浏览: 21
在 ThinkPHP6 中使用 ElasticSearch 需要先安装 ElasticSearch 和 Elasticsearch for PHP,具体安装步骤请参考前面的回答。
安装完成后,我们可以在代码中使用 Elasticsearch for PHP 提供的 API 进行数据的增删改查操作。下面是一个简单的示例:
```php
<?php
namespace app\controller;
use Elasticsearch\ClientBuilder;
use think\facade\Db;
class Index
{
public function search()
{
$client = ClientBuilder::create()->build();
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'title' => 'ElasticSearch'
]
]
]
];
$response = $client->search($params);
return json($response);
}
public function add()
{
$data = Db::table('my_table')->find();
$client = ClientBuilder::create()->build();
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => $data['id'],
'body' => [
'title' => $data['title'],
'content' => $data['content'],
]
];
$response = $client->index($params);
return json($response);
}
public function update()
{
$client = ClientBuilder::create()->build();
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id',
'body' => [
'doc' => [
'title' => 'new title',
]
]
];
$response = $client->update($params);
return json($response);
}
public function delete()
{
$client = ClientBuilder::create()->build();
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id'
];
$response = $client->delete($params);
return json($response);
}
}
```
这里我们定义了四个方法,分别是 `search`、`add`、`update` 和 `delete`。
`search` 方法用于查询数据,我们在查询中使用了 `match` 查询,查询了 `title` 字段中包含 `ElasticSearch` 关键字的文档。
`add` 方法用于添加数据,我们使用了 `index` 方法,将 `my_table` 表中的数据添加到了名为 `my_index`,类型为 `my_type` 的文档中。
`update` 方法用于更新数据,我们使用了 `update` 方法,将 ID 为 `my_id` 的文档中的 `title` 字段更新为了 `new title`。
`delete` 方法用于删除数据,我们使用了 `delete` 方法,删除了 ID 为 `my_id` 的文档。
这只是一个简单的示例,实际使用中需要根据业务需求进行更详细的配置和操作。