开源Elasticsearch提供了一系列Restful风格的API,您可以通过curl命令使用,也可以在Kibana中使用。本文介绍如何通过curl命令,调用API与阿里云Elasticsearch实例进行交互,并完成查看集群信息、创建索引和文档、搜索文档等操作。
前提条件
注意 您也可以使用已创建的ECS实例,但需确保与Elasticsearch实例在相同VPC下。如果ECS处于经典网络下,期望访问VPC内的Elasticsearch,需要先参考通过经典网络访问ES常见问题进行相关配置。
背景信息
访问实例
查看集群信息
- 查看集群健康状况
curl -u <user>:<password> -XGET 'http://es-cn-vxxxxx****.elasticsearch.aliyuncs.com:9200/_cat/health?v'
执行成功后,返回如下结果。
- 查看集群中包含的索引信息
curl -u <user>:<password> -XGET 'http://es-cn-vxxxxx****.elasticsearch.aliyuncs.com:9200/_cat/indices?v'
执行成功后,返回如下结果。
创建索引和文档
- 创建索引
curl -u <user>:<password> -XPUT 'http://es-cn-vxxxxx****.elasticsearch.aliyuncs.com:9200/product_info'
以上示例创建了一个名称为
product_info
的索引。执行成功后,返回如下结果。 - 为索引设置mapping
curl -u <user>:<password> -XPUT 'http://es-cn-vxxxxx****.elasticsearch.aliyuncs.com:9200/product_info/_doc/_mapping' -H 'Content-Type: application/json' -d ' { "_doc":{ "properties": { "productName": {"type": "text","analyzer": "ik_smart"}, "annual_rate":{"type":"keyword"}, "describe": {"type": "text","analyzer": "ik_smart"} } } }'
执行成功后,返回如下结果。
以上示例设置
product_info
索引的类型为_doc
,包含了productName
、annual_rate
和describe
字段,并定义了各字段的类型所使用的分词器。 - 创建文档并插入数据
- 创建单个文档
curl -u <user>:<password> -XPOST 'http://es-cn-vxxxxx****.elasticsearch.aliyuncs.com:9200/product_info/_doc/1?pretty' -H 'Content-Type: application/json' -d ' { "productName":"testpro", "annual_rate":"3.22%", "describe":"testpro" }'
执行成功后,返回结果如下。以上示例在类型为
_doc
的product_info
索引中,创建了一个名称为1
的文档,并向文档中插入了一条数据。 - 创建多个文档
curl -u <user>:<password> -XPOST http://es-cn-vxxxxx****.elasticsearch.aliyuncs.com:9200/_bulk -H 'Content-Type: application/json' -d' { "index" : { "_index": "product_info", "_type" : "_doc", "_id" : "1" } } {"productName":"testpro","annual_rate":"3.22%","describe":"testpro"} { "index" : { "_index": "product_info", "_type" : "_doc", "_id" : "2" } } {"productName":"testpro1","annual_rate":"3.26%","describe":"testpro"}'
执行成功后,返回结果如下。以上示例在类型为
_doc
的product_info
索引中,创建了一个名称为1
和2
的文档,并分别向文档中插入了一条数据。
- 创建单个文档
搜索文档
curl -u <user>:<password> -XGET 'http://es-cn-vxxxxx****.elasticsearch.aliyuncs.com:9200/product_info/_doc/1?pretty'
执行成功后,返回结果如下。

以上示例搜索名称为1
的文档。
删除索引
curl -u <user>:<password> -XDELETE 'http://es-cn-vxxxxx****.elasticsearch.aliyuncs.com:9200/product_info'
执行成功后,返回结果如下。

以上示例删除了名称为product_info
的索引。
说明 更多命令,请参见Elasticsearch官方文档。