Elasticsearch 提供了丰富的 RESTful API 用于对索引中的文档进行 CRUD(Create, Read, Update, Delete)操作。以下是对 Elasticsearch 进行 CRUD 操作的实战演示,使用 curl
命令进行示例,假设 Elasticsearch 服务器运行在 http://localhost:9200
。
1. 创建(Create)
创建索引
创建一个名为 users
的索引:
curl -X PUT "http://localhost:9200/users" -H 'Content-Type: application/json'
响应:
{
"acknowledged": true,
"shards_acknowledged": true,
"index": "users"
}
添加文档
向 users
索引中添加一个用户文档:
curl -X POST "http://localhost:9200/users/_doc" -H 'Content-Type: application/json' -d'
{
"user_id": "1",
"name": "John Doe",
"email": "john.doe@example.com",
"age": 3Ⅱ,
"location": "New York"
}
'
响应:
{
"_index": "users",
"_type": "_doc",
"_id": "KjGQZHEB6zvYFfOc1TgP",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 0,
"_primary_term": 1
}
2. 读取(Read)
获取单个文档
查询用户 ID 为 1
的文档:
curl -X GET "http://localhost:9200/users/_doc/1"
响应:
{
"_index": "users",
"_type": "_doc",
"_id": "1",
"_version": 1,
"_seq_no": 0,
"_primary_term": 1,
"found": true,
"_source": {
"user_id": "1",
"name": "John Doe",
"email": "john.doe@example.com",
"age": 32,
"location": "New York"
}
}
查询多个文档
执行一个简单查询,查找所有年龄大于等于 30 的用户:
curl -X GET "http://localhost:9200/users/_search" -H 'Content-Type: application/json' -d'
{
"query": {
"range": {
"age": {
"gte": 30
}
}
}
}'
响应:
{
"took": .png,
"timed_out": false,
"_shards": {
"total": 1,
"successful": 1,
"skipped": 0,
"failed": 0
},
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 1.0,
"hits": [
{
"_index": "users",
"_type": "_doc",
"_id": "1",
"_score": 1.0,
"_source": {
"user_id": "1",
"name": "John Doe",
"email": "john.doe@example.com",
"age": 32,
"location": "New York"
}
}
]
}
}
3. 更新(Update)
部分更新
更新用户 ID 为 1
的电子邮件地址:
curl -X PUT "http://localhost:9200/users/_doc/1" -H 'Content-Type: application/json' -d'
{
"doc": {
"email": "john.new@example.com"
}
}'
响应:
{
"_index": "users",
"_type": "_doc",
"_id": "1",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 1,
"_primary_term": 1
}
4. 删除(Delete)
删除单个文档
删除用户 ID 为 1
的文档:
curl -X DELETE "http://localhost:9200/users/_doc/1"
响应:
{
"_index": "users",
"_type": "_doc",
"_id": "1",
"_version": 3,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 2,
"_primary_term": 1
}
删除索引
删除整个 users
索引:
curl -X DELETE "http://localhost:9200/users"
响应:
{
"acknowledged": true
}
以上就是对 Elasticsearch 进行 CRUD 操作的实战演示。在实际使用中,您可能需要结合映射定义、复杂查询、聚合分析等功能进行更丰富的数据管理与查询操作。同时,这些操作也可以通过 Kibana Dev Tools Console 或其他客户端库(如官方提供的各种语言客户端)来完成。