一架梯子,一头程序猿,仰望星空!

php elasticsearch 索引管理


php elasticsearch 索引管理常用操作主要包括:创建索引、删除索引、查询索引结构,修改索引设置。

创建索引

虽然,ES可以自动创建索引,不过实际项目中,通常需要预先创建索引结构,明确指定数据类型,避免出现ES自动创建的字段类型不是你想要的类型。

$client = ClientBuilder::create()->build();
$params = [
    'index' => 'my_index', // 索引名
    'body' => [ // es 索引结构定义
        'settings' => [ // 索引配置
            'number_of_shards' => 3, // 分片数量
            'number_of_replicas' => 2 // 副本数量
        ],
        'mappings' => [ // mapping定义,即索引结构定义
            '_source' => [
                'enabled' => true
            ],
            'properties' => [
                'first_name' => [
                    'type' => 'keyword'
                ],
                'age' => [
                    'type' => 'integer'
                ]
            ]
        ]
    ]
];


// 创建索引
$response = $client->indices()->create($params);

ES中mappings负责索引字段和数据类型,具体的ES mapping语法,请参考:Elasticsearch mapping,将ES的mapings定义的json结构转成php数组即可,

删除索引

$params = [
   'index' => 'my_index' // 索引名
]; 
$response = $client->indices()->delete($params);

查询索引结构

查询首页的mapping定义

// 查询所有的mapping定义
$response = $client->indices()->getMapping();

// 查询指定索引的Mapping定义
$params = [
    'index' => 'my_index' // 索引名
];
$response = $client->indices()->getMapping($params);

// 查询my_index和my_index2两个索引的mapping定义
$params = [
    'index' => [ 'my_index', 'my_index2' ]
];
$response = $client->indices()->getMapping($params);

修改索引设置

$params = [
    'index' => 'my_index', // 索引名
    'body' => [
        'settings' => [ // 修改设置
            'number_of_replicas' => 5, // 副本数
        ]
    ]
];

$response = $client->indices()->putSettings($params);