PHP 中运用 elasticsearch
PHP扩展安装
1. 环境要求:PHP_VERSION >= 5.3.9,composer工具
2. 在E盘新建文件夹命名为elastic,,拷贝composer.phar到
E:/elastic目录下面
3. 打开命令行窗口,进入E:/elastic
4. 在命令行运行:
php composer.phar require elasticsearch/elasticsearch
5. 此时E:/elastic目录下会出现一个vendor目录,安装成功
6. 使用方法:
require 'vendor/autoload.php';
$client = new Elasticsearch\Client();
创建索引
- include('./vendor/autoload.php');
- $elastic = new Elasticsearch\Client();
- $index[‘index’] = ‘log’; //索引名称
- $index[‘type’] = ‘ems_run_log’; //类型名称
- $data[‘body’][‘settings’][‘number_of_shards’] = 5; //主分片数量
- $data[‘body’][‘settings’][‘number_of_replicas’] = 0; //从分片数量
- $elastic->indices()->create($index);
插入索引数据
- include('./vendor/autoload.php');
- $elastic = new Elasticsearch\Client();
- $index[‘index’] = ‘log’; //索引名称
- $index[‘type’] = ‘ems_run_log’; //类型名称
- $index[‘id’] = 1 //不指定id,系统会自动生成唯一id
- $index[‘body’] = array(
- ‘mac’ => 'fcd5d900beca',
- ‘customer_id’ => 3,
- ‘product_id’ => 5,
- ‘version’ => 2
- );
- $elastic->index($index);
查询
- include('./vendor/autoload.php');
- $elastic = new Elasticsearch\Client();
- $index[‘index’] = ‘log’; //索引名称
- $index[‘type’] = ‘ems_run_log’; //类型名称
- $index[‘body’][‘query’][‘bool’][‘must’] = array(
- array(‘match’ => array(‘mac’ => ‘fcd5d900beca’)),
- array(‘match’ => array(‘product_id’ => 20))
- );
- $index[‘size’] = 10;
- $index[‘from’] = 200;
- $elastic->search($index);
- 相当于sql语句:
- select*from ems_run_log where mac=‘fcd5d900beca’
- and product_id = 20 limit 200,10;
删除文档
- <pre name="code" class="php">include('./vendor/autoload.php');
- $elastic = new Elasticsearch\Client();
- $index['index'] = 'test'; //索引名称
- $index['type'] = 'ems_test'; //类型名称
- $index['id'] = 2;
- $elastic->delete($index);
IT成长中的那些事儿
分类:
Elasticsearch
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App