Py学习  »  Elasticsearch

ElasticSearch文档操作

缘来是你ylh • 5 年前 • 148 次点击  

本节我们来讲解一下ES中文档的相关操作

一:索引/更新文档

ES中索引和更新文档都是PUT操作。

PUT /{IndexName}/{TypeName}/{ID}

比如我又一条测试文档如下:

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "user",
        "_type" : "introduce",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "name" : "jack",
          "age" : 20,
          "gender" : "male"
        }
      }
    ]
  }
}

索引一条新文档

PUT /user/introduce/2
{
   "name":"lucy",
   "age":18,
   "gender":"female"
}

执行检索GET /user/introduce/_search?pretty查看文档

......
{
  "_index" : "user",
  "_type" : "introduce",
  "_id" : "2",
  "_score" : 1.0,
  "_source" : {
    "name" : "lucy",
    "age" : 18,
    "gender" : "female"
  }
},
{
  "_index" : "user",
  "_type" : "introduce",
  "_id" : "1",
  "_score" : 1.0,
  "_source" : {
    "name" : "jack",
    "age" : 20,
    "gender" : "male"
  }
}
......

这时候就插入了索引了一条新的文档了,接下来我们更新一条文档试试

PUT /user/introduce/1
{
   "name":"jone"
}
//返回
{
  "_index" : "user",
  "_type" : "introduce",
  "_id" : "1",
  "_version" : 4,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 3,
  "_primary_term" : 1
}

注意到 result变为了updated

再次执行检索GET /user/introduce/_search?pretty查看文档

........
"hits" : [
      {
        "_index" : "user",
        "_type" : "introduce",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "name" : "lucy",
          "age" : 18,
          "gender" : "female"
        }
      },
      {
        "_index" : "user",
        "_type" : "introduce",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "name" : "jone"
        }
      }
    ]
.......

注意到没有,_id为1的文档里面只有name一个字段了,agegender都没了。这说明PUT是对整个文档更新而不是文档中的某一个或某几个字段更新

文档局部字段更新POST

我先还原数据,然后再对某几个字段更新

POST /{IndexName}/{TypeName}/{ID}/_update
{
    "doc":{}
}
POST /user/introduce/1/_update
{
   "doc":{
      "name":"jone",
      "age":22
   }
}

POST也可以创建一个文档

POST /user/introduce?pretty
{
  "age":20
}

//返回
{
  "_index" : "user",
  "_type" : "introduce",
  "_id" : "VXetwmkBA0w1SMUATD7Z",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}

系统会自动分配_id这一点和MongoDB是一样的

二:删除文档

DELETE /{IndexName}/{TypeName}/{ID}?pretty
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/31077
 
148 次点击