创建Index

新建Index,可以直接向Elastic服务器发送PUT请求,比如下面的命令创建了一个名为:logdb的Index。

[root@elsearchserver ~]# curl -X PUT 'http://192.168.1.40:9200/logdb'

Elastic服务器返回一个JSON对象,里面的acknowledged字段为true表示操作成功。

{
"acknowledged": true,
"shards_acknowledged": true,
"index": "logdb"
}

注意:索引名必须全部小写,且不能以下划线开头,不能包含逗号。

新增记录

向指定的/Index/Type发送POST请求,就可以在Index里面新增一条记录。比如,向/logdb/debuglog发送请求,就可以新增一条debuglog调试日志记录。如下代码:

curl -X POST 'http://192.168.1.40:9200/logdb/debuglog' -d '
{
"SystemCode": "Ubtrip",
"Source": "ApprovalService",
"Message": "数据库管理"
}'

上面的代码,向/logdb/debuglog发出了一个POST请求,添加一条记录。这时服务器返回的JSON对象里面,_id是一个随机字符串,如下代码:

{
"_index": "logdb",
"_type": "debuglog",
"_id": "qpzDUWIB9teAN1UfUbN_",
"_version": 1,
"result": "created",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 0,
"_primary_term": 1
}

修改记录

修改记录就是使用PUT请求,重新向Elastic服务器发送一次数据,下面的代码中,我们将原记录的Message由“数据库管理”修改为了“数据库管理,即DBA”,请求代码如下:

http://192.168.1.40:9200/logdb/debuglog/qpzDUWIB9teAN1UfUbN_

{
"SystemCode": "Ubtrip",
"Source": "ApprovalService",
"Message": "数据库管理,即DBA"
}

服务器返回结果如下代码:

{
"_index": "logdb",
"_type": "debuglog",
"_id": "qpzDUWIB9teAN1UfUbN_",
"_version": 2,
"result": "updated",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 1,
"_primary_term": 1
}

从结果可以看到,以下几个字段发生了变化。

"_version": 2,
"result": "updated",

查询记录

向/Index/Type发送GET请求,就可以查询记录。例如:查询索引logdb下Type为debuglog的所有记录,请求url如下:

http://192.168.1.40:9200/logdb/debuglog/_search?pretty=true

URL参数的pretty=true表过以易读格式返回。

服务器返回结果如下:

{
"took" : 63,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 2,
"max_score" : 1.0,
"hits" : [
{
"_index" : "logdb",
"_type" : "debuglog",
"_id" : "qpzDUWIB9teAN1UfUbN_",
"_score" : 1.0,
"_source" : {
"SystemCode" : "Ubtrip",
"Source" : "ApprovalService",
"Message" : "数据库管理,即DBA"
}
},
{
"_index" : "logdb",
"_type" : "debuglog",
"_id" : "q5zTUWIB9teAN1UfvLNS",
"_score" : 1.0,
"_source" : {
"SystemCode" : "Ubtrip",
"Source" : "ApprovalService",
"Message" : "数据库管理,即DBA"
}
}
]
}
}

删除记录

删除记录就是向服务器发送一个DELETE请求,例如,我要删除/logdb/debuglog下_id为“q5zTUWIB9teAN1UfvLNS”的记录,请求URL如下:

curl -X DELETE 'http://192.168.1.40:9200/logdb/debuglog/q5zTUWIB9teAN1UfvLNS'

服务器返回结果如下:

{
"_index": "logdb",
"_type": "debuglog",
"_id": "q5zTUWIB9teAN1UfvLNS",
"_version": 2,
"result": "deleted",
"_shards": {
"total": 2,
"successful": 1,
"failed": 0
},
"_seq_no": 1,
"_primary_term": 1
}

再次查询/logdb/debuglog下所有记录,发现只剩下一条了,已经找不到_id为“q5zTUWIB9teAN1UfvLNS”的记录了。

{
"took" : 4,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : 1.0,
"hits" : [
{
"_index" : "logdb",
"_type" : "debuglog",
"_id" : "qpzDUWIB9teAN1UfUbN_",
"_score" : 1.0,
"_source" : {
"SystemCode" : "Ubtrip",
"Source" : "ApprovalService",
"Message" : "数据库管理,即DBA"
}
}
]
}
}
05-08 08:30