Document Metadata
- 三个必须的元数据是
- _index
- _type
- _id
Indexing a Document
如果不指定id,elastic search会自动生成。
PUT /{index}/{type}/{id}
{
"field": "value",
...
}
Retrieving a Document
GET /website/blog/123?pretty
pretty会格式化输出,结果如下,_source字段是原始的JSON document
{
"_index" : "website",
"_type" : "blog",
"_id" : "123",
"_version" : 1,
"found" : true,
"_source" : {
"title": "My first blog entry",
"text": "Just trying this out...",
"date": "2014/01/01"
}
}
只查询某些字段
GET /website/blog/123?_source=title,text
{
"_index" : "website",
"_type" : "blog",
"_id" : "123",
"_version" : 1,
"exists" : true,
"_source" : {
"title": "My first blog entry" ,
"text": "Just trying this out..."
}
}
只查询_source
GET /website/blog/123/_source
{
"title": "My first blog entry",
"text": "Just trying this out...",
"date": "2014/01/01"
}
查看文档是否存在
存在
curl -i -XHEAD http://localhost:9200/website/blog/123
HTTP/1.1 200 OK
Content-Type: text/plain; charset=UTF-8
Content-Length: 0
不存在
curl -i -XHEAD http://localhost:9200/website/blog/124
HTTP/1.1 404 Not Found
Content-Type: text/plain; charset=UTF-8
Content-Length: 0
更新整个文档
PUT /website/blog/123
{
"title": "My first blog entry",
"text": "I am starting to get the hang of this...",
"date": "2014/01/02"
}
{
"_index" : "website",
"_type" : "blog",
"_id" : "123",
"_version" : 2,
"created": false //false because a document with the same index, type, and ID already existed.
}
一个API背后包含了以下的操作
1. Retrieve the JSON from the old document
2. Change it
3. Delete the old document
4. Index a new document
创建新文档
最简单的方式是让Elastic Search自动生成id
POST /website/blog/
{ ... }
有两种方式可以指定id,返回201 Created或者409 Conflict
PUT /website/blog/123?op_type=create
{ ... }
PUT /website/blog/123/_create
{ ... }
删除文档
DELETE /website/blog/123
返回200 OK
{
"found" : true,
"_index" : "website",
"_type" : "blog",
"_id" : "123",
"_version" : 3
}
或者 404 Not Found
{
"found" : false,
"_index" : "website",
"_type" : "blog",
"_id" : "123",
"_version" : 4
}
部分更新
POST /website/blog/1/_update
{
"doc" : {
"tags" : [ "testing" ],
"views": 0
}
}
更新后
{
"_index": "website",
"_type": "blog",
"_id": "1",
"_version": 3,
"found": true,
"_source": {
"title": "My first blog entry",
"text": "Starting to get the hang of this...",
"tags": [ "testing" ],
"views": 0
}
}
检索多个文档
GET /_mget
{
"docs" : [
{
"_index" : "website",
"_type" : "blog",
"_id" : 2
},
{
"_index" : "website",
"_type" : "pageviews",
"_id" : 1,
"_source": "views"
}
]
}
如果想检索的文档在同一个_index甚至_type,可以在url中指定
GET /website/blog/_mget
{
"docs" : [
{ "_id" : 2 },
{ "_type" : "pageviews", "_id" : 1 }
]
}
在同一个_type下的文档可以使用ids代替docs
GET /website/blog/_mget
{
"ids" : [ "2", "1" ]
}
批量查询
{ action: { metadata }}\n
{ request body }\n
{ action: { metadata }}\n
{ request body }\n
...