访问Elasticsearch服务
更新时间:2020-12-30
Elasticsearch集群搭建好之后,用户可以通过任意HTTP客户端连接集群,进行数据的导入或查询。在使用Elasticsearch服务前,用户需要注意以下几点:
- 由于Elasticsearch集群创建的时候在用户定义的VPC内,所以只有属于同一个VPC内的bcc才能直接访问Elasticsearch服务,而不同VPC内的节点则需要通过对等连接等方式进行访问。
- Elasticsearch集群默认只有一个superuser用户,superuser用户的密码就是用户创建集群时指定的管理员密码。您也可以创建新的Elasticsearch用户,创建方法参见权限管理。
- 连接Elasticsearch服务的方式可参见Elasticsearch Restful API。
通过curl命令访问
下面以Linux下的curl命令为例来介绍如何访问Elasticsearch服务。
认证方式
例如使用 Http Basic认证方式访问集群:
curl -u {username}:{password} --header 'Content-Type: application/json' -XGET '{host}:{port}/'
使用URL参数认证:
curl -XGET '{host}:{port}/?username={username}&password={password}'
创建 index
通过Elasticsearch的创建 index API 带上用户名和密码来创建新的 index:
curl -u {username}:{password} --header 'Content-Type: application/json' -XPUT '{host}:{port}/index_name' -d'
{
"settings": {
"index": {
"number_of_shards": 1,
"number_of_replicas": 9
}
}
}'
导入数据
实时导入:
指定id:
curl -u {username}:{password} --header 'Content-Type: application/json' -XPOST '{host}:{port}/index_name/_doc/id' -d '
{
"field": "value"
}'
不指定id:
curl -u {username}:{password} --header 'Content-Type: application/json' -XPOST '{host}:{port}/index_name/_doc/' -d '
{
"field": "value"
}'
id为该条数据的唯一id,如果不指定id,则会自动随机生成一个id。
批量导入:
curl -u {username}:{password} --header 'Content-Type: application/json' -XPOST '{host}:{port}/index_name/_doc/_bulk?pretty' -d '
{"index":{"_id":"1"}}
{"name": "John Doe" }
{"index":{"_id":"2"}}
{"name": "Jane Doe" }
'
每两行为一条数据,必须用换行符分隔。
使用如下命令导入文件:
curl -u {username}:{password} --header 'Content-Type: application/json' -XPOST '{host}:{port}/index_name/_doc/_bulk' --data-binary @import.json
其中import.json为文件名,单个文件不能超过100M,大文件可分割为小文件并行导入。
查询数据
列出集群中所有的 index:
curl -u {username}:{password} --header 'Content-Type: application/json' -XGET '{host}:{port}/_cat/indices?v'
查询 index 中的数据:
curl -u {username}:{password} --header 'Content-Type: application/json' -XGET '{host}:{port}/testindex/_search?pretty' -d '
{
"query": { "match_all": {} }
}'
关于Elasticsearch其他详细API介绍,请参考Elasticsearch官方文档:
https://www.elastic.co/guide/en/elasticsearch/reference/current/index.html