php-client
connecting-连接
创建文档
要索引文档,我们需要指定三个信息:索引、id和文档主体。这是通过构造键:值对的关联数组来实现的。请求体本身是一个关联数组,其中的key:value对与文档中的数据相对应。
$params = [ 'index' => 'my_index', 'id' => 'my_id', 'body' => ['testField' => 'abc'] ]; $response = $client->index($params); print_r($response->asArray());
您得到的响应表明文档是在您指定的索引中创建的。可以使用asArray()函数将响应呈现为关联数组。数组响应包含Elasticsearch返回的JSON的解码版本:
Array ( [_index] => my_index [_type] => _doc [_id] => my_id [_version] => 1 [created] => 1 )
设置body为json字符串
如果你愿意,你可以将‘ body ’参数指定为JSON字符串。这对测试很有用(例如。从在线代码示例中复制粘贴)或者如果你已经有一些JSON文档要存储在Elasticsearch中。
例如,前面的索引示例可以重写如下:
$params = [ 'index' => 'my_index', 'id' => 'my_id', 'body' => '{"testField" : "abc"}' ]; $response = $client->index($params); print_r($response->asArray());
Array ( [_index] => my_index [_id] => my_id3 [_version] => 1 [result] => created [_shards] => Array ( [total] => 2 [successful] => 1 [failed] => 0 ) [_seq_no] => 5 [_primary_term] => 1 )
created表示新增文档,把testField的值改成abc4,再执行一次
$params = [ 'index' => 'my_index', 'id' => 'my_id', 'body' => '{"testField" : "abc4"}' ]; $response = $client->index($params); print_r($response->asArray());
Array ( [_index] => my_index [_id] => my_id3 [_version] => 2 [result] => updated [_shards] => Array ( [total] => 2 [successful] => 1 [failed] => 0 ) [_seq_no] => 6 [_primary_term] => 1 )
updated表示新增文档
获取文档
让我们得到刚刚索引的文档。这将返回文档:
$params = [ 'index' => 'my_index', 'id' => 'my_id' ]; $response = $client->get($params); print_r($response->asArray());
响应包含诸如索引、版本等元数据以及_source字段,该字段是您发送给Elasticsearch的原始文档。
Array ( [_index] => my_index [_type] => _doc [_id] => my_id [_version] => 1 [found] => 1 [_source] => Array ( [testField] => abc ) )