PHP使用ES4更新文档

<?php

include "vendor/autoload.php";

use Elastic\Elasticsearch\ClientBuilder;

$esUrl = 'http://127.0.0.1:9200';

// 创建客户端
$client = ClientBuilder::create()
                       ->setHosts([$esUrl])
    // 无认证和SSL
    // ->setBasicAuthentication('elastic', 'password copied during Elasticsearch start')
    // ->setCABundle('path/to/http_ca.crt')
                       ->build();

echo '<pre>';

// 操作文档地址:https://www.elastic.co/guide/en/elasticsearch/client/php-api/8.19/index_management.html

$client = ClientBuilder::create()->build();

//更新文档
$index = 'article';

// 新增和更新 建议用添加数据,不建议用更新
// 部分更新(仅修改指定字段) $client->update():
//update() 方法的核心是 “仅更新文档的部分字段”,不会影响未指定的字段:
//若文档存在:仅更新 body.doc 中指定的字段,其他字段保持不变。
//若文档不存在:抛出 404 异常(文档不存在)。

// 单个更新
$params = [
    'index' => $index,
    'id'    => '2',
    'body'  => [
        'doc' => [
            'title' => '批量索引分批处理内容2更新后了',
        ],
    ],
];

// Update doc at /my_index/_doc/my_id
//$response = $client->update($params);

//脚本更新
$params = [
    'index' => $index,
    'id'    => '2',
    'body'  => [
        'script' => 'ctx._source.title = ctx._source.title + "aaa"',

    ],
];
//$response = $client->update($params);

//Upserts是“更新或插入”操作。这意味着一个upsert尝试运行你的更新脚本,但如果文档不存在(或你试图更新的字段不存在),则插入默认值。
$params = [
    'index' => $index,
    'id'    => '2',
    'body'  => [
        'script' => [
            'source' => 'ctx._source.counter += params.count',
            'params' => [
                'count' => 4,
            ],
        ],
        'upsert' => [
            'counter' => 1,
        ],
    ],
];
//$response = $client->update($params);

//print_r($response->asArray());



©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容