Elasticsearch 提供了一个强大的 RESTful API,允许您通过 HTTP 请求与 Elasticsearch 集群进行交互,执行诸如索引文档、执行搜索、管理索引、监控集群状态等操作。以下是对 Elasticsearch RESTful API 的实战介绍,涵盖主要操作类别和常见用例:
**1. 索引管理
创建索引
- 请求方式:
PUT
或POST
- URL:
http://localhost:9200/<index_name>
- 示例:
curl -X PUT "localhost:9200/my_index?pretty"
获取索引信息
- 请求方式:
GET
- URL:
http://localhost:9200/<index_name>?pretty
- 示例:
curl -X GET "localhost:9200/my_index?pretty"
更新索引映射
- 请求方式:
PUT
- URL:
http://localhost:9200/<index_name>/_mapping
- 示例:
curl -X PUT "localhost:9200/my_index/_mapping?pretty" -H 'Content-Type: application/json' -d'
{
"properties": {
"description": { "type": "text" }
}
}'
删除索引
- 请求方式:
DELETE
- URL:
http://localhost:9200/<index_name>
- 示例:
curl -X DELETE "localhost:9200/my_index?pretty"
**2. 文档操作
索引文档
- 请求方式:
POST
- URL:
http://localhost:9200/<index_name>/_doc/<document_id>
- 示例:
curl -X POST "localhost:9200/my_index/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"title": "Elasticsearch Tutorial",
"content": "This is a tutorial on using Elasticsearch.",
"author": "John Doe",
"date": "2024-04-04"
}'
获取文档
- 请求方式:
GET
- URL:
http://localhost:9200/<index_name>/_doc/<document_id>
- 示例:
curl -X GET "localhost:9200/my_index/_doc/1?pretty"
更新文档
- 请求方式:
PUT
或POST
- URL:
http://localhost:9200/<index_name>/_doc/<document_id>
- 示例:
curl -X PUT "localhost:9200/my_index/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"doc": {
"content": "Updated content for the Elasticsearch tutorial."
},
"detect_noop": true
}'
删除文档
- 请求方式:
DELETE
- URL:
http://localhost:9200/<index_name>/_doc/<document_id>
- 示例:
curl -X DELETE "localhost:9200/my_index/_doc/1?pretty"
**3. 搜索操作
简单查询
- 请求方式:
GET
- URL:
http://localhost:9200/<index_name>/_search?q=<query_string>
- 示例:
curl -X GET "localhost:9200/my_index/_search?q=title:Elasticsearch&pretty"
查询DSL
- 请求方式:
GET
- URL:
http://localhost:9200/<index_name>/_search
- 示例:
curl -X GET "localhost:9200/my_index/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"content": "tutorial"
}
}
}'
**4. 聚合操作
执行聚合
- 请求方式:
GET
- URL:
http://localhost:9200/<index_name>/_search
- 示例:
curl -X GET "localhost:9200/my_index/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size": 0,
"aggs": {
"authors": {
"terms": {
"field": "author.keyword"
}
}
}
}'
**5. 集群管理
集群健康状态
- 请求方式:
GET
- URL:
http://localhost:9200/_cluster/health
- 示例:
curl -X GET "localhost:9200/_cluster/health?pretty"
节点统计信息
- 请求方式:
GET
- URL:
http://localhost:9200/_nodes/stats
- 示例:
curl -X GET "localhost:9200/_nodes/stats?pretty"
**6. 其他操作
刷新索引
- 请求方式:
POST
- URL:
http://localhost:9200/<index_name>/_refresh
- 示例:
curl -X POST "localhost:9200/my_index/_refresh?pretty"
获取集群状态
- 请求方式:
GET
- URL:
http://localhost:9200/_cluster/state
- 示例:
curl -X GET "localhost:9200/_cluster/state?pretty"
以上仅为 Elasticsearch RESTful API 的部分实战示例。实际使用时,您还可以查阅官方文档以获取更详尽的操作指南、参数说明和高级用法。Elasticsearch API 的强大之处在于其灵活性和丰富性,能够满足各种复杂的数据管理、搜索和分析需求。通过熟练掌握这些API,您可以有效地与Elasticsearch集群进行交互,构建高效的数据处理和搜索应用。