lqshow / notes

Cheat Sheet
10 stars 2 forks source link

Elasticsearch CURD #16

Open lqshow opened 6 years ago

lqshow commented 6 years ago

创建索引文档

使用自定义ID

PUT /{index}/{type}/{id}
{
  "field": "value",
  ...
}

自动生成唯一ID

POST /{index}/{type}/
{
  "field": "value",
  ...
}

例子

curl -XPOST http://localhost:9200/index_test/doc/1 -d'{"content":"美国留给伊拉克的是个烂摊子吗","title":"标题","tags":["美国","伊拉克","烂摊子"]}'
curl -XPOST http://localhost:9200/index_test/doc/2 -d'{"content":"中国是世界上人口最多的国家","title":"中国","tags":["中国","人口"]}'
curl -XPOST http://localhost:9200/index_test/doc/3 -d'{"content":"同一个世界同一个梦想","title":"北京奥运","tags":["和平"]}'
curl -XPOST http://localhost:9200/index_test/doc/4 -d'{"content":"杭州是一个美丽的城市,欢迎来到杭州","title":"宣传","tags":["旅游","城市"]}'

创建新文档

如果_index 、 _type 和 _id 的文档已经存在,Elasticsearch 将会返回 409 Conflict 响应码

PUT /{index}/{type}/{id}?op_type=create
{
...
}
PUT /{index}/{type}/{id}/_create
{
  ...
}

取回索引文档

取回文档所有数据

GET /{index}/{type}/{id}

取回文档部分数据(比如field1,field2两字段)

GET /{index}/{type}/{id}?_source=field1,field2

只取回_source字段,排除其他元数据(例如_index, _type等)

GET /{index}/{type}/{id}/_source

更新整个文档(替换操作)

检索-修改-重建索引

PUT /{index}/{type}/{id}
{
  "field": "value",
  ...
}

更新部分文档

接收文档的一部分作为 doc 的参数,与现有的文档进行合并。 对象被合并到一起,覆盖现有的字段,增加新的字段。

curl -XPOST 'localhost:9200/index_test/doc/3/_update?pretty' -H 'Content-Type: application/json' -d'
{
   "doc" : {
      "content": "同一个世界同一个梦想update",
          "tags" : [ "testing" ]
   }
}
'

删除文档

DELETE /{index}/{type}/{id}

批量取回多个文档

通过ids数组做参数(_index和_type都相同)

curl -XGET 'localhost:9200/index_test/doc/_mget?pretty' -H 'Content-Type: application/json' -d'
{
   "ids" : [1, 2]
}
'

通过docs数组做参数(_index和_type都不同)

curl -XGET 'localhost:9200/_mget?pretty' -H 'Content-Type: application/json' -d'
{
   "docs" : [
      {
         "_index" : "index_test",
         "_type" :  "doc",
         "_id" :    2
      },
      {
         "_index" : "index_test",
         "_type" :  "doc",
         "_id" :    1,
         "_source": "tags"
      }
   ]
}
'
curl -XGET 'localhost:9200/index_test/doc/_mget?pretty' -H 'Content-Type: application/json' -d'
{
   "docs" : [
      { 
        "_id" : 2 
      },
      { 
        "_type" : "pageviews", 
        "_id" :   1 
      }
   ]
}
'