Elasticsearch基本语法

一、创建文档索引
1、语法格式
PUT /{index}/{type}/{id}
{
  "field": "value",
  ...
}
_index:文档存放在哪里
_type:文档表示的对象类别
_id:文档唯一标识

  

2、示例

PUT /website/blog/123
{
  "title": "My first blog entry",
  "text":  "Just trying this out...",
  "date":  "2014/01/01"
}

  

创建索引website,并在索引下创建blog类型,并添加id为123的博文

3 响应

{ "_index": "websit", "_type": "blog", "_id": "123", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 0, "_primary_term": 1 }

result值为created表示创建

4、自动生成_id

修改请求方法PUTPOST,请求路径中不再包含id,例如:POST /website/blog/,Elasticsearch将根据自动生成策略生成id。同时,这种策略是可以自行配置修改的。

二、获取文档

1、语法

GET /{index}/{type}/{id}?pretty

请求方法:GET

2、示例

GET /website/blog/123?pretty

pretty:格式化返回格式(_source值原样输出)

3、响应

{
    "_index": "websit",
    "_type": "blog",
    "_id": "123",
    "_version": 1,
    "found": true,
    "_source": {
        "title": "My first blog entry",
        "text": "Just trying this out...",
        "date": "2014/01/01"
    }
}

found:该值表示是否获取到匹配结果,true-匹配到,false-未匹配到

4、指定数据返回

GET /website/blog/123?_source

当仅需要获取文档信息时,通过_source关键字进行过滤。

GET /website/blog/123?_source=title,text

通过_source参数也可以指定需要返回的数据,此处为只返回title text内容,关键字以,分隔。

三、更新文档

1、执行步骤

1、从旧文档构建 JSON
2、更改该 JSON
3、删除旧文档
4、索引一个新文档

2、示例

PUT /website/blog/123
{
  "title": "My first blog entry",
  "text":  "Just trying this out...",
  "date":  "2018/01/01"
}

/website/blog/123将标识文档的唯一性,通过再次PUT会更新对应文档信息,这实际上更像是对原索引文件的一种替换并从新进行索引。

3、响应

{
  "_index":   "website",
  "_type":    "blog",
  "_id":      "1",
  "_version": 2
  "created":  false
}

修改后版本号_version增加

4、update关键字
使用_update关键字指令对文档进行更新是更好的一种方式。
例如:

POST /website/blog/1/_update
{
   "doc" : {
      "tags" : [ "testing" ],
      "views": 0
   }
}

在此示例中,我们通过在url后面追加_update进行文档更新,同时传递我们需要更新的内容。
此处为文档/website/blog/1添加了tags views和对应的值。

5、脚本部分更新文档

脚本更新同样为文档的更新提供了便捷,处理更新也变得更加灵活,此处只做简单记录。

POST /website/blog/1/_update
{
   "script" : "ctx._source.views+=1"
}

通过关键字script进行脚本的定义。

四、删除

1、语法

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

2、示例

DELETE /website/blog/123

删除/website/blog/123文档

3、响应

{
  "found" :    true,
  "_index" :   "website",
  "_type" :    "blog",
  "_id" :      "123",
  "_version" : 3
}

如果删除文档不存在,则found值为false


转自:https://www.jianshu.com/p/a172c67bdd3e

posted @ 2020-02-13 07:59  风云_就是她了  阅读(375)  评论(0编辑  收藏  举报