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();