新增文档

PUT study/blog/1
{
  "id":1,
  "title":"Elasticsearch简介",
  "author":"kyle",
  "content":"Elasticsearch是一个基于Lucene的搜索引擎"
}
//返回
{
  "_index" : "study",
  "_type" : "blog",
  "_id" : "1",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}

## 未指定文档ID
POST study/blog
{
  "id":3,
  "title":"Elasticsearch简介1",
  "author":"kyle1",
  "content":"Elasticsearch是一个基于Lucene的搜索引擎"
}
//返回
{
  "_index" : "study",
  "_type" : "blog",
  "_id" : "vZoiiWwBWQWPkkfk1k9n",
  "_version" : 1,
  "result" : "created",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 0,
  "_primary_term" : 1
}

更新文档

文档在Elasticsearch中是不可变的,不能修改。如果我们需要修改文档,Elasticsearch实际上重建新文档替换掉旧文档

# 更新文档id为2的文档
POST /blog/segmentfault/2
{
  "id":2,
  "title":"Git简介",
  "author":"hahaha",
  "content":"Git是一个分布式版本控制软件"
}
//返回
{
  "_index": "blog",
  "_type": "segmentfault",
  "_id": "2",
  "_version": 2,
  "result": "updated",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 1,
  "_primary_term": 1
}

## 字段更新
POST /blog/segmentfault/2/_update
{
  "script": {
    "source": "ctx._source.content=\"GIT是一个开源的分布式版本控制软件\""  
  }
}
{
  "_index": "blog",
  "_type": "segmentfault",
  "_id": "2",
  "_version": 3,
  "result": "updated",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 2,
  "_primary_term": 1
}
## 查询更新
POST blog/_update_by_query
{
  "script": {
    "source": "ctx._source.category=params.category",
    "lang":"painless",
    "params":{"category":"git"}
  },
  "query":{
    "term": {"title":"git"}
  }
}

删除文档

DELETE /blog/segmentfault/2
//返回
{
  "_index": "blog",
  "_type": "segmentfault",
  "_id": "2",
  "_version": 7,
  "result": "deleted",
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "_seq_no": 6,
  "_primary_term": 1
}

文档搜索

  • 最简单的空查询

    GET boss/_search
    //返回
    {
      "took" : 10,//告诉我们执行整个搜索请求耗费了多少毫秒
      "timed_out" : false,//是否超时
      "_shards" : {//查询中参与分片的总数,以及这些分片成功了多少个失败了多少个
        "total" : 5,
        "successful" : 5,
        "skipped" : 0,
        "failed" : 0
      },
       
      "hits" : {//查询结果中最重要的部分
        "total" : 240090,//查询总共匹配到记录数
        "max_score" : 1.0,
        "hits" : [//一般会返回匹配的前十条记录
          {...},
          {...},
          {...},
          {...},
          {...},
          {...},
          {...},
          {...},
          {...},
          {...}
            }
          }
        ]
      }
    }
    
  • 分页查询

    Elasticsearch 接受 from 和 size 参数。显示应该跳过的初始结果数量,默认是 0

    GET /_search?size=5&from=5
    或者在查询语句中设置
    GET /_search
    {
     "from":0,
     "size":2
    }