PHP操作Elasticsearch No.2

本文详细介绍使用PHP操作Elasticsearch的过程,包括建立连接、创建索引、定义映射、插入文档及执行搜索等核心步骤,是理解Elasticsearch与PHP集成的实用指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                               PHP操作Elasticsearch

<?php
require './vendor/autoload.php';    //加载自动加载文件
 
#如果没有设置主机地址默认为127.0.0.1:9200
$client = Elasticsearch\ClientBuilder::create(['127.0.0.1:9200'])->build();
/**
* 1.index 对应关系型数据(以下简称MySQL)里面的数据库
*/
$params = [
    'index' => 'myindex', #index的名字不能是大写和下划线开头
    'body' => [
        'settings' => [
            'number_of_shards' => 2,
            'number_of_replicas' => 0
        ]
    ]
];
$client->indices()->create($params);
/**
 * 2.每个index只允许一个type(对应数据表),type不是单独定义的,而是和字段一起定义(相当于创建表结构).
 */
$params = [
    'index' => 'myindex',
    'type' => 'mytype',
    'body' => [
        'mytype' => [
            '_source' => [
                'enabled' => true
            ],
            'properties' => [
                'id' => [
                    'type' => 'integer'
                ],
                'first_name' => [
                    'type' => 'text',
                ],
                'last_name' => [
                    'type' => 'text',
                ],
                'age' => [
                    'type' => 'integer'
                ]
            ]
        ]
    ]
];
$client->indices()->putMapping($params);

/**
 * 3.往里面插入数据了,概念:这里的数据在ES中叫文档
 */

$params = [
    'index' => 'myindex',
    'type' => 'mytype',
    //'id' => 1, #可以手动指定id,也可以不指定随机生成
    'body' => [
        'first_name' => '张1111',
        'last_name' => '三11111',
        'age' => rand(0,12223)
    ]
];

$client->index($params);



/**
 *4.搜索
 * 
 */
   $query = [
       'query' => [
           'bool' => [
               'must' => [
                   'match' => [
                       'first_name' => '张',
                   ]
               ],
               'filter' => [
                   'range' => [
                       'age' => ['gt' => 76]
                   ]
               ]
           ]

       ]
   ];

$params = [
    'index' => 'myindex',
//  'index' => 'm*', #index 和 type 是可以模糊匹配的,甚至这两个参数都是可选的
    'type' => 'mytype',
    '_source' => ['first_name','age'], // 请求指定的字段
    'body' => array_merge([
        'from' => 0,
        'size' => 5
    ],$query)
];
$data = $client->search($params);
echo "<pre>";
print_r($data);die();
 
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值