通过其他客户端访问Elasticsearch
更新时间:2020-08-18
本文介绍使用PHP、Python和Go客户端访问Baidu Elasticsearch的方法,并提供了示例代码和注意事项供您参考。
PHP语言
警告
Elasticsearch的PHP客户端提供的默认连接池并不适合云上环境,可能在长连接断开时出现连接异常的问题。推荐PHP客户端访问程序使用SimpleConnectionPool作为连接池,并做好失败重连的机制。
通过PHP客户端访问Elasticsearch进行测试,示例代码如下,详情请参见elasticsearch-php。
Plain Text
1<?php
2require 'vendor/autoload.php';
3use Elasticsearch\ClientBuilder;
4
5$client = ClientBuilder::create()->setHosts([
6 [
7 'host' => '<HOST>',
8 'port' => '8200',
9 'scheme' => 'http',
10 'user' => '<USER_NAME>',
11 'pass' => '<PASSWORD>'
12 ]
13])->setConnectionPool('\Elasticsearch\ConnectionPool\SimpleConnectionPool', [])
14 ->setRetries(10)->build();
15
16$indexParams = [
17 'index' => 'my_index',
18 'type' => 'my_type',
19 'id' => '1',
20 'body' => ['testField' => 'abc'],
21 'client' => [
22 'timeout' => 10,
23 'connect_timeout' => 10
24 ]
25];
26$indexResponse = $client->index($indexParams);
27print_r($indexResponse);
28
29$searchParams = [
30 'index' => 'my_index',
31 'type' => 'my_type',
32 'body' => [
33 'query' => [
34 'match' => [
35 'testField' => 'abc'
36 ]
37 ]
38 ],
39 'client' => [
40 'timeout' => 10,
41 'connect_timeout' => 10
42 ]
43];
44$searchResponse = $client->search($searchParams);
45print_r($searchResponse);
46?>
参数 | 说明 |
---|---|
HOST |
ES HTTP URL,在Baidu Elasticsearch界面中可以查询 |
USER_NAME |
用户名。 |
PASSWORD |
密码。 |
Python语言
通过Python客户端访问Elasticsearch进行测试,示例代码如下,详情请参见elasticsearch-py。
Plain Text
1from elasticsearch import Elasticsearch, RequestsHttpConnection
2import certifi
3es = Elasticsearch(
4 ['<HOST>'],
5 http_auth=('<USER_NAME>', '<PASSWORD>'),
6 port=8200,
7 use_ssl=False
8)
9res = es.index(index="my_index", doc_type="my_type", id=1, body={"title": "One", "tags": ["ruby"]})
10print(res['created'])
11res = es.get(index="my_index", doc_type="my_type", id=1)
12print(res['_source'])
Go语言
通过Go语言访问Elasticsearch进行测试,示例代码如下:
- 安装Go编译环境,详情请参见官方文档。以下示例代码使用Go1.13.4版本。
- 创建Baidu Elasticsearch实例。
Plain Text
1package main
2
3import (
4 "context"
5 "gopkg.in/olivere/elastic.v5"
6 "gopkg.in/olivere/elastic.v5/config"
7 "log"
8)
9
10const (
11 url = "http://<HOST>:8200" //<1>
12 username = "<USER_NAME>" //<2>
13 password = "<PASSWORD>" //<3>
14)
15
16func main() {
17 var sniff = false //<4>
18 cfg := &config.Config{
19 URL: url,
20 Username: username,
21 Password: password,
22 }
23
24 cfg.Sniff = &sniff
25 var client, err = elastic.NewClientFromConfig(cfg)
26 if err != nil {
27 log.Println(err)
28 return
29 }
30
31 exists, err := client.IndexExists("index_test").Do(context.Background()) //<5>
32 if err != nil {
33 log.Println(err)
34 }
35 log.Println(exists)
36}
参数 | 说明 |
---|---|
HOST |
ES HTTP URL,在Baidu Elasticsearch界面中可以查询 |
USER_NAME |
用户名。 |
PASSWORD |
密码。 |
连接成功后,返回如下结果。
Plain Text
12019/11/29 10:07:37 true
更多语言
更多语言示例请参见HTTP/REST Clients and Security。