安装 elasticsearch/elasticsearch

// 下载 elasticsearch
composer require elasticsearch/elasticsearch
// 下载 elasticsearch 指定版本
composer require elasticsearch/elasticsearch 8.18.0

没有 composer 查看下面文章 安装

Composer 文章

连接 ES

// 引入文件
use Elastic\Elasticsearch\ClientBuilder;

	private $hosts = ['https://127.0.0.1:9200'];

	private $client;

	public function __construct()
	{
        $this->client = ClientBuilder::create()
                        ->setHosts($this->hosts)
                        ->setBasicAuthentication('用户(默认:elastic)','密码')
                        ->setCABundle(__DIR__ . '/elasticsearch/http_ca.crt')
                        ->build();
	}

http_ca.crt 文件 在 elasticsearch 安装包 \config\certs 下面

获取信息

$this->client->info();

创建索引

$params = [
     // 索引名称
     'index' => 'index_name',
     'body' => [
         'settings' => [
             //分片数量:一个索引库将拆分成多片分别存储不同的结点,默认5个
             'number_of_shards' => 5,
             //为每个分片分配的副本数,replica shard是primary shard的副本,负责容错,以及承担读请求负载,如果服务器只有一台,只能设置为0,不然会报错创建超时failed to process cluster event (create-index [test], cause [api]) within 30s
             'number_of_replicas' => 0,
             // 刷新周期
             'refresh_interval' => '10s',
             // 返回最大数 默认 10000
             'max_result_window' => 10000,
         ],

         //创建文档映射,就是文档存储在ES中的数据结构
         'mappings' => [
             'properties' => [
                 'id' => [
                     'type' => 'keyword',
                     'index' => 'true',
                 ],
                 'title' => [
                     //数据类型为text,支持分词;类型为keyword,不支持分词,只能精确索引;8.x以上版本不再支持string等类型
                     'type' => 'text',
                     //字段可以被索引,也就是能用来当做查询条件来查询,只能填写true和false
                     'index' => 'true',
                     //索引分词器,用于字符串类型,这里使用中文分词器ik,用默认分词器可以省略
                     'analyzer' => 'ik_max_word',
                     //搜索分词器,用于搜索关键词的分词器
                     'search_analyzer' => 'ik_max_word'
                 ],
                 'describe' => [
                     'type' => 'keyword',
                     'index' => 'false',
                 ],
                 'content' => [
                     'type' => 'text',
                     'index' => 'true',
                     'analyzer' => 'ik_max_word',
                     'search_analyzer' => 'ik_max_word'
                 ],
                 'more' => [
                      'type' => 'object',
                 ],
                 //创建时间
                 'create_time' => [
                     'type' => 'date',
                     'index' => 'false',
                     'format' => 'yyyy-MM-dd HH:mm:ss',
                 ],
             ]
         ]
     ]
 ];
 
// 创建索引
$this->client->indices()->create($params);

追加新的索引

$params = [
   // 索引名称
    'index' => 'index_name',
    'body' => [
        'properties' => [
        		// new_index -- 索引名称
            'new_index' => [
                'type' => 'keyword',
                'index' => 'false',
            ]
        ]
    ]
];

// 追加新的索引
$this->client->indices()->putMapping($params);

删除索引

$params = [
   // 索引名称
    'index' => 'index_name',
];

// 删除索引
$this->client->indices()->delete($params);

删除搜索信息

$params = [
    'index' => 'index_name',
    'body' => [
        'query' => [
            'bool' => [
                'filter' => [
                    'match_phrase' => [
                        'title' => '北京'
                    ],
								'range' => [
									'create_time' => [
								    'gte' => '2025-06-01',
								    'lte' => '2025-07-01',
									]
								],
								'range' => [
									'id' => [
										//删除id > 4的文档记录
										'gt' => 4
									]
								]
                ]
            ]

        ]
    ]
];

// 删除搜索信息
$this->client->deleteByQuery($params);

删除后内存 和 空间 不立即释放 执行下面 进行手动释放
方式 POST
https://127.0.0.1:9200/index_name/_forcemerge?max_num_segments=1

获取映射

$params = [
   // 索引名称
    'index' => 'index_name',
];

// 获取映射
$this->client->indices()->getMapping($params);

保存单条文档数据

$params = [
    'index' => 'index_name', // 索引名称
    'id' => 1,
    'body' => [
        'id' => 1,       
        'title' => '这是一个标题',
        'describe' => '这是一段描述',
        'content' => '<h4>这是一个内容的标题</h4><p>这是内容</p>',
        'more' => [['name'=>'附件.xlsx','url'=>'http://127.0.0.1/uploads/2047f629-bfa6-4d27-a15c-48083e036d01/附件.xlsx'],['name'=>'附件_20.xlsx','url'=>'http://127.0.0.1/uploads/2047f629-bfa6-4d27-a15c-48083e036d01/附件_20.xlsx']],
        'create_time' => '2025-06-23 10:06:12',
    ]
];

// 保存单条文档数据
$this->client->index($params);

保存多条文档数据

$arr = [
    [
        'id' => 2,       
        'title' => '这是一个标题2',
        'describe' => '这是一段描述2',
        'content' => '<h4>这是一个内容的标题</h4><p>这是内容</p>',
        'more' => [['name'=>'附件.xlsx','url'=>'http://127.0.0.1/uploads/2047f629-bfa6-4d27-a15c-48083e036d01/附件.xlsx'],['name'=>'附件_20.xlsx','url'=>'http://127.0.0.1/uploads/2047f629-bfa6-4d27-a15c-48083e036d01/附件_20.xlsx']],
        'create_time' => '2025-06-23 10:06:12',
    ],
    [
        'id' => 3,       
        'title' => '这是一个标题3',
        'describe' => '这是一段描述3',
        'content' => '<h4>这是一个内容的标题</h4><p>这是内容</p>',
        'more' => [['name'=>'附件.xlsx','url'=>'http://127.0.0.1/uploads/2047f629-bfa6-4d27-a15c-48083e036d01/附件.xlsx'],['name'=>'附件_20.xlsx','url'=>'http://127.0.0.1/uploads/2047f629-bfa6-4d27-a15c-48083e036d01/附件_20.xlsx']],
        'create_time' => '2025-06-23 10:06:12',
    ],
    [
        'id' => 4,       
        'title' => '这是一个标题4',
        'describe' => '这是一段描述4',
        'content' => '<h4>这是一个内容的标题</h4><p>这是内容</p>',
        'more' => [['name'=>'附件.xlsx','url'=>'http://127.0.0.1/uploads/2047f629-bfa6-4d27-a15c-48083e036d01/附件.xlsx'],['name'=>'附件_20.xlsx','url'=>'http://127.0.0.1/uploads/2047f629-bfa6-4d27-a15c-48083e036d01/附件_20.xlsx']],
        'create_time' => '2025-06-23 10:06:12',
    ],
];

$params = [];
foreach ($arr as $val) {
    $params['body'][] = [
        'index' => [
            '_index' => 'index_name',
            '_id' => $val['id']
        ]
    ];
    $params['body'][] = $val;
}

// 保存多条文档数据
$this->client->bulk($params);

获取文档信息

$params = [
   // 索引名称
    'index' => 'index_name',
    'id' => 1,
];

// 获取文档信息
$this->client->get($params);

获取搜索信息

$arr['index'] = 'index_name';
// 排序
$arr['body']['sort'] = ['create_time' => ['order' => 'desc'],'id'=>['order' => 'desc']];
// 分页起始位置
$page = $params['page'] ?? 0;
$size = 20;
// 页码
$arr['body']['from'] = $page > 1 ? ($page - 1) * $size : 0;
// 分页记录数量
$arr['body']['size'] = $size;
// 返回最大数
$arr['body']['track_total_hits'] = 5000;
// 显示字段
$arr['body']['_source'] = ['id','title','create_time'];
// 对结果进行高亮显示
$arr['body']['highlight']['fields']['title']= ['pre_tags' => '<font color="red">','post_tags' => '</font>',];
$arr['body']['highlight']['fields']['content']= ['pre_tags' => '<font color="red">','post_tags' => '</font>',];
// 筛选条件
// match 会对查询的关键词进行分词,
//term不会。例如查询华为手机,match会查询title中包含华为或者手机或者华为手机的,term不会对查询的关键词做拆分,
//range:范围查询
if (!empty($params['keyword_content'])) {
	$where['must']['simple_query_string']['query'] = $params['keyword_content'];
	$where['must']['simple_query_string']['fields'] = ["title", "content"];
	$where['must']['simple_query_string']['default_operator'] = "or";
}
// bool查询,多个条件共同成立,有四种选择,
// must(计算得分,性能较低 相当于 and)
// filter(过滤条件,不计算得分,性能高 相当于 and),
// must_not(条件必须不成立 相当于 and),
// should(条件可以成立 相当于 or)
if (!empty($where)) {
   $arr['body']['query'] = ['bool' => $where];
}

// 获取搜索信息
$this->client->search($arr)->asArray();
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐