Elasticsearch 与REST API交互
Elasticsearch是一个分布式搜索和分析引擎,广泛用于全文搜索、日志分析和实时数据分析。它提供了一个强大的RESTful API,允许开发者通过HTTP请求与Elasticsearch进行交互。本文将带你了解如何使用REST API与Elasticsearch进行基本的操作,包括索引创建、文档插入、更新、删除和查询。
1. Elasticsearch REST API简介
Elasticsearch的REST API是基于HTTP协议的,支持多种HTTP方法(如GET、POST、PUT、DELETE等)来执行不同的操作。通过REST API,你可以与Elasticsearch集群进行交互,执行诸如创建索引、插入文档、搜索数据等操作。
提示
Elasticsearch的REST API默认使用9200端口。你可以通过http://localhost:9200
访问Elasticsearch的API。
2. 基本操作
2.1 创建索引
在Elasticsearch中,索引类似于数据库中的表。你可以通过PUT请求创建一个新的索引。
PUT /my_index
{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 1
}
}
响应:
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "my_index"
}
2.2 插入文档
文档是Elasticsearch中的基本数据单元。你可以通过POST请求向索引中插入文档。
POST /my_index/_doc/
{
"name": "John Doe",
"age": 30,
"email": "[email protected]"
}
响应:
{
"_index": "my_index",
"_type": "_doc",
"_id": "1",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 0,
"_primary_term": 1
}
2.3 查询文档
你可以通过GET请求查询索引中的文档。
GET /my_index/_doc/1
响应:
{
"_index": "my_index",
"_type": "_doc",
"_id": "1",
"_version": 1,
"_seq_no": 0,
"_primary_term": 1,
"found": true,
"_source": {
"name": "John Doe",
"age": 30,
"email": "[email protected]"
}
}
2.4 更新文档
你可以通过POST请求更新文档。
POST /my_index/_update/1
{
"doc": {
"age": 31
}
}
响应:
{
"_index": "my_index",
"_type": "_doc",
"_id": "1",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 1,
"_primary_term": 1
}
2.5 删除文档
你可以通过DELETE请求删除文档。
DELETE /my_index/_doc/1
响应:
{
"_index": "my_index",
"_type": "_doc",
"_id": "1",
"_version": 3,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 2,
"_primary_term": 1
}