REST介绍与CURL应用

来源:互联网 发布:上海公交软件哪个好 编辑:程序博客网 时间:2024/06/06 14:20

REST内容转载两篇文章
http://www.ruanyifeng.com/blog/2011/09/restful
http://www.ruanyifeng.com/blog/2014/05/restful_api.html

先大致了解RESTFull概念之后,再进行实际的curl操作:

1、 REST引言

越来越多的人开始意识到,网站即软件,而且是一种新型的软件。

这种”互联网软件”采用客户端/服务器模式,建立在分布式体系上,通过互联网通信,具有高延时(high latency)、高并发等特点。

RESTful架构,就是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。

1.1 名称

REST,即Representational State Transfer的缩写,”表现层状态转化”。如果一个架构符合REST原则,就称它为RESTful架构。

1.2资源(Resources)

REST的名称”表现层状态转化”中,省略了主语。”表现层”其实指的是”资源”(Resources)的”表现层”。所谓”资源”,就是网络上的一个实体,或者说是网络上的一个具体信息。

1.3表现层(Representation)

“资源”是一种信息实体,它可以有多种外在表现形式。我们把”资源”具体呈现出来的形式,叫做它的”表现层”(Representation)。

文本可以用txt格式表现,也可以用HTML格式、XML格式、JSON格式表现,甚至可以采用二进制格式;图片可以用JPG格式表现,也可以用PNG格式表现。

URI只代表资源的实体,不代表它的形式。严格地说,有些网址最后的”.html”后缀名是不必要的,因为这个后缀名表示格式,属于”表现层”范畴,而URI应该只代表”资源”的位置。它的具体表现形式,应该在HTTP请求的头信息中用Accept和Content-Type字段指定,这两个字段才是对”表现层”的描述。

1.4状态转化(State Transfer)

互联网通信协议HTTP协议,是一个无状态协议。这意味着,所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某种手段,让服务器端发生”状态转化”(State Transfer)。而这种转化是建立在表现层之上的,所以就是”表现层状态转化”。

客户端用到的手段,只能是HTTP协议。具体来说,就是HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:
- GET用来获取资源
- POST用来新建资源(也可以用于更新资源)
- PUT用来更新资源
- DELETE用来删除资源

1.5 小结

  • 每一个URI代表一种资源;
  • 客户端和服务器之间,传递这种资源的某种表现层;
  • 客户端通过四个HTTP动词,对服务器端资源进行操作,实现”表现层状态转化”。

2、RESTful API

必须有一种统一的机制,方便不同的前端设备与后端进行通信。这导致API构架的流行。RESTful API是目前比较成熟的一套互联网应用程序的API设计理论。

2.1 协议

API与用户的通信协议,总是使用HTTPs协议。
应该尽量将API部署在专用域名之下。
https://api.example.com

2.2 版本(Versioning)

应该将API的版本号放入URL。
ttps://api.example.com/v1/

2.3 路径(Endpoint)

路径又称”终点”(endpoint),表示API的具体网址。

在RESTful架构中,每个网址代表一种资源(resource),所以网址中不能有动词,只能有名词,而且所用的名词往往与数据库的表格名对应。一般来说,数据库中的表都是同种记录的”集合”(collection),所以API中的名词也应该使用复数。

举例来说,有一个API提供动物园(zoo)的信息,还包括各种动物和雇员的信息,则它的路径应该设计成下面这样。

https://api.example.com/v1/zooshttps://api.example.com/v1/animalshttps://api.example.com/v1/employees

2.4 HTTP动词

对于资源的具体操作类型,由HTTP动词表示。

常用的HTTP动词有下面五个(括号里是对应的SQL命令)。

  • GET(SELECT):从服务器取出资源(一项或多项)。
  • POST(CREATE):在服务器新建一个资源。
  • PUT(UPDATE):在服务器更新资源(客户端提供改变后的完整资源)。
  • PATCH(UPDATE):在服务器更新资源(客户端提供改变的属性)。
  • DELETE(DELETE):从服务器删除资源。

还有两个不常用的HTTP动词。
- HEAD:获取资源的元数据。
- OPTIONS:获取信息,关于资源的哪些属性是客户端可以改变的。

下面是一些例子。

GET /zoos:列出所有动物园POST /zoos:新建一个动物园GET /zoos/ID:获取某个指定动物园的信息PUT /zoos/ID:更新某个指定动物园的信息(提供该动物园的全部信息)PATCH /zoos/ID:更新某个指定动物园的信息(提供该动物园的部分信息)DELETE /zoos/ID:删除某个动物园GET /zoos/ID/animals:列出某个指定动物园的所有动物DELETE /zoos/ID/animals/ID:删除某个指定动物园的指定动物

2.5 过滤信息(Filtering)

如果记录数量很多,服务器不可能都将它们返回给用户。API应该提供参数,过滤返回结果。

下面是一些常见的参数。

?limit=10:指定返回记录的数量?offset=10:指定返回记录的开始位置。?page=2&per_page=100:指定第几页,以及每页的记录数。?sortby=name&order=asc:指定返回结果按照哪个属性排序,以及排序顺序。?animal_type_id=1:指定筛选条件

参数的设计允许存在冗余,即允许API路径和URL参数偶尔有重复。比如,GET /zoo/ID/animals 与 GET /animals?zoo_id=ID 的含义是相同的。

2.6状态码(Status Codes)

服务器向用户返回的状态码和提示信息,常见的有以下一些(方括号中是该状态码对应的HTTP动词)。

200 OK - [GET]:服务器成功返回用户请求的数据,该操作是幂等的(Idempotent)。201 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。202 Accepted - [*]:表示一个请求已经进入后台排队(异步任务)204 NO CONTENT - [DELETE]:用户删除数据成功。400 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操作,该操作是幂等的。401 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。403 Forbidden - [*] 表示用户得到授权(与401错误相对),但是访问是被禁止的。404 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操作,该操作是幂等的。406 Not Acceptable - [GET]:用户请求的格式不可得(比如用户请求JSON格式,但是只有XML格式)。410 Gone -[GET]:用户请求的资源被永久删除,且不会再得到的。422 Unprocesable entity - [POST/PUT/PATCH] 当创建一个对象时,发生一个验证错误。500 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将无法判断发出的请求是否成功。

2.7 错误处理(Error handling)

如果状态码是4xx,就应该向用户返回出错信息。一般来说,返回的信息中将error作为键名,出错信息作为键值即可。

    {        error: "Invalid API key"    }

2.8 返回结果

针对不同操作,服务器向用户返回的结果应该符合以下规范。

GET /collection:返回资源对象的列表(数组)GET /collection/resource:返回单个资源对象POST /collection:返回新生成的资源对象PUT /collection/resource:返回完整的资源对象PATCH /collection/resource:返回完整的资源对象DELETE /collection/resource:返回一个空文档

2.9 Hypermedia API

RESTful API最好做到Hypermedia,即返回结果中提供链接,连向其他API方法,使得用户不查文档,也知道下一步应该做什么。

比如,当用户向api.example.com的根目录发出请求,会得到这样一个文档。

    {"link": {      "rel":   "collection https://www.example.com/zoos",      "href":  "https://api.example.com/zoos",      "title": "List of zoos",      "type":  "application/vnd.yourformat+json"    }}

上面代码表示,文档中有一个link属性,用户读取这个属性就知道下一步该调用什么API了。rel表示这个API与当前网址的关系(collection关系,并给出该collection的网址),href表示API的路径,title表示API的标题,type表示返回类型。

3、curl

3.1 curl介绍

curl命令是一个功能强大的网络工具,它能够通过http、ftp等方式下载文件,也能够上传文件。其实curl远不止前面所说的那些功能

curl命令使用了libcurl库来实现,libcurl库常用在C程序中用来处理HTTP请求,curlpp是libcurl的一个C++封装,这几个东西可以用在抓取网页、网络监控等方面的开发,而curl命令可以帮助来解决开发过程中遇到的问题。

安装curl

[root@hadron ~]# yum install -y curl

3.2 curl所有参数概览

[root@hadron ~]# curl --helpUsage: curl [options...] <url>Options: (H) means HTTP/HTTPS only, (F) means FTP only     --anyauth       Pick "any" authentication method (H) -a, --append        Append to target file when uploading (F/SFTP)     --basic         Use HTTP Basic Authentication (H)     --cacert FILE   CA certificate to verify peer against (SSL)     --capath DIR    CA directory to verify peer against (SSL) -E, --cert CERT[:PASSWD] Client certificate file and password (SSL)     --cert-type TYPE Certificate file type (DER/PEM/ENG) (SSL)     --ciphers LIST  SSL ciphers to use (SSL)     --compressed    Request compressed response (using deflate or gzip) -K, --config FILE   Specify which config file to read     --connect-timeout SECONDS  Maximum time allowed for connection -C, --continue-at OFFSET  Resumed transfer offset -b, --cookie STRING/FILE  String or file to read cookies from (H) -c, --cookie-jar FILE  Write cookies to this file after operation (H)     --create-dirs   Create necessary local directory hierarchy     --crlf          Convert LF to CRLF in upload     --crlfile FILE  Get a CRL list in PEM format from the given file -d, --data DATA     HTTP POST data (H)     --data-ascii DATA  HTTP POST ASCII data (H)     --data-binary DATA  HTTP POST binary data (H)     --data-urlencode DATA  HTTP POST data url encoded (H)     --delegation STRING GSS-API delegation permission     --digest        Use HTTP Digest Authentication (H)     --disable-eprt  Inhibit using EPRT or LPRT (F)     --disable-epsv  Inhibit using EPSV (F) -D, --dump-header FILE  Write the headers to this file     --egd-file FILE  EGD socket path for random data (SSL)     --engine ENGINGE  Crypto engine (SSL). "--engine list" for list -f, --fail          Fail silently (no output at all) on HTTP errors (H) -F, --form CONTENT  Specify HTTP multipart POST data (H)     --form-string STRING  Specify HTTP multipart POST data (H)     --ftp-account DATA  Account data string (F)     --ftp-alternative-to-user COMMAND  String to replace "USER [name]" (F)     --ftp-create-dirs  Create the remote dirs if not present (F)     --ftp-method [MULTICWD/NOCWD/SINGLECWD] Control CWD usage (F)     --ftp-pasv      Use PASV/EPSV instead of PORT (F) -P, --ftp-port ADR  Use PORT with given address instead of PASV (F)     --ftp-skip-pasv-ip Skip the IP address for PASV (F)     --ftp-pret      Send PRET before PASV (for drftpd) (F)     --ftp-ssl-ccc   Send CCC after authenticating (F)     --ftp-ssl-ccc-mode ACTIVE/PASSIVE  Set CCC mode (F)     --ftp-ssl-control Require SSL/TLS for ftp login, clear for transfer (F) -G, --get           Send the -d data with a HTTP GET (H) -g, --globoff       Disable URL sequences and ranges using {} and [] -H, --header LINE   Custom header to pass to server (H) -I, --head          Show document info only -h, --help          This help text     --hostpubmd5 MD5  Hex encoded MD5 string of the host public key. (SSH) -0, --http1.0       Use HTTP 1.0 (H)     --ignore-content-length  Ignore the HTTP Content-Length header -i, --include       Include protocol headers in the output (H/F) -k, --insecure      Allow connections to SSL sites without certs (H)     --interface INTERFACE  Specify network interface/address to use -4, --ipv4          Resolve name to IPv4 address -6, --ipv6          Resolve name to IPv6 address -j, --junk-session-cookies Ignore session cookies read from file (H)     --keepalive-time SECONDS  Interval between keepalive probes     --key KEY       Private key file name (SSL/SSH)     --key-type TYPE Private key file type (DER/PEM/ENG) (SSL)     --krb LEVEL     Enable Kerberos with specified security level (F)     --libcurl FILE  Dump libcurl equivalent code of this command line     --limit-rate RATE  Limit transfer speed to this rate -l, --list-only     List only names of an FTP directory (F)     --local-port RANGE  Force use of these local port numbers -L, --location      Follow redirects (H)     --location-trusted like --location and send auth to other hosts (H) -M, --manual        Display the full manual     --mail-from FROM  Mail from this address     --mail-rcpt TO  Mail to this receiver(s)     --mail-auth AUTH  Originator address of the original email     --max-filesize BYTES  Maximum file size to download (H/F)     --max-redirs NUM  Maximum number of redirects allowed (H) -m, --max-time SECONDS  Maximum time allowed for the transfer     --metalink      Process given URLs as metalink XML file     --negotiate     Use HTTP Negotiate Authentication (H) -n, --netrc         Must read .netrc for user name and password     --netrc-optional Use either .netrc or URL; overrides -n     --netrc-file FILE  Set up the netrc filename to use -N, --no-buffer     Disable buffering of the output stream     --no-keepalive  Disable keepalive use on the connection     --no-sessionid  Disable SSL session-ID reusing (SSL)     --noproxy       List of hosts which do not use proxy     --ntlm          Use HTTP NTLM authentication (H) -o, --output FILE   Write output to <file> instead of stdout     --pass PASS     Pass phrase for the private key (SSL/SSH)     --post301       Do not switch to GET after following a 301 redirect (H)     --post302       Do not switch to GET after following a 302 redirect (H)     --post303       Do not switch to GET after following a 303 redirect (H) -#, --progress-bar  Display transfer progress as a progress bar     --proto PROTOCOLS  Enable/disable specified protocols     --proto-redir PROTOCOLS  Enable/disable specified protocols on redirect -x, --proxy [PROTOCOL://]HOST[:PORT] Use proxy on given port     --proxy-anyauth Pick "any" proxy authentication method (H)     --proxy-basic   Use Basic authentication on the proxy (H)     --proxy-digest  Use Digest authentication on the proxy (H)     --proxy-negotiate Use Negotiate authentication on the proxy (H)     --proxy-ntlm    Use NTLM authentication on the proxy (H) -U, --proxy-user USER[:PASSWORD]  Proxy user and password     --proxy1.0 HOST[:PORT]  Use HTTP/1.0 proxy on given port -p, --proxytunnel   Operate through a HTTP proxy tunnel (using CONNECT)     --pubkey KEY    Public key file name (SSH) -Q, --quote CMD     Send command(s) to server before transfer (F/SFTP)     --random-file FILE  File for reading random data from (SSL) -r, --range RANGE   Retrieve only the bytes within a range     --raw           Do HTTP "raw", without any transfer decoding (H) -e, --referer       Referer URL (H) -J, --remote-header-name Use the header-provided filename (H) -O, --remote-name   Write output to a file named as the remote file     --remote-name-all Use the remote file name for all URLs -R, --remote-time   Set the remote file's time on the local output -X, --request COMMAND  Specify request command to use     --resolve HOST:PORT:ADDRESS  Force resolve of HOST:PORT to ADDRESS     --retry NUM   Retry request NUM times if transient problems occur     --retry-delay SECONDS When retrying, wait this many seconds between each     --retry-max-time SECONDS  Retry only within this period -S, --show-error    Show error. With -s, make curl show errors when they occur -s, --silent        Silent mode. Don't output anything     --socks4 HOST[:PORT]  SOCKS4 proxy on given host + port     --socks4a HOST[:PORT]  SOCKS4a proxy on given host + port     --socks5 HOST[:PORT]  SOCKS5 proxy on given host + port     --socks5-hostname HOST[:PORT] SOCKS5 proxy, pass host name to proxy     --socks5-gssapi-service NAME  SOCKS5 proxy service name for gssapi     --socks5-gssapi-nec  Compatibility with NEC SOCKS5 server -Y, --speed-limit RATE  Stop transfers below speed-limit for 'speed-time' secs -y, --speed-time SECONDS  Time for trig speed-limit abort. Defaults to 30     --ssl           Try SSL/TLS (FTP, IMAP, POP3, SMTP)     --ssl-reqd      Require SSL/TLS (FTP, IMAP, POP3, SMTP) -2, --sslv2         Use SSLv2 (SSL) -3, --sslv3         Use SSLv3 (SSL)     --ssl-allow-beast Allow security flaw to improve interop (SSL)     --stderr FILE   Where to redirect stderr. - means stdout     --tcp-nodelay   Use the TCP_NODELAY option -t, --telnet-option OPT=VAL  Set telnet option     --tftp-blksize VALUE  Set TFTP BLKSIZE option (must be >512) -z, --time-cond TIME  Transfer based on a time condition -1, --tlsv1         Use => TLSv1 (SSL)     --tlsv1.0       Use TLSv1.0 (SSL)     --tlsv1.1       Use TLSv1.1 (SSL)     --tlsv1.2       Use TLSv1.2 (SSL)     --trace FILE    Write a debug trace to the given file     --trace-ascii FILE  Like --trace but without the hex output     --trace-time    Add time stamps to trace/verbose output     --tr-encoding   Request compressed transfer encoding (H) -T, --upload-file FILE  Transfer FILE to destination     --url URL       URL to work with -B, --use-ascii     Use ASCII/text transfer -u, --user USER[:PASSWORD]  Server user and password     --tlsuser USER  TLS username     --tlspassword STRING TLS password     --tlsauthtype STRING  TLS authentication type (default SRP)     --unix-socket FILE    Connect through this UNIX domain socket -A, --user-agent STRING  User-Agent to send to server (H) -v, --verbose       Make the operation more talkative -V, --version       Show version number and quit -w, --write-out FORMAT  What to output after completion     --xattr        Store metadata in extended file attributes -q                 If used as the first parameter disables .curlrc

3.3 简单应用

  1. 下载单个文件,默认将输出打印到标准输出中(STDOUT)中
[root@hadron ~]# curl http://www.centos.org<html><head><title>301 Moved Permanently</title></head><body bgcolor="white"><center><h1>301 Moved Permanently</h1></center><hr><center>nginx/1.10.1</center></body></html>
  1. 可以使用-o或-O重定向,抓取页面内容到一个文件中
[root@hadron ~]# curl -o home.html http://www.baidu.com  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                 Dload  Upload   Total   Spent    Left  Speed100  2381  100  2381    0     0  37752      0 --:--:-- --:--:-- --:--:-- 38403[root@hadron ~]# ll |grep home.html-rw-r--r--  1 root root        2381 310 16:31 home.html

3.4 下载

-O(大写的),后面的url要具体到某个文件,不然抓不下来

-L选项进行强制重定向

[root@hadron ~]# curl -L -O https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-5.2.2.tar.gz  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current                                 Dload  Upload   Total   Spent    Left  Speed100 32.2M  100 32.2M    0     0  42035      0  0:13:24  0:13:24 --:--:-- 37582

3.5 -u 指定用户名和密码

[root@hadron ~]# curl -u admin:admin http://192.168.1.25:8080/api/v1/clusters{  "href" : "http://192.168.1.25:8080/api/v1/clusters",  "items" : [    {      "href" : "http://192.168.1.25:8080/api/v1/clusters/cc",      "Clusters" : {        "cluster_name" : "cc",        "version" : "HDP-2.5"      }    }  ]}[root@hadron ~]# 

3.6 GET查询

默认curl使用GET方式请求数据,这种方式下直接通过URL传递数据

[root@hadron ~]# curl http://192.168.1.181:9200/_cluster/health?pretty{  "cluster_name" : "es",  "status" : "green",  "timed_out" : false,  "number_of_nodes" : 3,  "number_of_data_nodes" : 3,  "active_primary_shards" : 0,  "active_shards" : 0,  "relocating_shards" : 0,  "initializing_shards" : 0,  "unassigned_shards" : 0,  "delayed_unassigned_shards" : 0,  "number_of_pending_tasks" : 0,  "number_of_in_flight_fetch" : 0,  "task_max_waiting_in_queue_millis" : 0,  "active_shards_percent_as_number" : 100.0}

3.7 -X指定协议

还可以通过 -X 选项指定协议

[root@hadron ~]# curl -XGET http://192.168.1.181:9200/_cluster/health?pretty{  "cluster_name" : "es",  "status" : "green",  "timed_out" : false,  "number_of_nodes" : 3,  "number_of_data_nodes" : 3,  "active_primary_shards" : 0,  "active_shards" : 0,  "relocating_shards" : 0,  "initializing_shards" : 0,  "unassigned_shards" : 0,  "delayed_unassigned_shards" : 0,  "number_of_pending_tasks" : 0,  "number_of_in_flight_fetch" : 0,  "task_max_waiting_in_queue_millis" : 0,  "active_shards_percent_as_number" : 100.0}[root@hadron ~]# GET方法只是查询,不改变系统状态。POST方法可以更改系统状态

查询节点的状态

[root@hadron ~]# curl -XGET 192.168.1.181:9200/_nodes/process{"_nodes":{"total":3,"successful":3,"failed":0},"cluster_name":"es","nodes":{"mWFZ25DdT-SbrP8fwu3NYg":{"name":"vnode1","transport_address":"192.168.1.181:9300","host":"vnode1","ip":"192.168.1.181","version":"5.1.1","build_hash":"5395e21","roles":["master","data","ingest"],"attributes":{"rack":"rack01"},"process":{"refresh_interval_in_millis":1000,"id":13073,"mlockall":true}},"xpPLpbXhSzOm3M-IfKhWfA":{"name":"vnode3","transport_address":"192.168.1.183:9300","host":"vnode3","ip":"192.168.1.183","version":"5.1.1","build_hash":"5395e21","roles":["master","data","ingest"],"attributes":{"rack":"rack01"},"process":{"refresh_interval_in_millis":1000,"id":91860,"mlockall":true}},"E0fwSa_qRSu_Ri0xjJn7bA":{"name":"vnode2","transport_address":"192.168.1.182:9300","host":"vnode2","ip":"192.168.1.182","version":"5.1.1","build_hash":"5395e21","roles":["master","data","ingest"],"attributes":{"rack":"rack01"},"process":{"refresh_interval_in_millis":1000,"id":15562,"mlockall":true}}}}

3.8 -d 传递数据

可以通过 –data/-d 方式指定使用POST方式传递数据

创建(PUT)

[root@hadron ~]# curl -XPUT 'http://192.168.1.181:9200/dept/employee/32' -d '{ "empname": "emp32"}'{"_index":"dept","_type":"employee","_id":"32","_version":1,"result":"created","_shards":{"total":2,"successful":1,"failed":0},"created":true}

注意cURL命令的一个新选项: -d 参数。
此选项的值是将作为请求负载的文本,也即请求主
体(request body)。这样,我们可以发送附加信息,如文档定义。同时,注意唯一标识符(32)是
放在URL,而不是请求主体中。

[root@hadron ~]# curl -XPUT 'http://192.168.1.181:9200/dept/employee/1' -d '{ "empname": "emp1"}'{"_index":"dept","_type":"employee","_id":"1","_version":1,"result":"created","_shards":{"total":2,"successful":2,"failed":0},"created":true}[root@hadron ~]# curl -XPUT 'http://192.168.1.181:9200/dept/employee/2' -d '{ "empname": "emp2"}'{"_index":"dept","_type":"employee","_id":"2","_version":1,"result":"created","_shards":{"total":2,"successful":2,"failed":0},"created":true}[root@hadron ~]# curl -XPUT 'http://192.168.1.181:9200/dept/employee/3' -d '{ "empname": "emp3"}'{"_index":"dept","_type":"employee","_id":"3","_version":1,"result":"created","_shards":{"total":2,"successful":2,"failed":0},"created":true}[root@hadron ~]# curl -XPUT 'http://192.168.1.181:9200/dept/employee/4' -d '{ "empname": "emp4"}'{"_index":"dept","_type":"employee","_id":"4","_version":1,"result":"created","_shards":{"total":2,"successful":2,"failed":0},"created":true}[root@hadron ~]# 
[root@hadron curl -XPUT http://192.168.1.181:9200/blog/article/1 -d '{"title": "New version of Elasticsearch released!", "content": "Version 1.0 released today!", "tags": ["announce","elasticsearch", "release"] }'{"_index":"blog","_type":"article","_id":"1","_version":1,"result":"created","_shards":{"total":2,"successful":2,"failed":0},"created":true}[root@hadron ~]# curl -XGET http://192.168.1.181:9200/blog/article/1{"_index":"blog","_type":"article","_id":"1","_version":1,"found":true,"_source":{"title": "New version of Elasticsearch released!", "content": "Version 1.0 released today!", "tags": ["announce","elasticsearch", "release"] }}

3.9 POST(创建与更新)

标识符的自动创建
在上面的示例中,我们自己指定了文档标识符。然而,Elasticsearch可以自动生成它。

使用
HTTP POST请求类型并且不在URL中指定标识符,就可以生成一个唯一标识符

[root@hadron ~]# curl -XPOST http://192.168.1.181:9200/blog/article/ -d '{"title": "New version of Elasticsearch released!", "content": "Version 1.0 released today!", "tags":["announce", "elasticsearch", "release"] }'{"_index":"blog","_type":"article","_id":"AVq8Yww2OSCYXkaHfpSd","_version":1,"result":"created","_shards":{"total":2,"successful":2,"failed":0},"created":true

AVq8Yww2OSCYXkaHfpSd是自动生成的标识符

POST更新操作

[root@hadron ~]# curl -XPOST http://192.168.1.181:9200/blog/article/1/_update -d '{"script": "ctx._source.content = \"new content\""}'{"_index":"blog","_type":"article","_id":"1","_version":2,"result":"updated","_shards":{"total":2,"successful":2,"failed":0}}[root@hadron ~]# cd[root@hadron ~]# curl -XGET http://192.168.1.181:9200/blog/article/1{"_index":"blog","_type":"article","_id":"1","_version":2,"found":true,"_source":{"title":"New version of Elasticsearch released!","content":"new content","tags":["announce","elasticsearch","release"]}}[root@hadron ~]# 

3.10 DELETE删除

hadron ~]# curl -XGET http://192.168.1.181:9200/dept/employee/1{"_index":"dept","_type":"employee","_id":"1","_version":1,"found":true,"_source":{ "empname": "emp1"}}[root@hadron ~]# curl -XDELETE http://192.168.1.181:9200/dept/employee/1{"found":true,"_index":"dept","_type":"employee","_id":"1","_version":2,"result":"deleted","_shards":{"total":2,"successful":2,"failed":0}}
0 0
原创粉丝点击